From bb018fc46cac48fd51675dfbbeb8d9b3b204fdc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 26 Sep 2024 19:17:21 +0200 Subject: [PATCH 001/932] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors,=20rem?= =?UTF-8?q?ove=20Fine.dev=20(#12271)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 - docs/en/data/sponsors.yml | 3 --- docs/en/overrides/main.html | 6 ------ 3 files changed, 10 deletions(-) diff --git a/README.md b/README.md index 3b01b713a..f274265de 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,6 @@ The key features are: - diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index d96646fb3..6db9c509a 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -26,9 +26,6 @@ gold: - url: https://zuplo.link/fastapi-gh title: 'Zuplo: Scale, Protect, Document, and Monetize your FastAPI' img: https://fastapi.tiangolo.com/img/sponsors/zuplo.png - - url: https://fine.dev?ref=fastapibadge - title: "Fine's AI FastAPI Workflow: Effortlessly Deploy and Integrate FastAPI into Your Project" - img: https://fastapi.tiangolo.com/img/sponsors/fine.png - url: https://liblab.com?utm_source=fastapi title: liblab - Generate SDKs from FastAPI img: https://fastapi.tiangolo.com/img/sponsors/liblab.png diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 463c5af3b..462907e7c 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -76,12 +76,6 @@ -
- - - - -
From 847296e885ed83bc333b6cc0a3000d6242083b87 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 26 Sep 2024 17:17:48 +0000 Subject: [PATCH 002/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8a6f2d8be..885112a6a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -22,6 +22,7 @@ hide: ### Internal +* 🔧 Update sponsors, remove Fine.dev. PR [#12271](https://github.com/fastapi/fastapi/pull/12271) by [@tiangolo](https://github.com/tiangolo). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12253](https://github.com/fastapi/fastapi/pull/12253) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * ✏️ Fix docstring typos in http security. PR [#12223](https://github.com/fastapi/fastapi/pull/12223) by [@albertvillanova](https://github.com/albertvillanova). From f0ebae6e9ec1fdbef7720968ee9eadf5d9ad8045 Mon Sep 17 00:00:00 2001 From: Anderson Rocha Date: Fri, 4 Oct 2024 11:55:49 +0100 Subject: [PATCH 003/932] =?UTF-8?q?=20=F0=9F=8C=90=20Update=20Portuguese?= =?UTF-8?q?=20translation=20for=20`docs/pt/docs/advanced/security/http-bas?= =?UTF-8?q?ic-auth.md`=20(#12275)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/advanced/security/http-basic-auth.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/pt/docs/advanced/security/http-basic-auth.md b/docs/pt/docs/advanced/security/http-basic-auth.md index 12b8ab01c..103d622c7 100644 --- a/docs/pt/docs/advanced/security/http-basic-auth.md +++ b/docs/pt/docs/advanced/security/http-basic-auth.md @@ -62,7 +62,7 @@ Utilize uma dependência para verificar se o usuário e a senha estão corretos. Para isso, utilize o módulo padrão do Python `secrets` para verificar o usuário e senha. -O `secrets.compare_digest()` necessita receber `bytes` ou `str` que possuem apenas caracteres ASCII (os em Inglês). Isso significa que não funcionaria com caracteres como o `á`, como em `Sebastián`. +O `secrets.compare_digest()` necessita receber `bytes` ou `str` que possuem apenas caracteres ASCII (os em inglês). Isso significa que não funcionaria com caracteres como o `á`, como em `Sebastián`. Para lidar com isso, primeiramente nós convertemos o `username` e o `password` para `bytes`, codificando-os com UTF-8. @@ -106,11 +106,11 @@ if not (credentials.username == "stanleyjobson") or not (credentials.password == ... ``` -Porém ao utilizar o `secrets.compare_digest()`, isso estará seguro contra um tipo de ataque chamado "ataque de temporização (timing attacks)". +Porém, ao utilizar o `secrets.compare_digest()`, isso estará seguro contra um tipo de ataque chamado "timing attacks" (ataques de temporização). ### Ataques de Temporização -Mas o que é um "ataque de temporização"? +Mas o que é um "timing attack" (ataque de temporização)? Vamos imaginar que alguns invasores estão tentando adivinhar o usuário e a senha. @@ -125,7 +125,7 @@ if "johndoe" == "stanleyjobson" and "love123" == "swordfish": Mas no exato momento que o Python compara o primeiro `j` em `johndoe` contra o primeiro `s` em `stanleyjobson`, ele retornará `False`, porque ele já sabe que aquelas duas strings não são a mesma, pensando que "não existe a necessidade de desperdiçar mais poder computacional comparando o resto das letras". E a sua aplicação dirá "Usuário ou senha incorretos". -Mas então os invasores vão tentar com o usuário `stanleyjobsox` e a senha `love123`. +Então os invasores vão tentar com o usuário `stanleyjobsox` e a senha `love123`. E a sua aplicação faz algo como: @@ -134,11 +134,11 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": ... ``` -O Python terá que comparar todo o `stanleyjobso` tanto em `stanleyjobsox` como em `stanleyjobson` antes de perceber que as strings não são a mesma. Então isso levará alguns microsegundos a mais para retornar "Usuário ou senha incorretos". +O Python terá que comparar todo o `stanleyjobso` tanto em `stanleyjobsox` como em `stanleyjobson` antes de perceber que as strings não são a mesma. Então isso levará alguns microssegundos a mais para retornar "Usuário ou senha incorretos". #### O tempo para responder ajuda os invasores -Neste ponto, ao perceber que o servidor demorou alguns microsegundos a mais para enviar o retorno "Usuário ou senha incorretos", os invasores irão saber que eles acertaram _alguma coisa_, algumas das letras iniciais estavam certas. +Neste ponto, ao perceber que o servidor demorou alguns microssegundos a mais para enviar o retorno "Usuário ou senha incorretos", os invasores irão saber que eles acertaram _alguma coisa_, algumas das letras iniciais estavam certas. E eles podem tentar de novo sabendo que provavelmente é algo mais parecido com `stanleyjobsox` do que com `johndoe`. @@ -150,16 +150,16 @@ Mas fazendo isso, em alguns minutos ou horas os invasores teriam adivinhado o us #### Corrija com o `secrets.compare_digest()` -Mas em nosso código nós estamos utilizando o `secrets.compare_digest()`. +Mas em nosso código já estamos utilizando o `secrets.compare_digest()`. Resumindo, levará o mesmo tempo para comparar `stanleyjobsox` com `stanleyjobson` do que comparar `johndoe` com `stanleyjobson`. E o mesmo para a senha. -Deste modo, ao utilizar `secrets.compare_digest()` no código de sua aplicação, ela esterá a salvo contra toda essa gama de ataques de segurança. +Deste modo, ao utilizar `secrets.compare_digest()` no código de sua aplicação, ela estará a salvo contra toda essa gama de ataques de segurança. ### Retorne o erro -Depois de detectar que as credenciais estão incorretas, retorne um `HTTPException` com o status 401 (o mesmo retornado quando nenhuma credencial foi informada) e adicione o cabeçalho `WWW-Authenticate` para fazer com que o navegador mostre o prompt de login novamente: +Após detectar que as credenciais estão incorretas, retorne um `HTTPException` com o status 401 (o mesmo retornado quando nenhuma credencial foi informada) e adicione o cabeçalho `WWW-Authenticate` para fazer com que o navegador mostre o prompt de login novamente: //// tab | Python 3.9+ From 919721ce8d08c04e5dbf657481502539a92ddad0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 10:56:12 +0000 Subject: [PATCH 004/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 885112a6a..242981548 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Update Portuguese translation for `docs/pt/docs/advanced/security/http-basic-auth.md`. PR [#12275](https://github.com/fastapi/fastapi/pull/12275) by [@andersonrocha0](https://github.com/andersonrocha0). * 🌐 Add Portuguese translation for `docs/pt/docs/deployment/cloud.md`. PR [#12217](https://github.com/fastapi/fastapi/pull/12217) by [@marcelomarkus](https://github.com/marcelomarkus). * ✏️ Fix typo in `docs/es/docs/python-types.md`. PR [#12235](https://github.com/fastapi/fastapi/pull/12235) by [@JavierSanchezCastro](https://github.com/JavierSanchezCastro). * 🌐 Add Dutch translation for `docs/nl/docs/environment-variables.md`. PR [#12200](https://github.com/fastapi/fastapi/pull/12200) by [@maxscheijen](https://github.com/maxscheijen). From 0030f1749e4e74a4cfd58f59d85f7c4c279d239d Mon Sep 17 00:00:00 2001 From: kkotipy Date: Fri, 4 Oct 2024 19:57:17 +0900 Subject: [PATCH 005/932] =?UTF-8?q?=F0=9F=8C=90=20Fix=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/tutorial/index.md`=20(#12278)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/tutorial/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ko/docs/tutorial/index.md b/docs/ko/docs/tutorial/index.md index d00a942f0..a148bc76e 100644 --- a/docs/ko/docs/tutorial/index.md +++ b/docs/ko/docs/tutorial/index.md @@ -30,7 +30,7 @@ $ uvicorn main:app --reload 코드를 작성하거나 복사, 편집할 때, 로컬 환경에서 실행하는 것을 **강력히 권장**합니다. -로컬 편집기에서 사용한다면, 모든 타입 검사와 자동완성 등 작성해야 하는 코드가 얼마나 적은지 보면서 FastAPI의 비로소 경험할 수 있습니다. +로컬 편집기에서 사용한다면, 모든 타입 검사와 자동완성 등 작성해야 하는 코드가 얼마나 적은지 보면서 FastAPI의 이점을 비로소 경험할 수 있습니다. --- From ca68c99a6eebec8d665517a88e34a514255aa36b Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Fri, 4 Oct 2024 07:58:03 -0300 Subject: [PATCH 006/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Portuguese=20tr?= =?UTF-8?q?anslation=20for=20`docs/pt/docs/tutorial/cookie-params.md`=20(#?= =?UTF-8?q?12297)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/cookie-params.md | 109 +++++++++++++++++++++++-- 1 file changed, 103 insertions(+), 6 deletions(-) diff --git a/docs/pt/docs/tutorial/cookie-params.md b/docs/pt/docs/tutorial/cookie-params.md index caed17632..bb59dcd2c 100644 --- a/docs/pt/docs/tutorial/cookie-params.md +++ b/docs/pt/docs/tutorial/cookie-params.md @@ -6,21 +6,118 @@ Você pode definir parâmetros de Cookie da mesma maneira que define paramêtros Primeiro importe `Cookie`: +//// tab | Python 3.10+ + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + ```Python hl_lines="3" -{!../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="3" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// + ## Declare parâmetros de `Cookie` Então declare os paramêtros de cookie usando a mesma estrutura que em `Path` e `Query`. -O primeiro valor é o valor padrão, você pode passar todas as validações adicionais ou parâmetros de anotação: +Você pode definir o valor padrão, assim como todas as validações extras ou parâmetros de anotação: + + +//// tab | Python 3.10+ + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ ```Python hl_lines="9" -{!../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` -/// note | "Detalhes Técnicos" +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10" +{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="9" +{!> ../../../docs_src/cookie_params/tutorial001.py!} +``` + +//// + +/// note | Detalhes Técnicos `Cookie` é uma classe "irmã" de `Path` e `Query`. Ela também herda da mesma classe em comum `Param`. @@ -28,9 +125,9 @@ Mas lembre-se que quando você importa `Query`, `Path`, `Cookie` e outras de `fa /// -/// info | "Informação" +/// info | Informação -Para declarar cookies, você precisa usar `Cookie`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta. +Para declarar cookies, você precisa usar `Cookie`, pois caso contrário, os parâmetros seriam interpretados como parâmetros de consulta. /// From ed477ee8873219398289b0ef7e2a750151410a0b Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 10:58:40 +0000 Subject: [PATCH 007/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 242981548..d7482cc46 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Fix Korean translation for `docs/ko/docs/tutorial/index.md`. PR [#12278](https://github.com/fastapi/fastapi/pull/12278) by [@kkotipy](https://github.com/kkotipy). * 🌐 Update Portuguese translation for `docs/pt/docs/advanced/security/http-basic-auth.md`. PR [#12275](https://github.com/fastapi/fastapi/pull/12275) by [@andersonrocha0](https://github.com/andersonrocha0). * 🌐 Add Portuguese translation for `docs/pt/docs/deployment/cloud.md`. PR [#12217](https://github.com/fastapi/fastapi/pull/12217) by [@marcelomarkus](https://github.com/marcelomarkus). * ✏️ Fix typo in `docs/es/docs/python-types.md`. PR [#12235](https://github.com/fastapi/fastapi/pull/12235) by [@JavierSanchezCastro](https://github.com/JavierSanchezCastro). From 69921b463ef1669807cc2d793cc9f0193da403cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Pedro=20Pereira=20Holanda?= Date: Fri, 4 Oct 2024 08:00:29 -0300 Subject: [PATCH 008/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/response-directly.md`=20(?= =?UTF-8?q?#12266)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/response-directly.md | 70 ++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 docs/pt/docs/advanced/response-directly.md diff --git a/docs/pt/docs/advanced/response-directly.md b/docs/pt/docs/advanced/response-directly.md new file mode 100644 index 000000000..fc571d39b --- /dev/null +++ b/docs/pt/docs/advanced/response-directly.md @@ -0,0 +1,70 @@ +# Retornando uma Resposta Diretamente + +Quando você cria uma *operação de rota* no **FastAPI** você pode retornar qualquer dado nela: um dicionário (`dict`), uma lista (`list`), um modelo do Pydantic ou do seu banco de dados, etc. + +Por padrão, o **FastAPI** irá converter automaticamente o valor do retorno para JSON utilizando o `jsonable_encoder` explicado em [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank}. + +Então, por baixo dos panos, ele incluiria esses dados compatíveis com JSON (e.g. um `dict`) dentro de uma `JSONResponse` que é utilizada para enviar uma resposta para o cliente. + +Mas você pode retornar a `JSONResponse` diretamente nas suas *operações de rota*. + +Pode ser útil para retornar cabeçalhos e cookies personalizados, por exemplo. + +## Retornando uma `Response` + +Na verdade, você pode retornar qualquer `Response` ou subclasse dela. + +/// tip | Dica + +A própria `JSONResponse` é uma subclasse de `Response`. + +/// + +E quando você retorna uma `Response`, o **FastAPI** vai repassá-la diretamente. + +Ele não vai fazer conversões de dados com modelos do Pydantic, não irá converter a tipagem de nenhum conteúdo, etc. + +Isso te dá bastante flexibilidade. Você pode retornar qualquer tipo de dado, sobrescrever qualquer declaração e validação nos dados, etc. + +## Utilizando o `jsonable_encoder` em uma `Response` + +Como o **FastAPI** não realiza nenhuma mudança na `Response` que você retorna, você precisa garantir que o conteúdo dela está pronto para uso. + +Por exemplo, você não pode colocar um modelo do Pydantic em uma `JSONResponse` sem antes convertê-lo em um `dict` com todos os tipos de dados (como `datetime`, `UUID`, etc) convertidos para tipos compatíveis com JSON. + +Para esses casos, você pode usar o `jsonable_encoder` para converter seus dados antes de repassá-los para a resposta: + +```Python hl_lines="6-7 21-22" +{!../../../docs_src/response_directly/tutorial001.py!} +``` + +/// note | Detalhes Técnicos + +Você também pode utilizar `from starlette.responses import JSONResponse`. + +**FastAPI** utiliza a mesma `starlette.responses` como `fastapi.responses` apenas como uma conveniência para você, desenvolvedor. Mas maior parte das respostas disponíveis vem diretamente do Starlette. + +/// + +## Retornando uma `Response` + +O exemplo acima mostra todas as partes que você precisa, mas ainda não é muito útil, já que você poderia ter retornado o `item` diretamente, e o **FastAPI** colocaria em uma `JSONResponse` para você, convertendo em um `dict`, etc. Tudo isso por padrão. + +Agora, vamos ver como você pode usar isso para retornar uma resposta personalizada. + +Vamos dizer quer retornar uma resposta XML. + +Você pode colocar o seu conteúdo XML em uma string, colocar em uma `Response`, e retorná-lo: + +```Python hl_lines="1 18" +{!../../../docs_src/response_directly/tutorial002.py!} +``` + +## Notas + +Quando você retorna uma `Response` diretamente os dados não são validados, convertidos (serializados) ou documentados automaticamente. + +Mas você ainda pode documentar como descrito em [Retornos Adicionais no OpenAPI +](additional-responses.md){.internal-link target=_blank}. + +Você pode ver nas próximas seções como usar/declarar essas `Responses` customizadas enquanto mantém a conversão e documentação automática dos dados. From 98d190f780691fa3a8cc3abdc9805f05e6a1b751 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:01:25 +0000 Subject: [PATCH 009/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d7482cc46..f66e72753 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Update Portuguese translation for `docs/pt/docs/tutorial/cookie-params.md`. PR [#12297](https://github.com/fastapi/fastapi/pull/12297) by [@ceb10n](https://github.com/ceb10n). * 🌐 Fix Korean translation for `docs/ko/docs/tutorial/index.md`. PR [#12278](https://github.com/fastapi/fastapi/pull/12278) by [@kkotipy](https://github.com/kkotipy). * 🌐 Update Portuguese translation for `docs/pt/docs/advanced/security/http-basic-auth.md`. PR [#12275](https://github.com/fastapi/fastapi/pull/12275) by [@andersonrocha0](https://github.com/andersonrocha0). * 🌐 Add Portuguese translation for `docs/pt/docs/deployment/cloud.md`. PR [#12217](https://github.com/fastapi/fastapi/pull/12217) by [@marcelomarkus](https://github.com/marcelomarkus). From b1c03ba57e50c25c6e40501bb87ce4063a91e885 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:03:27 +0000 Subject: [PATCH 010/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f66e72753..c871e1c71 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-directly.md`. PR [#12266](https://github.com/fastapi/fastapi/pull/12266) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Update Portuguese translation for `docs/pt/docs/tutorial/cookie-params.md`. PR [#12297](https://github.com/fastapi/fastapi/pull/12297) by [@ceb10n](https://github.com/ceb10n). * 🌐 Fix Korean translation for `docs/ko/docs/tutorial/index.md`. PR [#12278](https://github.com/fastapi/fastapi/pull/12278) by [@kkotipy](https://github.com/kkotipy). * 🌐 Update Portuguese translation for `docs/pt/docs/advanced/security/http-basic-auth.md`. PR [#12275](https://github.com/fastapi/fastapi/pull/12275) by [@andersonrocha0](https://github.com/andersonrocha0). From fa50b0c73cbf2bc298c596dda8f79e4789608341 Mon Sep 17 00:00:00 2001 From: marcelomarkus Date: Fri, 4 Oct 2024 08:03:46 -0300 Subject: [PATCH 011/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/how-to/conditional-openapi.md`=20(?= =?UTF-8?q?#12221)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/how-to/conditional-openapi.md | 58 ++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 docs/pt/docs/how-to/conditional-openapi.md diff --git a/docs/pt/docs/how-to/conditional-openapi.md b/docs/pt/docs/how-to/conditional-openapi.md new file mode 100644 index 000000000..cfa652fa5 --- /dev/null +++ b/docs/pt/docs/how-to/conditional-openapi.md @@ -0,0 +1,58 @@ +# OpenAPI condicional + +Se necessário, você pode usar configurações e variáveis ​​de ambiente para configurar o OpenAPI condicionalmente, dependendo do ambiente, e até mesmo desativá-lo completamente. + +## Sobre segurança, APIs e documentos + +Ocultar suas interfaces de usuário de documentação na produção *não deveria* ser a maneira de proteger sua API. + +Isso não adiciona nenhuma segurança extra à sua API; as *operações de rotas* ainda estarão disponíveis onde estão. + +Se houver uma falha de segurança no seu código, ela ainda existirá. + +Ocultar a documentação apenas torna mais difícil entender como interagir com sua API e pode dificultar sua depuração na produção. Pode ser considerado simplesmente uma forma de Segurança através da obscuridade. + +Se você quiser proteger sua API, há várias coisas melhores que você pode fazer, por exemplo: + +* Certifique-se de ter modelos Pydantic bem definidos para seus corpos de solicitação e respostas. +* Configure quaisquer permissões e funções necessárias usando dependências. +* Nunca armazene senhas em texto simples, apenas hashes de senha. +* Implemente e use ferramentas criptográficas bem conhecidas, como tokens JWT e Passlib, etc. +* Adicione controles de permissão mais granulares com escopos OAuth2 quando necessário. +* ...etc. + +No entanto, você pode ter um caso de uso muito específico em que realmente precisa desabilitar a documentação da API para algum ambiente (por exemplo, para produção) ou dependendo de configurações de variáveis ​​de ambiente. + +## OpenAPI condicional com configurações e variáveis ​​de ambiente + +Você pode usar facilmente as mesmas configurações do Pydantic para configurar sua OpenAPI gerada e as interfaces de usuário de documentos. + +Por exemplo: + +```Python hl_lines="6 11" +{!../../../docs_src/conditional_openapi/tutorial001.py!} +``` + +Aqui declaramos a configuração `openapi_url` com o mesmo padrão de `"/openapi.json"`. + +E então o usamos ao criar o aplicativo `FastAPI`. + +Então você pode desabilitar o OpenAPI (incluindo os documentos da interface do usuário) definindo a variável de ambiente `OPENAPI_URL` como uma string vazia, como: + +
+ +```console +$ OPENAPI_URL= uvicorn main:app + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Então, se você acessar as URLs em `/openapi.json`, `/docs` ou `/redoc`, você receberá apenas um erro `404 Não Encontrado` como: + +```JSON +{ + "detail": "Not Found" +} +``` From 17e234452abc3dce895e2e2e93c48f856dd43da3 Mon Sep 17 00:00:00 2001 From: marcelomarkus Date: Fri, 4 Oct 2024 08:04:50 -0300 Subject: [PATCH 012/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/deployment/concepts.md`=20(#12219)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/deployment/concepts.md | 321 ++++++++++++++++++++++++++++ 1 file changed, 321 insertions(+) create mode 100644 docs/pt/docs/deployment/concepts.md diff --git a/docs/pt/docs/deployment/concepts.md b/docs/pt/docs/deployment/concepts.md new file mode 100644 index 000000000..20513c366 --- /dev/null +++ b/docs/pt/docs/deployment/concepts.md @@ -0,0 +1,321 @@ +# Conceitos de Implantações + +Ao implantar um aplicativo **FastAPI**, ou na verdade, qualquer tipo de API da web, há vários conceitos com os quais você provavelmente se importa e, usando-os, você pode encontrar a maneira **mais apropriada** de **implantar seu aplicativo**. + +Alguns dos conceitos importantes são: + +* Segurança - HTTPS +* Executando na inicialização +* Reinicializações +* Replicação (o número de processos em execução) +* Memória +* Etapas anteriores antes de iniciar + +Veremos como eles afetariam as **implantações**. + +No final, o principal objetivo é ser capaz de **atender seus clientes de API** de uma forma **segura**, **evitar interrupções** e usar os **recursos de computação** (por exemplo, servidores remotos/máquinas virtuais) da forma mais eficiente possível. 🚀 + +Vou lhe contar um pouco mais sobre esses **conceitos** aqui, e espero que isso lhe dê a **intuição** necessária para decidir como implantar sua API em ambientes muito diferentes, possivelmente até mesmo em **futuros** ambientes que ainda não existem. + +Ao considerar esses conceitos, você será capaz de **avaliar e projetar** a melhor maneira de implantar **suas próprias APIs**. + +Nos próximos capítulos, darei a você mais **receitas concretas** para implantar aplicativos FastAPI. + +Mas por enquanto, vamos verificar essas importantes **ideias conceituais**. Esses conceitos também se aplicam a qualquer outro tipo de API da web. 💡 + +## Segurança - HTTPS + +No [capítulo anterior sobre HTTPS](https.md){.internal-link target=_blank} aprendemos como o HTTPS fornece criptografia para sua API. + +Também vimos que o HTTPS normalmente é fornecido por um componente **externo** ao seu servidor de aplicativos, um **Proxy de terminação TLS**. + +E tem que haver algo responsável por **renovar os certificados HTTPS**, pode ser o mesmo componente ou pode ser algo diferente. + +### Ferramentas de exemplo para HTTPS + +Algumas das ferramentas que você pode usar como um proxy de terminação TLS são: + +* Traefik + * Lida automaticamente com renovações de certificados ✨ +* Caddy + * Lida automaticamente com renovações de certificados ✨ +* Nginx + * Com um componente externo como o Certbot para renovações de certificados +* HAProxy + * Com um componente externo como o Certbot para renovações de certificados +* Kubernetes com um controlador Ingress como o Nginx + * Com um componente externo como cert-manager para renovações de certificados +* Gerenciado internamente por um provedor de nuvem como parte de seus serviços (leia abaixo 👇) + +Outra opção é que você poderia usar um **serviço de nuvem** que faz mais do trabalho, incluindo a configuração de HTTPS. Ele pode ter algumas restrições ou cobrar mais, etc. Mas, nesse caso, você não teria que configurar um Proxy de terminação TLS sozinho. + +Mostrarei alguns exemplos concretos nos próximos capítulos. + +--- + +Os próximos conceitos a serem considerados são todos sobre o programa que executa sua API real (por exemplo, Uvicorn). + +## Programa e Processo + +Falaremos muito sobre o "**processo**" em execução, então é útil ter clareza sobre o que ele significa e qual é a diferença com a palavra "**programa**". + +### O que é um Programa + +A palavra **programa** é comumente usada para descrever muitas coisas: + +* O **código** que você escreve, os **arquivos Python**. +* O **arquivo** que pode ser **executado** pelo sistema operacional, por exemplo: `python`, `python.exe` ou `uvicorn`. +* Um programa específico enquanto está **em execução** no sistema operacional, usando a CPU e armazenando coisas na memória. Isso também é chamado de **processo**. + +### O que é um Processo + +A palavra **processo** normalmente é usada de forma mais específica, referindo-se apenas ao que está sendo executado no sistema operacional (como no último ponto acima): + +* Um programa específico enquanto está **em execução** no sistema operacional. + * Isso não se refere ao arquivo, nem ao código, refere-se **especificamente** à coisa que está sendo **executada** e gerenciada pelo sistema operacional. +* Qualquer programa, qualquer código, **só pode fazer coisas** quando está sendo **executado**. Então, quando há um **processo em execução**. +* O processo pode ser **terminado** (ou "morto") por você, ou pelo sistema operacional. Nesse ponto, ele para de rodar/ser executado, e ele **não pode mais fazer coisas**. +* Cada aplicativo que você tem em execução no seu computador tem algum processo por trás dele, cada programa em execução, cada janela, etc. E normalmente há muitos processos em execução **ao mesmo tempo** enquanto um computador está ligado. +* Pode haver **vários processos** do **mesmo programa** em execução ao mesmo tempo. + +Se você verificar o "gerenciador de tarefas" ou o "monitor do sistema" (ou ferramentas semelhantes) no seu sistema operacional, poderá ver muitos desses processos em execução. + +E, por exemplo, você provavelmente verá que há vários processos executando o mesmo programa de navegador (Firefox, Chrome, Edge, etc.). Eles normalmente executam um processo por aba, além de alguns outros processos extras. + + + +--- + +Agora que sabemos a diferença entre os termos **processo** e **programa**, vamos continuar falando sobre implantações. + +## Executando na inicialização + +Na maioria dos casos, quando você cria uma API web, você quer que ela esteja **sempre em execução**, ininterrupta, para que seus clientes possam sempre acessá-la. Isso é claro, a menos que você tenha um motivo específico para querer que ela seja executada somente em certas situações, mas na maioria das vezes você quer que ela esteja constantemente em execução e **disponível**. + +### Em um servidor remoto + +Ao configurar um servidor remoto (um servidor em nuvem, uma máquina virtual, etc.), a coisa mais simples que você pode fazer é usar `fastapi run` (que usa Uvicorn) ou algo semelhante, manualmente, da mesma forma que você faz ao desenvolver localmente. + +E funcionará e será útil **durante o desenvolvimento**. + +Mas se sua conexão com o servidor for perdida, o **processo em execução** provavelmente morrerá. + +E se o servidor for reiniciado (por exemplo, após atualizações ou migrações do provedor de nuvem), você provavelmente **não notará**. E por causa disso, você nem saberá que precisa reiniciar o processo manualmente. Então, sua API simplesmente permanecerá inativa. 😱 + +### Executar automaticamente na inicialização + +Em geral, você provavelmente desejará que o programa do servidor (por exemplo, Uvicorn) seja iniciado automaticamente na inicialização do servidor e, sem precisar de nenhuma **intervenção humana**, tenha um processo sempre em execução com sua API (por exemplo, Uvicorn executando seu aplicativo FastAPI). + +### Programa separado + +Para conseguir isso, você normalmente terá um **programa separado** que garantiria que seu aplicativo fosse executado na inicialização. E em muitos casos, ele também garantiria que outros componentes ou aplicativos também fossem executados, por exemplo, um banco de dados. + +### Ferramentas de exemplo para executar na inicialização + +Alguns exemplos de ferramentas que podem fazer esse trabalho são: + +* Docker +* Kubernetes +* Docker Compose +* Docker em Modo Swarm +* Systemd +* Supervisor +* Gerenciado internamente por um provedor de nuvem como parte de seus serviços +* Outros... + +Darei exemplos mais concretos nos próximos capítulos. + +## Reinicializações + +Semelhante a garantir que seu aplicativo seja executado na inicialização, você provavelmente também deseja garantir que ele seja **reiniciado** após falhas. + +### Nós cometemos erros + +Nós, como humanos, cometemos **erros** o tempo todo. O software quase *sempre* tem **bugs** escondidos em lugares diferentes. 🐛 + +E nós, como desenvolvedores, continuamos aprimorando o código à medida que encontramos esses bugs e implementamos novos recursos (possivelmente adicionando novos bugs também 😅). + +### Pequenos erros são tratados automaticamente + +Ao criar APIs da web com FastAPI, se houver um erro em nosso código, o FastAPI normalmente o conterá na única solicitação que acionou o erro. 🛡 + +O cliente receberá um **Erro Interno do Servidor 500** para essa solicitação, mas o aplicativo continuará funcionando para as próximas solicitações em vez de travar completamente. + +### Erros maiores - Travamentos + +No entanto, pode haver casos em que escrevemos algum código que **trava todo o aplicativo**, fazendo com que o Uvicorn e o Python travem. 💥 + +E ainda assim, você provavelmente não gostaria que o aplicativo permanecesse inativo porque houve um erro em um lugar, você provavelmente quer que ele **continue em execução** pelo menos para as *operações de caminho* que não estão quebradas. + +### Reiniciar após falha + +Mas nos casos com erros realmente graves que travam o **processo** em execução, você vai querer um componente externo que seja responsável por **reiniciar** o processo, pelo menos algumas vezes... + +/// tip | "Dica" + +...Embora se o aplicativo inteiro estiver **travando imediatamente**, provavelmente não faça sentido reiniciá-lo para sempre. Mas nesses casos, você provavelmente notará isso durante o desenvolvimento, ou pelo menos logo após a implantação. + +Então, vamos nos concentrar nos casos principais, onde ele pode travar completamente em alguns casos específicos **no futuro**, e ainda faz sentido reiniciá-lo. + +/// + +Você provavelmente gostaria de ter a coisa responsável por reiniciar seu aplicativo como um **componente externo**, porque a essa altura, o mesmo aplicativo com Uvicorn e Python já havia travado, então não há nada no mesmo código do mesmo aplicativo que possa fazer algo a respeito. + +### Ferramentas de exemplo para reiniciar automaticamente + +Na maioria dos casos, a mesma ferramenta usada para **executar o programa na inicialização** também é usada para lidar com **reinicializações** automáticas. + +Por exemplo, isso poderia ser resolvido por: + +* Docker +* Kubernetes +* Docker Compose +* Docker no Modo Swarm +* Systemd +* Supervisor +* Gerenciado internamente por um provedor de nuvem como parte de seus serviços +* Outros... + +## Replicação - Processos e Memória + +Com um aplicativo FastAPI, usando um programa de servidor como o comando `fastapi` que executa o Uvicorn, executá-lo uma vez em **um processo** pode atender a vários clientes simultaneamente. + +Mas em muitos casos, você desejará executar vários processos de trabalho ao mesmo tempo. + +### Processos Múltiplos - Trabalhadores + +Se você tiver mais clientes do que um único processo pode manipular (por exemplo, se a máquina virtual não for muito grande) e tiver **vários núcleos** na CPU do servidor, você poderá ter **vários processos** em execução com o mesmo aplicativo ao mesmo tempo e distribuir todas as solicitações entre eles. + +Quando você executa **vários processos** do mesmo programa de API, eles são comumente chamados de **trabalhadores**. + +### Processos do Trabalhador e Portas + +Lembra da documentação [Sobre HTTPS](https.md){.internal-link target=_blank} que diz que apenas um processo pode escutar em uma combinação de porta e endereço IP em um servidor? + +Isso ainda é verdade. + +Então, para poder ter **vários processos** ao mesmo tempo, tem que haver um **único processo escutando em uma porta** que então transmite a comunicação para cada processo de trabalho de alguma forma. + +### Memória por Processo + +Agora, quando o programa carrega coisas na memória, por exemplo, um modelo de aprendizado de máquina em uma variável, ou o conteúdo de um arquivo grande em uma variável, tudo isso **consome um pouco da memória (RAM)** do servidor. + +E vários processos normalmente **não compartilham nenhuma memória**. Isso significa que cada processo em execução tem suas próprias coisas, variáveis ​​e memória. E se você estiver consumindo uma grande quantidade de memória em seu código, **cada processo** consumirá uma quantidade equivalente de memória. + +### Memória do servidor + +Por exemplo, se seu código carrega um modelo de Machine Learning com **1 GB de tamanho**, quando você executa um processo com sua API, ele consumirá pelo menos 1 GB de RAM. E se você iniciar **4 processos** (4 trabalhadores), cada um consumirá 1 GB de RAM. Então, no total, sua API consumirá **4 GB de RAM**. + +E se o seu servidor remoto ou máquina virtual tiver apenas 3 GB de RAM, tentar carregar mais de 4 GB de RAM causará problemas. 🚨 + +### Processos Múltiplos - Um Exemplo + +Neste exemplo, há um **Processo Gerenciador** que inicia e controla dois **Processos de Trabalhadores**. + +Este Processo de Gerenciador provavelmente seria o que escutaria na **porta** no IP. E ele transmitiria toda a comunicação para os processos de trabalho. + +Esses processos de trabalho seriam aqueles que executariam seu aplicativo, eles executariam os cálculos principais para receber uma **solicitação** e retornar uma **resposta**, e carregariam qualquer coisa que você colocasse em variáveis ​​na RAM. + + + +E, claro, a mesma máquina provavelmente teria **outros processos** em execução, além do seu aplicativo. + +Um detalhe interessante é que a porcentagem da **CPU usada** por cada processo pode **variar** muito ao longo do tempo, mas a **memória (RAM)** normalmente fica mais ou menos **estável**. + +Se você tiver uma API que faz uma quantidade comparável de cálculos todas as vezes e tiver muitos clientes, então a **utilização da CPU** provavelmente *também será estável* (em vez de ficar constantemente subindo e descendo rapidamente). + +### Exemplos de ferramentas e estratégias de replicação + +Pode haver várias abordagens para conseguir isso, e falarei mais sobre estratégias específicas nos próximos capítulos, por exemplo, ao falar sobre Docker e contêineres. + +A principal restrição a ser considerada é que tem que haver um **único** componente manipulando a **porta** no **IP público**. E então tem que ter uma maneira de **transmitir** a comunicação para os **processos/trabalhadores** replicados. + +Aqui estão algumas combinações e estratégias possíveis: + +* **Uvicorn** com `--workers` + * Um **gerenciador de processos** Uvicorn escutaria no **IP** e na **porta** e iniciaria **vários processos de trabalho Uvicorn**. +* **Kubernetes** e outros **sistemas de contêineres** distribuídos + * Algo na camada **Kubernetes** escutaria no **IP** e na **porta**. A replicação seria por ter **vários contêineres**, cada um com **um processo Uvicorn** em execução. +* **Serviços de nuvem** que cuidam disso para você + * O serviço de nuvem provavelmente **cuidará da replicação para você**. Ele possivelmente deixaria você definir **um processo para executar**, ou uma **imagem de contêiner** para usar, em qualquer caso, provavelmente seria **um único processo Uvicorn**, e o serviço de nuvem seria responsável por replicá-lo. + +/// tip | "Dica" + +Não se preocupe se alguns desses itens sobre **contêineres**, Docker ou Kubernetes ainda não fizerem muito sentido. + +Falarei mais sobre imagens de contêiner, Docker, Kubernetes, etc. em um capítulo futuro: [FastAPI em contêineres - Docker](docker.md){.internal-link target=_blank}. + +/// + +## Etapas anteriores antes de começar + +Há muitos casos em que você deseja executar algumas etapas **antes de iniciar** sua aplicação. + +Por exemplo, você pode querer executar **migrações de banco de dados**. + +Mas na maioria dos casos, você precisará executar essas etapas apenas **uma vez**. + +Portanto, você vai querer ter um **processo único** para executar essas **etapas anteriores** antes de iniciar o aplicativo. + +E você terá que se certificar de que é um único processo executando essas etapas anteriores *mesmo* se depois, você iniciar **vários processos** (vários trabalhadores) para o próprio aplicativo. Se essas etapas fossem executadas por **vários processos**, eles **duplicariam** o trabalho executando-o em **paralelo**, e se as etapas fossem algo delicado como uma migração de banco de dados, elas poderiam causar conflitos entre si. + +Claro, há alguns casos em que não há problema em executar as etapas anteriores várias vezes; nesse caso, é muito mais fácil de lidar. + +/// tip | "Dica" + +Além disso, tenha em mente que, dependendo da sua configuração, em alguns casos você **pode nem precisar de nenhuma etapa anterior** antes de iniciar sua aplicação. + +Nesse caso, você não precisaria se preocupar com nada disso. 🤷 + +/// + +### Exemplos de estratégias de etapas anteriores + +Isso **dependerá muito** da maneira como você **implanta seu sistema** e provavelmente estará conectado à maneira como você inicia programas, lida com reinicializações, etc. + +Aqui estão algumas ideias possíveis: + +* Um "Init Container" no Kubernetes que roda antes do seu app container +* Um script bash que roda os passos anteriores e então inicia seu aplicativo + * Você ainda precisaria de uma maneira de iniciar/reiniciar *aquele* script bash, detectar erros, etc. + +/// tip | "Dica" + +Darei exemplos mais concretos de como fazer isso com contêineres em um capítulo futuro: [FastAPI em contêineres - Docker](docker.md){.internal-link target=_blank}. + +/// + +## Utilização de recursos + +Seu(s) servidor(es) é(são) um **recurso** que você pode consumir ou **utilizar**, com seus programas, o tempo de computação nas CPUs e a memória RAM disponível. + +Quanto dos recursos do sistema você quer consumir/utilizar? Pode ser fácil pensar "não muito", mas, na realidade, você provavelmente vai querer consumir **o máximo possível sem travar**. + +Se você está pagando por 3 servidores, mas está usando apenas um pouco de RAM e CPU, você provavelmente está **desperdiçando dinheiro** 💸, e provavelmente **desperdiçando energia elétrica do servidor** 🌎, etc. + +Nesse caso, seria melhor ter apenas 2 servidores e usar uma porcentagem maior de seus recursos (CPU, memória, disco, largura de banda de rede, etc). + +Por outro lado, se você tem 2 servidores e está usando **100% da CPU e RAM deles**, em algum momento um processo pedirá mais memória, e o servidor terá que usar o disco como "memória" (o que pode ser milhares de vezes mais lento), ou até mesmo **travar**. Ou um processo pode precisar fazer alguma computação e teria que esperar até que a CPU esteja livre novamente. + +Nesse caso, seria melhor obter **um servidor extra** e executar alguns processos nele para que todos tenham **RAM e tempo de CPU suficientes**. + +Também há a chance de que, por algum motivo, você tenha um **pico** de uso da sua API. Talvez ela tenha se tornado viral, ou talvez alguns outros serviços ou bots comecem a usá-la. E você pode querer ter recursos extras para estar seguro nesses casos. + +Você poderia colocar um **número arbitrário** para atingir, por exemplo, algo **entre 50% a 90%** da utilização de recursos. O ponto é que essas são provavelmente as principais coisas que você vai querer medir e usar para ajustar suas implantações. + +Você pode usar ferramentas simples como `htop` para ver a CPU e a RAM usadas no seu servidor ou a quantidade usada por cada processo. Ou você pode usar ferramentas de monitoramento mais complexas, que podem ser distribuídas entre servidores, etc. + +## Recapitular + +Você leu aqui alguns dos principais conceitos que provavelmente precisa ter em mente ao decidir como implantar seu aplicativo: + +* Segurança - HTTPS +* Executando na inicialização +* Reinicializações +* Replicação (o número de processos em execução) +* Memória +* Etapas anteriores antes de iniciar + +Entender essas ideias e como aplicá-las deve lhe dar a intuição necessária para tomar qualquer decisão ao configurar e ajustar suas implantações. 🤓 + +Nas próximas seções, darei exemplos mais concretos de possíveis estratégias que você pode seguir. 🚀 From 304f514ed95107a32e7b1f263003720b9475c580 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:08:00 +0000 Subject: [PATCH 013/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c871e1c71..ca8dcedb0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/conditional-openapi.md`. PR [#12221](https://github.com/fastapi/fastapi/pull/12221) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-directly.md`. PR [#12266](https://github.com/fastapi/fastapi/pull/12266) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Update Portuguese translation for `docs/pt/docs/tutorial/cookie-params.md`. PR [#12297](https://github.com/fastapi/fastapi/pull/12297) by [@ceb10n](https://github.com/ceb10n). * 🌐 Fix Korean translation for `docs/ko/docs/tutorial/index.md`. PR [#12278](https://github.com/fastapi/fastapi/pull/12278) by [@kkotipy](https://github.com/kkotipy). From 5820d4261e2784cfabbe5358015142d71039555a Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:10:09 +0000 Subject: [PATCH 014/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ca8dcedb0..7188a698f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/deployment/concepts.md`. PR [#12219](https://github.com/fastapi/fastapi/pull/12219) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/conditional-openapi.md`. PR [#12221](https://github.com/fastapi/fastapi/pull/12221) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-directly.md`. PR [#12266](https://github.com/fastapi/fastapi/pull/12266) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Update Portuguese translation for `docs/pt/docs/tutorial/cookie-params.md`. PR [#12297](https://github.com/fastapi/fastapi/pull/12297) by [@ceb10n](https://github.com/ceb10n). From 0e7806e3f97ad16a526e77488a72be62359890e1 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Fri, 4 Oct 2024 08:11:41 -0300 Subject: [PATCH 015/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/security/oauth2-scopes.md?= =?UTF-8?q?`=20(#12263)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/advanced/security/oauth2-scopes.md | 786 ++++++++++++++++++ 1 file changed, 786 insertions(+) create mode 100644 docs/pt/docs/advanced/security/oauth2-scopes.md diff --git a/docs/pt/docs/advanced/security/oauth2-scopes.md b/docs/pt/docs/advanced/security/oauth2-scopes.md new file mode 100644 index 000000000..4ad7c807e --- /dev/null +++ b/docs/pt/docs/advanced/security/oauth2-scopes.md @@ -0,0 +1,786 @@ +# Escopos OAuth2 + +Você pode utilizar escopos do OAuth2 diretamente com o **FastAPI**, eles são integrados para funcionar perfeitamente. + +Isso permitiria que você tivesse um sistema de permissionamento mais refinado, seguindo o padrão do OAuth2 integrado na sua aplicação OpenAPI (e as documentações da API). + +OAuth2 com escopos é o mecanismo utilizado por muitos provedores de autenticação, como o Facebook, Google, GitHub, Microsoft, Twitter, etc. Eles utilizam isso para prover permissões específicas para os usuários e aplicações. + +Toda vez que você "se autentica com" Facebook, Google, GitHub, Microsoft, Twitter, aquela aplicação está utilizando o OAuth2 com escopos. + +Nesta seção, você verá como gerenciar a autenticação e autorização com os mesmos escopos do OAuth2 em sua aplicação **FastAPI**. + +/// warning | "Aviso" + +Isso é uma seção mais ou menos avançada. Se você está apenas começando, você pode pular. + +Você não necessariamente precisa de escopos do OAuth2, e você pode lidar com autenticação e autorização da maneira que você achar melhor. + +Mas o OAuth2 com escopos pode ser integrado de maneira fácil em sua API (com OpenAPI) e a sua documentação de API. + +No entando, você ainda aplica estes escopos, ou qualquer outro requisito de segurança/autorização, conforme necessário, em seu código. + +Em muitos casos, OAuth2 com escopos pode ser um exagero. + +Mas se você sabe que precisa, ou está curioso, continue lendo. + +/// + +## Escopos OAuth2 e OpenAPI + +A especificação OAuth2 define "escopos" como uma lista de strings separadas por espaços. + +O conteúdo de cada uma dessas strings pode ter qualquer formato, mas não devem possuir espaços. + +Estes escopos representam "permissões". + +No OpenAPI (e.g. os documentos da API), você pode definir "esquemas de segurança". + +Quando um desses esquemas de segurança utiliza OAuth2, você pode também declarar e utilizar escopos. + +Cada "escopo" é apenas uma string (sem espaços). + +Eles são normalmente utilizados para declarar permissões de segurança específicas, como por exemplo: + +* `users:read` or `users:write` são exemplos comuns. +* `instagram_basic` é utilizado pelo Facebook / Instagram. +* `https://www.googleapis.com/auth/drive` é utilizado pelo Google. + +/// info | Informação + +No OAuth2, um "escopo" é apenas uma string que declara uma permissão específica necessária. + +Não importa se ela contém outros caracteres como `:` ou se ela é uma URL. + +Estes detalhes são específicos da implementação. + +Para o OAuth2, eles são apenas strings. + +/// + +## Visão global + +Primeiro, vamos olhar rapidamente as partes que mudam dos exemplos do **Tutorial - Guia de Usuário** para [OAuth2 com Senha (e hash), Bearer com tokens JWT](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Agora utilizando escopos OAuth2: + +//// tab | Python 3.10+ + +```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// + +Agora vamos revisar essas mudanças passo a passo. + +## Esquema de segurança OAuth2 + +A primeira mudança é que agora nós estamos declarando o esquema de segurança OAuth2 com dois escopos disponíveis, `me` e `items`. + +O parâmetro `scopes` recebe um `dict` contendo cada escopo como chave e a descrição como valor: + +//// tab | Python 3.10+ + +```Python hl_lines="63-66" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="63-66" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="64-67" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="62-65" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="63-66" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="63-66" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// + +Pelo motivo de estarmos declarando estes escopos, eles aparecerão nos documentos da API quando você se autenticar/autorizar. + +E você poderá selecionar quais escopos você deseja dar acesso: `me` e `items`. + +Este é o mesmo mecanismo utilizado quando você adiciona permissões enquanto se autentica com o Facebook, Google, GitHub, etc: + + + +## Token JWT com escopos + +Agora, modifique o *caminho de rota* para retornar os escopos solicitados. + +Nós ainda estamos utilizando o mesmo `OAuth2PasswordRequestForm`. Ele inclui a propriedade `scopes` com uma `list` de `str`, com cada escopo que ele recebeu na requisição. + +E nós retornamos os escopos como parte do token JWT. + +/// danger | Cuidado + +Para manter as coisas simples, aqui nós estamos apenas adicionando os escopos recebidos diretamente ao token. + +Porém em sua aplicação, por segurança, você deve garantir que você apenas adiciona os escopos que o usuário possui permissão de fato, ou aqueles que você predefiniu. + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="156" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="156" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="157" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="155" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="156" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="156" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// + +## Declare escopos em *operações de rota* e dependências + +Agora nós declaramos que a *operação de rota* para `/users/me/items/` exige o escopo `items`. + +Para isso, nós importamos e utilizamos `Security` de `fastapi`. + +Você pode utilizar `Security` para declarar dependências (assim como `Depends`), porém o `Security` também recebe o parâmetros `scopes` com uma lista de escopos (strings). + +Neste caso, nós passamos a função `get_current_active_user` como dependência para `Security` (da mesma forma que nós faríamos com `Depends`). + +Mas nós também passamos uma `list` de escopos, neste caso com apenas um escopo: `items` (poderia ter mais). + +E a função de dependência `get_current_active_user` também pode declarar subdependências, não apenas com `Depends`, mas também com `Security`. Ao declarar sua própria função de subdependência (`get_current_user`), e mais requisitos de escopo. + +Neste caso, ele requer o escopo `me` (poderia requerer mais de um escopo). + +/// note | "Nota" + +Você não necessariamente precisa adicionar diferentes escopos em diferentes lugares. + +Nós estamos fazendo isso aqui para demonstrar como o **FastAPI** lida com escopos declarados em diferentes níveis. + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="5 140 171" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="5 140 171" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="5 141 172" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="4 139 168" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="5 140 169" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="5 140 169" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// + +/// info | Informações Técnicas + +`Security` é na verdade uma subclasse de `Depends`, e ele possui apenas um parâmetro extra que veremos depois. + +Porém ao utilizar `Security` no lugar de `Depends`, o **FastAPI** saberá que ele pode declarar escopos de segurança, utilizá-los internamente, e documentar a API com o OpenAPI. + +Mas quando você importa `Query`, `Path`, `Depends`, `Security` entre outros de `fastapi`, eles são na verdade funções que retornam classes especiais. + +/// + +## Utilize `SecurityScopes` + +Agora atualize a dependência `get_current_user`. + +Este é o usado pelas dependências acima. + +Aqui é onde estamos utilizando o mesmo esquema OAuth2 que nós declaramos antes, declarando-o como uma dependência: `oauth2_scheme`. + +Porque esta função de dependência não possui nenhum requerimento de escopo, nós podemos utilizar `Depends` com o `oauth2_scheme`. Nós não precisamos utilizar `Security` quando nós não precisamos especificar escopos de segurança. + +Nós também declaramos um parâmetro especial do tipo `SecurityScopes`, importado de `fastapi.security`. + +A classe `SecurityScopes` é semelhante à classe `Request` (`Request` foi utilizada para obter o objeto da requisição diretamente). + +//// tab | Python 3.10+ + +```Python hl_lines="9 106" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9 106" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9 107" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="8 105" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="9 106" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="9 106" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// + +## Utilize os `scopes` + +O parâmetro `security_scopes` será do tipo `SecurityScopes`. + +Ele terá a propriedade `scopes` com uma lista contendo todos os escopos requeridos por ele e todas as dependências que utilizam ele como uma subdependência. Isso significa, todos os "dependentes"... pode soar meio confuso, e isso será explicado novamente mais adiante. + +O objeto `security_scopes` (da classe `SecurityScopes`) também oferece um atributo `scope_str` com uma única string, contendo os escopos separados por espaços (nós vamos utilizar isso). + +Nós criamos uma `HTTPException` que nós podemos reutilizar (`raise`) mais tarde em diversos lugares. + +Nesta exceção, nós incluímos os escopos necessários (se houver algum) como uma string separada por espaços (utilizando `scope_str`). Nós colocamos esta string contendo os escopos no cabeçalho `WWW-Authenticate` (isso é parte da especificação). + +//// tab | Python 3.10+ + +```Python hl_lines="106 108-116" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="106 108-116" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="107 109-117" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="105 107-115" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="106 108-116" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="106 108-116" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// + +## Verifique o `username` e o formato dos dados + +Nós verificamos que nós obtemos um `username`, e extraímos os escopos. + +E depois nós validamos esse dado com o modelo Pydantic (capturando a exceção `ValidationError`), e se nós obtemos um erro ao ler o token JWT ou validando os dados com o Pydantic, nós levantamos a exceção `HTTPException` que criamos anteriormente. + +Para isso, nós atualizamos o modelo Pydantic `TokenData` com a nova propriedade `scopes`. + +Ao validar os dados com o Pydantic nós podemos garantir que temos, por exemplo, exatamente uma `list` de `str` com os escopos e uma `str` com o `username`. + +No lugar de, por exemplo, um `dict`, ou alguma outra coisa, que poderia quebrar a aplicação em algum lugar mais tarde, tornando isso um risco de segurança. + +Nós também verificamos que nós temos um usuário com o "*username*", e caso contrário, nós levantamos a mesma exceção que criamos anteriormente. + +//// tab | Python 3.10+ + +```Python hl_lines="47 117-128" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="47 117-128" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="48 118-129" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="46 116-127" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="47 117-128" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="47 117-128" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// + +## Verifique os `scopes` + +Nós verificamos agora que todos os escopos necessários, por essa dependência e todos os dependentes (incluindo as *operações de rota*) estão incluídas nos escopos fornecidos pelo token recebido, caso contrário, levantamos uma `HTTPException`. + +Para isso, nós utilizamos `security_scopes.scopes`, que contém uma `list` com todos esses escopos como uma `str`. + +//// tab | Python 3.10+ + +```Python hl_lines="129-135" +{!> ../../../docs_src/security/tutorial005_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="129-135" +{!> ../../../docs_src/security/tutorial005_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="130-136" +{!> ../../../docs_src/security/tutorial005_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="128-134" +{!> ../../../docs_src/security/tutorial005_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="129-135" +{!> ../../../docs_src/security/tutorial005_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="129-135" +{!> ../../../docs_src/security/tutorial005.py!} +``` + +//// + +## Árvore de dependência e escopos + +Vamos rever novamente essa árvore de dependência e os escopos. + +Como a dependência `get_current_active_user` possui uma subdependência em `get_current_user`, o escopo `"me"` declarado em `get_current_active_user` será incluído na lista de escopos necessários em `security_scopes.scopes` passado para `get_current_user`. + +A própria *operação de rota* também declara o escopo, `"items"`, então ele também estará na lista de `security_scopes.scopes` passado para o `get_current_user`. + +Aqui está como a hierarquia de dependências e escopos parecem: + +* A *operação de rota* `read_own_items` possui: + * Escopos necessários `["items"]` com a dependência: + * `get_current_active_user`: + * A função de dependência `get_current_active_user` possui: + * Escopos necessários `["me"]` com a dependência: + * `get_current_user`: + * A função de dependência `get_current_user` possui: + * Nenhum escopo necessário. + * Uma dependência utilizando `oauth2_scheme`. + * Um parâmetro `security_scopes` do tipo `SecurityScopes`: + * Este parâmetro `security_scopes` possui uma propriedade `scopes` com uma `list` contendo todos estes escopos declarados acima, então: + * `security_scopes.scopes` terá `["me", "items"]` para a *operação de rota* `read_own_items`. + * `security_scopes.scopes` terá `["me"]` para a *operação de rota* `read_users_me`, porque ela declarou na dependência `get_current_active_user`. + * `security_scopes.scopes` terá `[]` (nada) para a *operação de rota* `read_system_status`, porque ele não declarou nenhum `Security` com `scopes`, e sua dependência, `get_current_user`, não declara nenhum `scopes` também. + +/// tip | Dica + +A coisa importante e "mágica" aqui é que `get_current_user` terá diferentes listas de `scopes` para validar para cada *operação de rota*. + +Tudo depende dos `scopes` declarados em cada *operação de rota* e cada dependência da árvore de dependências para aquela *operação de rota* específica. + +/// + +## Mais detalhes sobre `SecurityScopes` + +Você pode utilizar `SecurityScopes` em qualquer lugar, e em diversos lugares. Ele não precisa estar na dependência "raiz". + +Ele sempre terá os escopos de segurança declarados nas dependências atuais de `Security` e todos os dependentes para **aquela** *operação de rota* **específica** e **aquela** árvore de dependência **específica**. + +Porque o `SecurityScopes` terá todos os escopos declarados por dependentes, você pode utilizá-lo para verificar se o token possui os escopos necessários em uma função de dependência central, e depois declarar diferentes requisitos de escopo em diferentes *operações de rota*. + +Todos eles serão validados independentemente para cada *operação de rota*. + +## Verifique + +Se você abrir os documentos da API, você pode antenticar e especificar quais escopos você quer autorizar. + + + +Se você não selecionar nenhum escopo, você terá "autenticado", mas quando você tentar acessar `/users/me/` ou `/users/me/items/`, você vai obter um erro dizendo que você não possui as permissões necessárias. Você ainda poderá acessar `/status/`. + +E se você selecionar o escopo `me`, mas não o escopo `items`, você poderá acessar `/users/me/`, mas não `/users/me/items/`. + +Isso é o que aconteceria se uma aplicação terceira que tentou acessar uma dessas *operações de rota* com um token fornecido por um usuário, dependendo de quantas permissões o usuário forneceu para a aplicação. + +## Sobre integrações de terceiros + +Neste exemplos nós estamos utilizando o fluxo de senha do OAuth2. + +Isso é apropriado quando nós estamos autenticando em nossa própria aplicação, provavelmente com o nosso próprio "*frontend*". + +Porque nós podemos confiar nele para receber o `username` e o `password`, pois nós controlamos isso. + +Mas se nós estamos construindo uma aplicação OAuth2 que outros poderiam conectar (i.e., se você está construindo um provedor de autenticação equivalente ao Facebook, Google, GitHub, etc.) você deveria utilizar um dos outros fluxos. + +O mais comum é o fluxo implícito. + +O mais seguro é o fluxo de código, mas ele é mais complexo para implementar, pois ele necessita mais passos. Como ele é mais complexo, muitos provedores terminam sugerindo o fluxo implícito. + +/// note | "Nota" + +É comum que cada provedor de autenticação nomeie os seus fluxos de forma diferente, para torná-lo parte de sua marca. + +Mas no final, eles estão implementando o mesmo padrão OAuth2. + +/// + +O **FastAPI** inclui utilitários para todos esses fluxos de autenticação OAuth2 em `fastapi.security.oauth2`. + +## `Security` em docoradores de `dependências` + +Da mesma forma que você pode definir uma `list` de `Depends` no parâmetro de `dependencias` do decorador (como explicado em [Dependências em decoradores de operações de rota](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), você também pode utilizar `Security` com escopos lá. From e2217e24b9895adf5d6f8ef25c491fca4f1bdafb Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:14:33 +0000 Subject: [PATCH 016/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 7188a698f..e2b5808a4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/oauth2-scopes.md`. PR [#12263](https://github.com/fastapi/fastapi/pull/12263) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/deployment/concepts.md`. PR [#12219](https://github.com/fastapi/fastapi/pull/12219) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/conditional-openapi.md`. PR [#12221](https://github.com/fastapi/fastapi/pull/12221) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-directly.md`. PR [#12266](https://github.com/fastapi/fastapi/pull/12266) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). From a681aeba6d7112b9351a11ca5a1756de4e27d370 Mon Sep 17 00:00:00 2001 From: AnandaCampelo <103457620+AnandaCampelo@users.noreply.github.com> Date: Fri, 4 Oct 2024 08:15:21 -0300 Subject: [PATCH 017/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/how-to/graphql.md`=20(#12215)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/how-to/graphql.md | 62 ++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 docs/pt/docs/how-to/graphql.md diff --git a/docs/pt/docs/how-to/graphql.md b/docs/pt/docs/how-to/graphql.md new file mode 100644 index 000000000..0b711aa5e --- /dev/null +++ b/docs/pt/docs/how-to/graphql.md @@ -0,0 +1,62 @@ +# GraphQL + +Como o **FastAPI** é baseado no padrão **ASGI**, é muito fácil integrar qualquer biblioteca **GraphQL** também compatível com ASGI. + +Você pode combinar *operações de rota* normais do FastAPI com GraphQL na mesma aplicação. + +/// tip | "Dica" + +**GraphQL** resolve alguns casos de uso muito específicos. + +Ele tem **vantagens** e **desvantagens** quando comparado a **web APIs** comuns. + +Certifique-se de avaliar se os **benefícios** para o seu caso de uso compensam as **desvantagens**. 🤓 + +/// + +## Bibliotecas GraphQL + +Aqui estão algumas das bibliotecas **GraphQL** que têm suporte **ASGI**. Você pode usá-las com **FastAPI**: + +* Strawberry 🍓 + * Com docs para FastAPI +* Ariadne + * Com docs para FastAPI +* Tartiflette + * Com Tartiflette ASGI para fornecer integração ASGI +* Graphene + * Com starlette-graphene3 + +## GraphQL com Strawberry + +Se você precisar ou quiser trabalhar com **GraphQL**, **Strawberry** é a biblioteca **recomendada** pois tem o design mais próximo ao design do **FastAPI**, ela é toda baseada em **type annotations**. + +Dependendo do seu caso de uso, você pode preferir usar uma biblioteca diferente, mas se você me perguntasse, eu provavelmente sugeriria que você experimentasse o **Strawberry**. + +Aqui está uma pequena prévia de como você poderia integrar Strawberry com FastAPI: + +```Python hl_lines="3 22 25-26" +{!../../../docs_src/graphql/tutorial001.py!} +``` + +Você pode aprender mais sobre Strawberry na documentação do Strawberry. + +E também na documentação sobre Strawberry com FastAPI. + +## Antigo `GraphQLApp` do Starlette + +Versões anteriores do Starlette incluiam uma classe `GraphQLApp` para integrar com Graphene. + +Ela foi descontinuada do Starlette, mas se você tem código que a utilizava, você pode facilmente **migrar** para starlette-graphene3, que cobre o mesmo caso de uso e tem uma **interface quase idêntica**. + +/// tip | "Dica" + +Se você precisa de GraphQL, eu ainda recomendaria que você desse uma olhada no Strawberry, pois ele é baseado em type annotations em vez de classes e tipos personalizados. + +/// + +## Saiba Mais + +Você pode aprender mais sobre **GraphQL** na documentação oficial do GraphQL. + +Você também pode ler mais sobre cada uma das bibliotecas descritas acima em seus links. From c93810e0975a1f488f9d9d0a5b7a845b4d447a96 Mon Sep 17 00:00:00 2001 From: Kayque Govetri <59173212+kayqueGovetri@users.noreply.github.com> Date: Fri, 4 Oct 2024 08:16:34 -0300 Subject: [PATCH 018/932] =?UTF-8?q?=F0=9F=93=9D=20Adding=20links=20for=20P?= =?UTF-8?q?laywright=20and=20Vite=20in=20`docs/project-generation.md`=20(#?= =?UTF-8?q?12274)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/project-generation.md | 4 ++-- docs/es/docs/project-generation.md | 4 ++-- docs/ko/docs/project-generation.md | 4 ++-- docs/zh/docs/project-generation.md | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/en/docs/project-generation.md b/docs/en/docs/project-generation.md index 61459ba53..665bc54f9 100644 --- a/docs/en/docs/project-generation.md +++ b/docs/en/docs/project-generation.md @@ -13,10 +13,10 @@ GitHub Repository: Date: Fri, 4 Oct 2024 11:20:35 +0000 Subject: [PATCH 019/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e2b5808a4..d205d96ac 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/graphql.md`. PR [#12215](https://github.com/fastapi/fastapi/pull/12215) by [@AnandaCampelo](https://github.com/AnandaCampelo). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/oauth2-scopes.md`. PR [#12263](https://github.com/fastapi/fastapi/pull/12263) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/deployment/concepts.md`. PR [#12219](https://github.com/fastapi/fastapi/pull/12219) by [@marcelomarkus](https://github.com/marcelomarkus). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/conditional-openapi.md`. PR [#12221](https://github.com/fastapi/fastapi/pull/12221) by [@marcelomarkus](https://github.com/marcelomarkus). From 3d2483327234182791cd6855b180aa61936eaf05 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:20:57 +0000 Subject: [PATCH 020/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d205d96ac..bbc8ac14e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Adding links for Playwright and Vite in `docs/project-generation.md`. PR [#12274](https://github.com/fastapi/fastapi/pull/12274) by [@kayqueGovetri](https://github.com/kayqueGovetri). * 📝 Fix small typos in the documentation. PR [#12213](https://github.com/fastapi/fastapi/pull/12213) by [@svlandeg](https://github.com/svlandeg). ### Translations From a096615f79cb428b68b4478fe5d53e2cf43f6ca2 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 4 Oct 2024 13:21:41 +0200 Subject: [PATCH 021/932] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#12331)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/astral-sh/ruff-pre-commit: v0.6.7 → v0.6.8](https://github.com/astral-sh/ruff-pre-commit/compare/v0.6.7...v0.6.8) Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1502f0abd..48a7d495c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.6.7 + rev: v0.6.8 hooks: - id: ruff args: From f2fb0251cc22b1a7c7a2a65b3f6ee68750353af5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:26:21 +0000 Subject: [PATCH 022/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bbc8ac14e..82012b1af 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Internal +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12331](https://github.com/fastapi/fastapi/pull/12331) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 🔧 Update sponsors, remove Fine.dev. PR [#12271](https://github.com/fastapi/fastapi/pull/12271) by [@tiangolo](https://github.com/tiangolo). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12253](https://github.com/fastapi/fastapi/pull/12253) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * ✏️ Fix docstring typos in http security. PR [#12223](https://github.com/fastapi/fastapi/pull/12223) by [@albertvillanova](https://github.com/albertvillanova). From 3f3a3dd6640f0639f27202cf049fb9b24b6c53a6 Mon Sep 17 00:00:00 2001 From: Pavlo Pohorieltsev <49622129+makisukurisu@users.noreply.github.com> Date: Fri, 4 Oct 2024 14:34:57 +0300 Subject: [PATCH 023/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20link=20to=20Swa?= =?UTF-8?q?gger=20UI=20configuration=20docs=20(#12264)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/how-to/configure-swagger-ui.md | 4 ++-- docs/en/docs/how-to/configure-swagger-ui.md | 4 ++-- docs/pt/docs/how-to/configure-swagger-ui.md | 4 ++-- docs/zh/docs/how-to/configure-swagger-ui.md | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/de/docs/how-to/configure-swagger-ui.md b/docs/de/docs/how-to/configure-swagger-ui.md index c18091efd..7d62a14d3 100644 --- a/docs/de/docs/how-to/configure-swagger-ui.md +++ b/docs/de/docs/how-to/configure-swagger-ui.md @@ -1,6 +1,6 @@ # Swagger-Oberfläche konfigurieren -Sie können einige zusätzliche Parameter der Swagger-Oberfläche konfigurieren. +Sie können einige zusätzliche Parameter der Swagger-Oberfläche konfigurieren. Um diese zu konfigurieren, übergeben Sie das Argument `swagger_ui_parameters` beim Erstellen des `FastAPI()`-App-Objekts oder an die Funktion `get_swagger_ui_html()`. @@ -58,7 +58,7 @@ Um beispielsweise `deepLinking` zu deaktivieren, könnten Sie folgende Einstellu ## Andere Parameter der Swagger-Oberfläche -Um alle anderen möglichen Konfigurationen zu sehen, die Sie verwenden können, lesen Sie die offizielle Dokumentation für die Parameter der Swagger-Oberfläche. +Um alle anderen möglichen Konfigurationen zu sehen, die Sie verwenden können, lesen Sie die offizielle Dokumentation für die Parameter der Swagger-Oberfläche. ## JavaScript-basierte Einstellungen diff --git a/docs/en/docs/how-to/configure-swagger-ui.md b/docs/en/docs/how-to/configure-swagger-ui.md index 108afb929..040c3926b 100644 --- a/docs/en/docs/how-to/configure-swagger-ui.md +++ b/docs/en/docs/how-to/configure-swagger-ui.md @@ -1,6 +1,6 @@ # Configure Swagger UI -You can configure some extra Swagger UI parameters. +You can configure some extra Swagger UI parameters. To configure them, pass the `swagger_ui_parameters` argument when creating the `FastAPI()` app object or to the `get_swagger_ui_html()` function. @@ -58,7 +58,7 @@ For example, to disable `deepLinking` you could pass these settings to `swagger_ ## Other Swagger UI Parameters -To see all the other possible configurations you can use, read the official docs for Swagger UI parameters. +To see all the other possible configurations you can use, read the official docs for Swagger UI parameters. ## JavaScript-only settings diff --git a/docs/pt/docs/how-to/configure-swagger-ui.md b/docs/pt/docs/how-to/configure-swagger-ui.md index b40dad695..ceb8c634e 100644 --- a/docs/pt/docs/how-to/configure-swagger-ui.md +++ b/docs/pt/docs/how-to/configure-swagger-ui.md @@ -1,6 +1,6 @@ # Configurar Swagger UI -Você pode configurar alguns parâmetros extras da UI do Swagger. +Você pode configurar alguns parâmetros extras da UI do Swagger. Para configurá-los, passe o argumento `swagger_ui_parameters` ao criar o objeto de aplicativo `FastAPI()` ou para a função `get_swagger_ui_html()`. @@ -58,7 +58,7 @@ Por exemplo, para desabilitar `deepLinking` você pode passar essas configuraç ## Outros parâmetros da UI do Swagger -Para ver todas as outras configurações possíveis que você pode usar, leia a documentação oficial dos parâmetros da UI do Swagger. +Para ver todas as outras configurações possíveis que você pode usar, leia a documentação oficial dos parâmetros da UI do Swagger. ## Configurações somente JavaScript diff --git a/docs/zh/docs/how-to/configure-swagger-ui.md b/docs/zh/docs/how-to/configure-swagger-ui.md index c0d09f943..17f89b22f 100644 --- a/docs/zh/docs/how-to/configure-swagger-ui.md +++ b/docs/zh/docs/how-to/configure-swagger-ui.md @@ -1,6 +1,6 @@ # 配置 Swagger UI -你可以配置一些额外的 Swagger UI 参数. +你可以配置一些额外的 Swagger UI 参数. 如果需要配置它们,可以在创建 `FastAPI()` 应用对象时或调用 `get_swagger_ui_html()` 函数时传递 `swagger_ui_parameters` 参数。 @@ -58,7 +58,7 @@ FastAPI 包含了一些默认配置参数,适用于大多数用例。 ## 其他 Swagger UI 参数 -查看其他 Swagger UI 参数,请阅读 docs for Swagger UI parameters。 +查看其他 Swagger UI 参数,请阅读 docs for Swagger UI parameters。 ## JavaScript-only 配置 From d12db0b26c11d338bba3f0099a6236b5931224dd Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:36:26 +0000 Subject: [PATCH 024/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 82012b1af..744377757 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update link to Swagger UI configuration docs. PR [#12264](https://github.com/fastapi/fastapi/pull/12264) by [@makisukurisu](https://github.com/makisukurisu). * 📝 Adding links for Playwright and Vite in `docs/project-generation.md`. PR [#12274](https://github.com/fastapi/fastapi/pull/12274) by [@kayqueGovetri](https://github.com/kayqueGovetri). * 📝 Fix small typos in the documentation. PR [#12213](https://github.com/fastapi/fastapi/pull/12213) by [@svlandeg](https://github.com/svlandeg). From 8953d9a3234968d3673eddbeb947e42f34d3536a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 4 Oct 2024 13:37:26 +0200 Subject: [PATCH 025/932] =?UTF-8?q?=E2=AC=86=20Bump=20griffe-typingdoc=20f?= =?UTF-8?q?rom=200.2.6=20to=200.2.7=20(#12370)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [griffe-typingdoc](https://github.com/mkdocstrings/griffe-typingdoc) from 0.2.6 to 0.2.7. - [Release notes](https://github.com/mkdocstrings/griffe-typingdoc/releases) - [Changelog](https://github.com/mkdocstrings/griffe-typingdoc/blob/main/CHANGELOG.md) - [Commits](https://github.com/mkdocstrings/griffe-typingdoc/compare/0.2.6...0.2.7) --- updated-dependencies: - dependency-name: griffe-typingdoc dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs.txt b/requirements-docs.txt index 332fd1857..70dca9f2f 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -12,7 +12,7 @@ pillow==10.4.0 # For image processing by Material for MkDocs cairosvg==2.7.1 mkdocstrings[python]==0.25.1 -griffe-typingdoc==0.2.6 +griffe-typingdoc==0.2.7 # For griffe, it formats with black black==24.3.0 mkdocs-macros-plugin==1.0.5 From deec2e591e6fb506c4249340b1b96c0b2afd4b07 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:39:01 +0000 Subject: [PATCH 026/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 744377757..8fbb26bb0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Internal +* ⬆ Bump griffe-typingdoc from 0.2.6 to 0.2.7. PR [#12370](https://github.com/fastapi/fastapi/pull/12370) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12331](https://github.com/fastapi/fastapi/pull/12331) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 🔧 Update sponsors, remove Fine.dev. PR [#12271](https://github.com/fastapi/fastapi/pull/12271) by [@tiangolo](https://github.com/tiangolo). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12253](https://github.com/fastapi/fastapi/pull/12253) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). From 757eaacd5950ab355807ebf4f9e80dd17bd56b20 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 4 Oct 2024 13:56:35 +0200 Subject: [PATCH 027/932] =?UTF-8?q?=E2=AC=86=20Bump=20mkdocstrings[python]?= =?UTF-8?q?=20from=200.25.1=20to=200.26.1=20(#12371)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [mkdocstrings[python]](https://github.com/mkdocstrings/mkdocstrings) from 0.25.1 to 0.26.1. - [Release notes](https://github.com/mkdocstrings/mkdocstrings/releases) - [Changelog](https://github.com/mkdocstrings/mkdocstrings/blob/main/CHANGELOG.md) - [Commits](https://github.com/mkdocstrings/mkdocstrings/compare/0.25.1...0.26.1) --- updated-dependencies: - dependency-name: mkdocstrings[python] dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs.txt b/requirements-docs.txt index 70dca9f2f..16b2998b9 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -11,7 +11,7 @@ jieba==0.42.1 pillow==10.4.0 # For image processing by Material for MkDocs cairosvg==2.7.1 -mkdocstrings[python]==0.25.1 +mkdocstrings[python]==0.26.1 griffe-typingdoc==0.2.7 # For griffe, it formats with black black==24.3.0 From 82b95dcef8d032628217599ea8700260d1ecc670 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:56:57 +0000 Subject: [PATCH 028/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8fbb26bb0..77daba91c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Internal +* ⬆ Bump mkdocstrings[python] from 0.25.1 to 0.26.1. PR [#12371](https://github.com/fastapi/fastapi/pull/12371) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump griffe-typingdoc from 0.2.6 to 0.2.7. PR [#12370](https://github.com/fastapi/fastapi/pull/12370) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12331](https://github.com/fastapi/fastapi/pull/12331) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 🔧 Update sponsors, remove Fine.dev. PR [#12271](https://github.com/fastapi/fastapi/pull/12271) by [@tiangolo](https://github.com/tiangolo). From caa298aefea0ddbd373368b87a740b3bd08e4e42 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 4 Oct 2024 13:57:23 +0200 Subject: [PATCH 029/932] =?UTF-8?q?=E2=AC=86=20Bump=20pypa/gh-action-pypi-?= =?UTF-8?q?publish=20from=201.10.1=20to=201.10.3=20(#12386)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.10.1 to 1.10.3. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.10.1...v1.10.3) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 5004b94dd..c8ea4e18c 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -35,7 +35,7 @@ jobs: TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.10.1 + uses: pypa/gh-action-pypi-publish@v1.10.3 - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} From ea1265b78beb2a7a1991a6dd4e8f19852ffa3196 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 4 Oct 2024 11:58:03 +0000 Subject: [PATCH 030/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 77daba91c..6660ea894 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Internal +* ⬆ Bump pypa/gh-action-pypi-publish from 1.10.1 to 1.10.3. PR [#12386](https://github.com/fastapi/fastapi/pull/12386) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump mkdocstrings[python] from 0.25.1 to 0.26.1. PR [#12371](https://github.com/fastapi/fastapi/pull/12371) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump griffe-typingdoc from 0.2.6 to 0.2.7. PR [#12370](https://github.com/fastapi/fastapi/pull/12370) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12331](https://github.com/fastapi/fastapi/pull/12331) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). From 9d6ec4aa77f613a99c8f05d8f8a0d2088a2a2d00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 5 Oct 2024 14:49:04 +0200 Subject: [PATCH 031/932] =?UTF-8?q?=F0=9F=91=B7=20Update=20Cloudflare=20Gi?= =?UTF-8?q?tHub=20Action=20(#12387)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy-docs.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index d2953f284..c7827f132 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -55,14 +55,14 @@ jobs: # hashFiles returns an empty string if there are no files if: hashFiles('./site/*') id: deploy - uses: cloudflare/pages-action@v1 + env: + PROJECT_NAME: fastapitiangolo + BRANCH: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} + uses: cloudflare/wrangler-action@v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - projectName: fastapitiangolo - directory: './site' - gitHubToken: ${{ secrets.GITHUB_TOKEN }} - branch: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} + command: pages deploy ./site --project-name=${{ env.PROJECT_NAME }} --branch=${{ env.BRANCH }} - name: Comment Deploy run: python ./scripts/deploy_docs_status.py env: From ad8b3ba3ec5e41f7ebf85791870cab40f0429517 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 5 Oct 2024 12:49:28 +0000 Subject: [PATCH 032/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6660ea894..ddbaee46b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Internal +* 👷 Update Cloudflare GitHub Action. PR [#12387](https://github.com/fastapi/fastapi/pull/12387) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump pypa/gh-action-pypi-publish from 1.10.1 to 1.10.3. PR [#12386](https://github.com/fastapi/fastapi/pull/12386) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump mkdocstrings[python] from 0.25.1 to 0.26.1. PR [#12371](https://github.com/fastapi/fastapi/pull/12371) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump griffe-typingdoc from 0.2.6 to 0.2.7. PR [#12370](https://github.com/fastapi/fastapi/pull/12370) by [@dependabot[bot]](https://github.com/apps/dependabot). From 1705a8c37f047df61564e47dd8c050d6213def81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 6 Oct 2024 22:14:05 +0200 Subject: [PATCH 033/932] =?UTF-8?q?=F0=9F=91=B7=20Update=20deploy-docs-not?= =?UTF-8?q?ify=20URL=20(#12392)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy-docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index c7827f132..22dc89dff 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -67,7 +67,7 @@ jobs: run: python ./scripts/deploy_docs_status.py env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - DEPLOY_URL: ${{ steps.deploy.outputs.url }} + DEPLOY_URL: ${{ steps.deploy.outputs.deployment-url }} COMMIT_SHA: ${{ github.event.workflow_run.head_sha }} RUN_ID: ${{ github.run_id }} IS_DONE: "true" From c67b41546cd322cb61e25cc275e995902519ca68 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 6 Oct 2024 20:14:33 +0000 Subject: [PATCH 034/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ddbaee46b..2995aa8df 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -32,6 +32,7 @@ hide: ### Internal +* 👷 Update worfkow deploy-docs-notify URL. PR [#12392](https://github.com/fastapi/fastapi/pull/12392) by [@tiangolo](https://github.com/tiangolo). * 👷 Update Cloudflare GitHub Action. PR [#12387](https://github.com/fastapi/fastapi/pull/12387) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump pypa/gh-action-pypi-publish from 1.10.1 to 1.10.3. PR [#12386](https://github.com/fastapi/fastapi/pull/12386) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump mkdocstrings[python] from 0.25.1 to 0.26.1. PR [#12371](https://github.com/fastapi/fastapi/pull/12371) by [@dependabot[bot]](https://github.com/apps/dependabot). From 0f7d67e85c9b99c82821c9cfde51721dd98698a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 6 Oct 2024 22:36:54 +0200 Subject: [PATCH 035/932] =?UTF-8?q?=F0=9F=94=A7=20Remove=20`base=5Fpath`?= =?UTF-8?q?=20for=20`mdx=5Finclude`=20Markdown=20extension=20in=20MkDocs?= =?UTF-8?q?=20(#12391)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/bn/docs/python-types.md | 56 +++---- docs/de/docs/advanced/additional-responses.md | 8 +- .../docs/advanced/additional-status-codes.md | 10 +- .../de/docs/advanced/advanced-dependencies.md | 24 +-- docs/de/docs/advanced/async-tests.md | 8 +- docs/de/docs/advanced/behind-a-proxy.md | 10 +- docs/de/docs/advanced/custom-response.md | 32 ++-- docs/de/docs/advanced/dataclasses.md | 6 +- docs/de/docs/advanced/events.md | 12 +- docs/de/docs/advanced/generate-clients.md | 16 +- docs/de/docs/advanced/middleware.md | 6 +- docs/de/docs/advanced/openapi-callbacks.md | 8 +- docs/de/docs/advanced/openapi-webhooks.md | 2 +- .../path-operation-advanced-configuration.md | 20 +-- .../advanced/response-change-status-code.md | 2 +- docs/de/docs/advanced/response-cookies.md | 4 +- docs/de/docs/advanced/response-directly.md | 4 +- docs/de/docs/advanced/response-headers.md | 4 +- .../docs/advanced/security/http-basic-auth.md | 18 +-- .../docs/advanced/security/oauth2-scopes.md | 96 ++++++------ docs/de/docs/advanced/settings.md | 36 ++--- docs/de/docs/advanced/sub-applications.md | 6 +- docs/de/docs/advanced/templates.md | 8 +- docs/de/docs/advanced/testing-dependencies.md | 10 +- docs/de/docs/advanced/testing-events.md | 2 +- docs/de/docs/advanced/testing-websockets.md | 2 +- .../docs/advanced/using-request-directly.md | 2 +- docs/de/docs/advanced/websockets.md | 20 +-- docs/de/docs/advanced/wsgi.md | 2 +- docs/de/docs/how-to/conditional-openapi.md | 2 +- docs/de/docs/how-to/configure-swagger-ui.md | 8 +- docs/de/docs/how-to/custom-docs-ui-assets.md | 14 +- .../docs/how-to/custom-request-and-route.md | 12 +- docs/de/docs/how-to/extending-openapi.md | 10 +- docs/de/docs/how-to/graphql.md | 2 +- .../docs/how-to/separate-openapi-schemas.md | 36 ++--- docs/de/docs/python-types.md | 56 +++---- docs/de/docs/tutorial/background-tasks.md | 16 +- docs/de/docs/tutorial/bigger-applications.md | 30 ++-- docs/de/docs/tutorial/body-fields.md | 20 +-- docs/de/docs/tutorial/body-multiple-params.md | 44 +++--- docs/de/docs/tutorial/body-nested-models.md | 56 +++---- docs/de/docs/tutorial/body-updates.md | 24 +-- docs/de/docs/tutorial/body.md | 24 +-- docs/de/docs/tutorial/cookie-params.md | 20 +-- .../dependencies/classes-as-dependencies.md | 70 ++++----- ...pendencies-in-path-operation-decorators.md | 24 +-- .../dependencies/dependencies-with-yield.md | 28 ++-- .../dependencies/global-dependencies.md | 6 +- docs/de/docs/tutorial/dependencies/index.md | 36 ++--- .../tutorial/dependencies/sub-dependencies.md | 30 ++-- docs/de/docs/tutorial/encoder.md | 4 +- docs/de/docs/tutorial/extra-data-types.md | 20 +-- docs/de/docs/tutorial/extra-models.md | 20 +-- docs/de/docs/tutorial/first-steps.md | 16 +- docs/de/docs/tutorial/handling-errors.md | 16 +- docs/de/docs/tutorial/header-params.md | 42 ++--- docs/de/docs/tutorial/metadata.md | 12 +- docs/de/docs/tutorial/middleware.md | 4 +- .../tutorial/path-operation-configuration.md | 34 ++-- .../path-params-numeric-validations.md | 50 +++--- docs/de/docs/tutorial/path-params.md | 20 +-- .../tutorial/query-params-str-validations.md | 142 ++++++++--------- docs/de/docs/tutorial/query-params.md | 20 +-- docs/de/docs/tutorial/request-files.md | 50 +++--- .../docs/tutorial/request-forms-and-files.md | 12 +- docs/de/docs/tutorial/request-forms.md | 12 +- docs/de/docs/tutorial/response-model.md | 68 ++++---- docs/de/docs/tutorial/response-status-code.md | 6 +- docs/de/docs/tutorial/schema-extra-example.md | 42 ++--- docs/de/docs/tutorial/security/first-steps.md | 18 +-- .../tutorial/security/get-current-user.md | 56 +++---- docs/de/docs/tutorial/security/oauth2-jwt.md | 40 ++--- .../docs/tutorial/security/simple-oauth2.md | 50 +++--- docs/de/docs/tutorial/static-files.md | 2 +- docs/de/docs/tutorial/testing.md | 18 +-- docs/em/docs/advanced/additional-responses.md | 8 +- .../docs/advanced/additional-status-codes.md | 2 +- .../em/docs/advanced/advanced-dependencies.md | 8 +- docs/em/docs/advanced/async-tests.md | 8 +- docs/em/docs/advanced/behind-a-proxy.md | 8 +- docs/em/docs/advanced/custom-response.md | 32 ++-- docs/em/docs/advanced/dataclasses.md | 6 +- docs/em/docs/advanced/events.md | 12 +- docs/em/docs/advanced/generate-clients.md | 14 +- docs/em/docs/advanced/middleware.md | 6 +- docs/em/docs/advanced/openapi-callbacks.md | 8 +- .../path-operation-advanced-configuration.md | 16 +- .../advanced/response-change-status-code.md | 2 +- docs/em/docs/advanced/response-cookies.md | 4 +- docs/em/docs/advanced/response-directly.md | 4 +- docs/em/docs/advanced/response-headers.md | 4 +- .../docs/advanced/security/http-basic-auth.md | 6 +- .../docs/advanced/security/oauth2-scopes.md | 16 +- docs/em/docs/advanced/settings.md | 20 +-- docs/em/docs/advanced/sub-applications.md | 6 +- docs/em/docs/advanced/templates.md | 8 +- docs/em/docs/advanced/testing-database.md | 8 +- docs/em/docs/advanced/testing-dependencies.md | 2 +- docs/em/docs/advanced/testing-events.md | 2 +- docs/em/docs/advanced/testing-websockets.md | 2 +- .../docs/advanced/using-request-directly.md | 2 +- docs/em/docs/advanced/websockets.md | 10 +- docs/em/docs/advanced/wsgi.md | 2 +- docs/em/docs/how-to/conditional-openapi.md | 2 +- .../docs/how-to/custom-request-and-route.md | 12 +- docs/em/docs/how-to/extending-openapi.md | 10 +- docs/em/docs/how-to/graphql.md | 2 +- docs/em/docs/how-to/sql-databases-peewee.md | 34 ++-- docs/em/docs/python-types.md | 52 +++---- docs/em/docs/tutorial/background-tasks.md | 10 +- docs/em/docs/tutorial/bigger-applications.md | 26 ++-- docs/em/docs/tutorial/body-fields.md | 8 +- docs/em/docs/tutorial/body-multiple-params.md | 20 +-- docs/em/docs/tutorial/body-nested-models.md | 56 +++---- docs/em/docs/tutorial/body-updates.md | 24 +-- docs/em/docs/tutorial/body.md | 24 +-- docs/em/docs/tutorial/cookie-params.md | 8 +- docs/em/docs/tutorial/cors.md | 2 +- docs/em/docs/tutorial/debugging.md | 2 +- .../dependencies/classes-as-dependencies.md | 28 ++-- ...pendencies-in-path-operation-decorators.md | 8 +- .../dependencies/dependencies-with-yield.md | 14 +- .../dependencies/global-dependencies.md | 2 +- docs/em/docs/tutorial/dependencies/index.md | 12 +- .../tutorial/dependencies/sub-dependencies.md | 12 +- docs/em/docs/tutorial/encoder.md | 4 +- docs/em/docs/tutorial/extra-data-types.md | 8 +- docs/em/docs/tutorial/extra-models.md | 20 +-- docs/em/docs/tutorial/first-steps.md | 16 +- docs/em/docs/tutorial/handling-errors.md | 16 +- docs/em/docs/tutorial/header-params.md | 18 +-- docs/em/docs/tutorial/metadata.md | 10 +- docs/em/docs/tutorial/middleware.md | 4 +- .../tutorial/path-operation-configuration.md | 34 ++-- .../path-params-numeric-validations.md | 18 +-- docs/em/docs/tutorial/path-params.md | 20 +-- .../tutorial/query-params-str-validations.md | 64 ++++---- docs/em/docs/tutorial/query-params.md | 20 +-- docs/em/docs/tutorial/request-files.md | 20 +-- .../docs/tutorial/request-forms-and-files.md | 4 +- docs/em/docs/tutorial/request-forms.md | 4 +- docs/em/docs/tutorial/response-model.md | 68 ++++---- docs/em/docs/tutorial/response-status-code.md | 6 +- docs/em/docs/tutorial/schema-extra-example.md | 16 +- docs/em/docs/tutorial/security/first-steps.md | 6 +- .../tutorial/security/get-current-user.md | 22 +-- docs/em/docs/tutorial/security/oauth2-jwt.md | 16 +- .../docs/tutorial/security/simple-oauth2.md | 20 +-- docs/em/docs/tutorial/sql-databases.md | 74 ++++----- docs/em/docs/tutorial/static-files.md | 2 +- docs/em/docs/tutorial/testing.md | 12 +- docs/en/docs/advanced/additional-responses.md | 8 +- .../docs/advanced/additional-status-codes.md | 10 +- .../en/docs/advanced/advanced-dependencies.md | 24 +-- docs/en/docs/advanced/async-tests.md | 8 +- docs/en/docs/advanced/behind-a-proxy.md | 10 +- docs/en/docs/advanced/custom-response.md | 32 ++-- docs/en/docs/advanced/dataclasses.md | 6 +- docs/en/docs/advanced/events.md | 12 +- docs/en/docs/advanced/generate-clients.md | 16 +- docs/en/docs/advanced/middleware.md | 6 +- docs/en/docs/advanced/openapi-callbacks.md | 8 +- docs/en/docs/advanced/openapi-webhooks.md | 2 +- .../path-operation-advanced-configuration.md | 20 +-- .../advanced/response-change-status-code.md | 2 +- docs/en/docs/advanced/response-cookies.md | 4 +- docs/en/docs/advanced/response-directly.md | 4 +- docs/en/docs/advanced/response-headers.md | 4 +- .../docs/advanced/security/http-basic-auth.md | 18 +-- .../docs/advanced/security/oauth2-scopes.md | 96 ++++++------ docs/en/docs/advanced/settings.md | 36 ++--- docs/en/docs/advanced/sub-applications.md | 6 +- docs/en/docs/advanced/templates.md | 8 +- docs/en/docs/advanced/testing-database.md | 8 +- docs/en/docs/advanced/testing-dependencies.md | 10 +- docs/en/docs/advanced/testing-events.md | 2 +- docs/en/docs/advanced/testing-websockets.md | 2 +- .../docs/advanced/using-request-directly.md | 2 +- docs/en/docs/advanced/websockets.md | 20 +-- docs/en/docs/advanced/wsgi.md | 2 +- .../docs/how-to/async-sql-encode-databases.md | 14 +- docs/en/docs/how-to/conditional-openapi.md | 2 +- docs/en/docs/how-to/configure-swagger-ui.md | 8 +- docs/en/docs/how-to/custom-docs-ui-assets.md | 14 +- .../docs/how-to/custom-request-and-route.md | 12 +- docs/en/docs/how-to/extending-openapi.md | 10 +- docs/en/docs/how-to/graphql.md | 2 +- .../docs/how-to/nosql-databases-couchbase.md | 16 +- .../docs/how-to/separate-openapi-schemas.md | 36 ++--- docs/en/docs/how-to/sql-databases-peewee.md | 34 ++-- docs/en/docs/python-types.md | 56 +++---- docs/en/docs/tutorial/background-tasks.md | 16 +- docs/en/docs/tutorial/bigger-applications.md | 30 ++-- docs/en/docs/tutorial/body-fields.md | 20 +-- docs/en/docs/tutorial/body-multiple-params.md | 44 +++--- docs/en/docs/tutorial/body-nested-models.md | 56 +++---- docs/en/docs/tutorial/body-updates.md | 24 +-- docs/en/docs/tutorial/body.md | 24 +-- docs/en/docs/tutorial/cookie-param-models.md | 16 +- docs/en/docs/tutorial/cookie-params.md | 20 +-- docs/en/docs/tutorial/cors.md | 2 +- docs/en/docs/tutorial/debugging.md | 2 +- .../dependencies/classes-as-dependencies.md | 70 ++++----- ...pendencies-in-path-operation-decorators.md | 24 +-- .../dependencies/dependencies-with-yield.md | 40 ++--- .../dependencies/global-dependencies.md | 6 +- docs/en/docs/tutorial/dependencies/index.md | 36 ++--- .../tutorial/dependencies/sub-dependencies.md | 30 ++-- docs/en/docs/tutorial/encoder.md | 4 +- docs/en/docs/tutorial/extra-data-types.md | 20 +-- docs/en/docs/tutorial/extra-models.md | 20 +-- docs/en/docs/tutorial/first-steps.md | 14 +- docs/en/docs/tutorial/handling-errors.md | 16 +- docs/en/docs/tutorial/header-param-models.md | 24 +-- docs/en/docs/tutorial/header-params.md | 42 ++--- docs/en/docs/tutorial/metadata.md | 12 +- docs/en/docs/tutorial/middleware.md | 4 +- .../tutorial/path-operation-configuration.md | 34 ++-- .../path-params-numeric-validations.md | 50 +++--- docs/en/docs/tutorial/path-params.md | 20 +-- docs/en/docs/tutorial/query-param-models.md | 24 +-- .../tutorial/query-params-str-validations.md | 142 ++++++++--------- docs/en/docs/tutorial/query-params.md | 20 +-- docs/en/docs/tutorial/request-files.md | 50 +++--- docs/en/docs/tutorial/request-form-models.md | 12 +- .../docs/tutorial/request-forms-and-files.md | 12 +- docs/en/docs/tutorial/request-forms.md | 12 +- docs/en/docs/tutorial/response-model.md | 68 ++++---- docs/en/docs/tutorial/response-status-code.md | 6 +- docs/en/docs/tutorial/schema-extra-example.md | 42 ++--- docs/en/docs/tutorial/security/first-steps.md | 18 +-- .../tutorial/security/get-current-user.md | 56 +++---- docs/en/docs/tutorial/security/oauth2-jwt.md | 40 ++--- .../docs/tutorial/security/simple-oauth2.md | 50 +++--- docs/en/docs/tutorial/sql-databases.md | 26 ++-- docs/en/docs/tutorial/static-files.md | 2 +- docs/en/docs/tutorial/testing.md | 18 +-- docs/en/mkdocs.yml | 1 - .../docs/advanced/additional-status-codes.md | 2 +- .../path-operation-advanced-configuration.md | 8 +- .../advanced/response-change-status-code.md | 2 +- docs/es/docs/advanced/response-directly.md | 4 +- docs/es/docs/advanced/response-headers.md | 4 +- docs/es/docs/how-to/graphql.md | 2 +- docs/es/docs/python-types.md | 26 ++-- docs/es/docs/tutorial/cookie-params.md | 20 +-- docs/es/docs/tutorial/first-steps.md | 16 +- docs/es/docs/tutorial/path-params.md | 18 +-- docs/es/docs/tutorial/query-params.md | 12 +- docs/fa/docs/advanced/sub-applications.md | 6 +- docs/fa/docs/tutorial/middleware.md | 4 +- docs/fr/docs/advanced/additional-responses.md | 8 +- .../docs/advanced/additional-status-codes.md | 2 +- .../path-operation-advanced-configuration.md | 16 +- docs/fr/docs/advanced/response-directly.md | 4 +- docs/fr/docs/python-types.md | 28 ++-- docs/fr/docs/tutorial/background-tasks.md | 8 +- docs/fr/docs/tutorial/body-multiple-params.md | 44 +++--- docs/fr/docs/tutorial/body.md | 12 +- docs/fr/docs/tutorial/debugging.md | 2 +- docs/fr/docs/tutorial/first-steps.md | 16 +- .../path-params-numeric-validations.md | 56 +++---- docs/fr/docs/tutorial/path-params.md | 18 +-- .../tutorial/query-params-str-validations.md | 28 ++-- docs/fr/docs/tutorial/query-params.md | 12 +- .../docs/advanced/additional-status-codes.md | 2 +- docs/ja/docs/advanced/custom-response.md | 24 +-- .../path-operation-advanced-configuration.md | 8 +- docs/ja/docs/advanced/response-directly.md | 4 +- docs/ja/docs/advanced/websockets.md | 10 +- docs/ja/docs/how-to/conditional-openapi.md | 2 +- docs/ja/docs/python-types.md | 28 ++-- docs/ja/docs/tutorial/background-tasks.md | 8 +- docs/ja/docs/tutorial/body-fields.md | 4 +- docs/ja/docs/tutorial/body-multiple-params.md | 10 +- docs/ja/docs/tutorial/body-nested-models.md | 22 +-- docs/ja/docs/tutorial/body-updates.md | 8 +- docs/ja/docs/tutorial/body.md | 12 +- docs/ja/docs/tutorial/cookie-params.md | 4 +- docs/ja/docs/tutorial/cors.md | 2 +- docs/ja/docs/tutorial/debugging.md | 2 +- .../dependencies/classes-as-dependencies.md | 14 +- ...pendencies-in-path-operation-decorators.md | 8 +- .../dependencies/dependencies-with-yield.md | 14 +- docs/ja/docs/tutorial/dependencies/index.md | 6 +- .../tutorial/dependencies/sub-dependencies.md | 6 +- docs/ja/docs/tutorial/encoder.md | 2 +- docs/ja/docs/tutorial/extra-data-types.md | 4 +- docs/ja/docs/tutorial/extra-models.md | 10 +- docs/ja/docs/tutorial/first-steps.md | 16 +- docs/ja/docs/tutorial/handling-errors.md | 16 +- docs/ja/docs/tutorial/header-params.md | 8 +- docs/ja/docs/tutorial/metadata.md | 10 +- docs/ja/docs/tutorial/middleware.md | 4 +- .../tutorial/path-operation-configuration.md | 12 +- .../path-params-numeric-validations.md | 14 +- docs/ja/docs/tutorial/path-params.md | 18 +-- .../tutorial/query-params-str-validations.md | 28 ++-- docs/ja/docs/tutorial/query-params.md | 12 +- .../docs/tutorial/request-forms-and-files.md | 4 +- docs/ja/docs/tutorial/request-forms.md | 4 +- docs/ja/docs/tutorial/response-model.md | 20 +-- docs/ja/docs/tutorial/response-status-code.md | 6 +- docs/ja/docs/tutorial/schema-extra-example.md | 6 +- docs/ja/docs/tutorial/security/first-steps.md | 6 +- .../tutorial/security/get-current-user.md | 12 +- docs/ja/docs/tutorial/security/oauth2-jwt.md | 8 +- docs/ja/docs/tutorial/static-files.md | 2 +- docs/ja/docs/tutorial/testing.md | 12 +- docs/ko/docs/advanced/events.md | 4 +- docs/ko/docs/python-types.md | 28 ++-- docs/ko/docs/tutorial/background-tasks.md | 10 +- docs/ko/docs/tutorial/body-fields.md | 20 +-- docs/ko/docs/tutorial/body-multiple-params.md | 10 +- docs/ko/docs/tutorial/body-nested-models.md | 22 +-- docs/ko/docs/tutorial/body.md | 24 +-- docs/ko/docs/tutorial/cookie-params.md | 20 +-- docs/ko/docs/tutorial/cors.md | 2 +- docs/ko/docs/tutorial/debugging.md | 2 +- .../dependencies/classes-as-dependencies.md | 28 ++-- ...pendencies-in-path-operation-decorators.md | 24 +-- .../dependencies/global-dependencies.md | 6 +- docs/ko/docs/tutorial/dependencies/index.md | 36 ++--- docs/ko/docs/tutorial/encoder.md | 2 +- docs/ko/docs/tutorial/extra-data-types.md | 20 +-- docs/ko/docs/tutorial/first-steps.md | 16 +- docs/ko/docs/tutorial/header-params.md | 8 +- docs/ko/docs/tutorial/middleware.md | 4 +- .../tutorial/path-operation-configuration.md | 12 +- .../path-params-numeric-validations.md | 14 +- docs/ko/docs/tutorial/path-params.md | 18 +-- .../tutorial/query-params-str-validations.md | 28 ++-- docs/ko/docs/tutorial/query-params.md | 12 +- docs/ko/docs/tutorial/request-files.md | 8 +- .../docs/tutorial/request-forms-and-files.md | 4 +- docs/ko/docs/tutorial/response-model.md | 20 +-- docs/ko/docs/tutorial/response-status-code.md | 6 +- docs/ko/docs/tutorial/schema-extra-example.md | 42 ++--- .../tutorial/security/get-current-user.md | 22 +-- .../docs/tutorial/security/simple-oauth2.md | 20 +-- docs/ko/docs/tutorial/static-files.md | 2 +- docs/nl/docs/python-types.md | 56 +++---- docs/pl/docs/tutorial/first-steps.md | 16 +- docs/pt/docs/advanced/additional-responses.md | 8 +- .../docs/advanced/additional-status-codes.md | 10 +- .../pt/docs/advanced/advanced-dependencies.md | 24 +-- docs/pt/docs/advanced/async-tests.md | 8 +- docs/pt/docs/advanced/behind-a-proxy.md | 10 +- docs/pt/docs/advanced/events.md | 12 +- docs/pt/docs/advanced/openapi-webhooks.md | 2 +- .../advanced/response-change-status-code.md | 2 +- docs/pt/docs/advanced/response-directly.md | 4 +- .../docs/advanced/security/http-basic-auth.md | 18 +-- .../docs/advanced/security/oauth2-scopes.md | 96 ++++++------ docs/pt/docs/advanced/settings.md | 36 ++--- docs/pt/docs/advanced/sub-applications.md | 6 +- docs/pt/docs/advanced/templates.md | 8 +- docs/pt/docs/advanced/testing-dependencies.md | 10 +- docs/pt/docs/advanced/testing-events.md | 2 +- docs/pt/docs/advanced/testing-websockets.md | 2 +- .../docs/advanced/using-request-directly.md | 2 +- docs/pt/docs/advanced/wsgi.md | 2 +- docs/pt/docs/how-to/conditional-openapi.md | 2 +- docs/pt/docs/how-to/configure-swagger-ui.md | 8 +- docs/pt/docs/how-to/graphql.md | 2 +- docs/pt/docs/python-types.md | 28 ++-- docs/pt/docs/tutorial/background-tasks.md | 8 +- docs/pt/docs/tutorial/bigger-applications.md | 30 ++-- docs/pt/docs/tutorial/body-fields.md | 4 +- docs/pt/docs/tutorial/body-multiple-params.md | 20 +-- docs/pt/docs/tutorial/body-nested-models.md | 22 +-- docs/pt/docs/tutorial/body.md | 12 +- docs/pt/docs/tutorial/cookie-params.md | 20 +-- docs/pt/docs/tutorial/cors.md | 2 +- docs/pt/docs/tutorial/debugging.md | 2 +- .../dependencies/classes-as-dependencies.md | 70 ++++----- ...pendencies-in-path-operation-decorators.md | 24 +-- .../dependencies/dependencies-with-yield.md | 40 ++--- .../dependencies/global-dependencies.md | 6 +- docs/pt/docs/tutorial/dependencies/index.md | 36 ++--- .../tutorial/dependencies/sub-dependencies.md | 30 ++-- docs/pt/docs/tutorial/encoder.md | 4 +- docs/pt/docs/tutorial/extra-data-types.md | 4 +- docs/pt/docs/tutorial/extra-models.md | 20 +-- docs/pt/docs/tutorial/first-steps.md | 16 +- docs/pt/docs/tutorial/handling-errors.md | 14 +- docs/pt/docs/tutorial/header-params.md | 18 +-- docs/pt/docs/tutorial/middleware.md | 4 +- .../tutorial/path-operation-configuration.md | 34 ++-- .../path-params-numeric-validations.md | 18 +-- docs/pt/docs/tutorial/path-params.md | 18 +-- .../tutorial/query-params-str-validations.md | 28 ++-- docs/pt/docs/tutorial/query-params.md | 20 +-- docs/pt/docs/tutorial/request-form-models.md | 12 +- .../docs/tutorial/request-forms-and-files.md | 4 +- docs/pt/docs/tutorial/request-forms.md | 4 +- docs/pt/docs/tutorial/request_files.md | 50 +++--- docs/pt/docs/tutorial/response-status-code.md | 6 +- docs/pt/docs/tutorial/schema-extra-example.md | 8 +- docs/pt/docs/tutorial/security/first-steps.md | 6 +- docs/pt/docs/tutorial/static-files.md | 2 +- docs/pt/docs/tutorial/testing.md | 18 +-- docs/ru/docs/python-types.md | 28 ++-- docs/ru/docs/tutorial/background-tasks.md | 10 +- docs/ru/docs/tutorial/body-fields.md | 8 +- docs/ru/docs/tutorial/body-multiple-params.md | 44 +++--- docs/ru/docs/tutorial/body-nested-models.md | 56 +++---- docs/ru/docs/tutorial/body-updates.md | 24 +-- docs/ru/docs/tutorial/body.md | 12 +- docs/ru/docs/tutorial/cookie-params.md | 8 +- docs/ru/docs/tutorial/cors.md | 2 +- docs/ru/docs/tutorial/debugging.md | 2 +- .../dependencies/classes-as-dependencies.md | 70 ++++----- ...pendencies-in-path-operation-decorators.md | 24 +-- .../dependencies/dependencies-with-yield.md | 22 +-- .../dependencies/global-dependencies.md | 6 +- docs/ru/docs/tutorial/dependencies/index.md | 36 ++--- .../tutorial/dependencies/sub-dependencies.md | 30 ++-- docs/ru/docs/tutorial/encoder.md | 4 +- docs/ru/docs/tutorial/extra-data-types.md | 8 +- docs/ru/docs/tutorial/extra-models.md | 20 +-- docs/ru/docs/tutorial/first-steps.md | 16 +- docs/ru/docs/tutorial/handling-errors.md | 16 +- docs/ru/docs/tutorial/header-params.md | 42 ++--- docs/ru/docs/tutorial/metadata.md | 10 +- .../tutorial/path-operation-configuration.md | 34 ++-- .../path-params-numeric-validations.md | 50 +++--- docs/ru/docs/tutorial/path-params.md | 20 +-- .../tutorial/query-params-str-validations.md | 146 +++++++++--------- docs/ru/docs/tutorial/query-params.md | 20 +-- docs/ru/docs/tutorial/request-files.md | 50 +++--- .../docs/tutorial/request-forms-and-files.md | 12 +- docs/ru/docs/tutorial/request-forms.md | 12 +- docs/ru/docs/tutorial/response-model.md | 68 ++++---- docs/ru/docs/tutorial/response-status-code.md | 6 +- docs/ru/docs/tutorial/schema-extra-example.md | 28 ++-- docs/ru/docs/tutorial/security/first-steps.md | 18 +-- docs/ru/docs/tutorial/static-files.md | 2 +- docs/ru/docs/tutorial/testing.md | 18 +-- docs/tr/docs/advanced/testing-websockets.md | 2 +- docs/tr/docs/advanced/wsgi.md | 2 +- docs/tr/docs/python-types.md | 28 ++-- docs/tr/docs/tutorial/cookie-params.md | 20 +-- docs/tr/docs/tutorial/first-steps.md | 16 +- docs/tr/docs/tutorial/path-params.md | 20 +-- docs/tr/docs/tutorial/query-params.md | 20 +-- docs/tr/docs/tutorial/request-forms.md | 12 +- docs/tr/docs/tutorial/static-files.md | 2 +- docs/uk/docs/python-types.md | 48 +++--- docs/uk/docs/tutorial/body-fields.md | 20 +-- docs/uk/docs/tutorial/body.md | 24 +-- docs/uk/docs/tutorial/cookie-params.md | 20 +-- docs/uk/docs/tutorial/encoder.md | 4 +- docs/uk/docs/tutorial/extra-data-types.md | 20 +-- docs/uk/docs/tutorial/first-steps.md | 14 +- docs/vi/docs/python-types.md | 56 +++---- docs/vi/docs/tutorial/first-steps.md | 16 +- docs/zh/docs/advanced/additional-responses.md | 8 +- .../docs/advanced/additional-status-codes.md | 2 +- .../zh/docs/advanced/advanced-dependencies.md | 8 +- docs/zh/docs/advanced/behind-a-proxy.md | 8 +- docs/zh/docs/advanced/custom-response.md | 22 +-- docs/zh/docs/advanced/dataclasses.md | 6 +- docs/zh/docs/advanced/events.md | 4 +- docs/zh/docs/advanced/generate-clients.md | 14 +- docs/zh/docs/advanced/middleware.md | 6 +- docs/zh/docs/advanced/openapi-callbacks.md | 8 +- .../path-operation-advanced-configuration.md | 8 +- .../advanced/response-change-status-code.md | 2 +- docs/zh/docs/advanced/response-cookies.md | 4 +- docs/zh/docs/advanced/response-directly.md | 4 +- docs/zh/docs/advanced/response-headers.md | 4 +- .../docs/advanced/security/http-basic-auth.md | 18 +-- .../docs/advanced/security/oauth2-scopes.md | 16 +- docs/zh/docs/advanced/settings.md | 32 ++-- docs/zh/docs/advanced/sub-applications.md | 6 +- docs/zh/docs/advanced/templates.md | 8 +- docs/zh/docs/advanced/testing-database.md | 8 +- docs/zh/docs/advanced/testing-dependencies.md | 2 +- docs/zh/docs/advanced/testing-events.md | 2 +- docs/zh/docs/advanced/testing-websockets.md | 2 +- .../docs/advanced/using-request-directly.md | 2 +- docs/zh/docs/advanced/websockets.md | 20 +-- docs/zh/docs/advanced/wsgi.md | 2 +- docs/zh/docs/how-to/configure-swagger-ui.md | 8 +- docs/zh/docs/python-types.md | 26 ++-- docs/zh/docs/tutorial/background-tasks.md | 16 +- docs/zh/docs/tutorial/bigger-applications.md | 26 ++-- docs/zh/docs/tutorial/body-fields.md | 20 +-- docs/zh/docs/tutorial/body-multiple-params.md | 44 +++--- docs/zh/docs/tutorial/body-nested-models.md | 56 +++---- docs/zh/docs/tutorial/body-updates.md | 8 +- docs/zh/docs/tutorial/body.md | 24 +-- docs/zh/docs/tutorial/cookie-params.md | 20 +-- docs/zh/docs/tutorial/cors.md | 2 +- docs/zh/docs/tutorial/debugging.md | 2 +- .../dependencies/classes-as-dependencies.md | 28 ++-- ...pendencies-in-path-operation-decorators.md | 8 +- .../dependencies/dependencies-with-yield.md | 40 ++--- .../dependencies/global-dependencies.md | 2 +- docs/zh/docs/tutorial/dependencies/index.md | 6 +- .../tutorial/dependencies/sub-dependencies.md | 6 +- docs/zh/docs/tutorial/encoder.md | 4 +- docs/zh/docs/tutorial/extra-data-types.md | 20 +-- docs/zh/docs/tutorial/extra-models.md | 20 +-- docs/zh/docs/tutorial/first-steps.md | 16 +- docs/zh/docs/tutorial/handling-errors.md | 16 +- docs/zh/docs/tutorial/header-params.md | 42 ++--- docs/zh/docs/tutorial/metadata.md | 10 +- docs/zh/docs/tutorial/middleware.md | 4 +- .../tutorial/path-operation-configuration.md | 12 +- .../path-params-numeric-validations.md | 30 ++-- docs/zh/docs/tutorial/path-params.md | 18 +-- .../tutorial/query-params-str-validations.md | 36 ++--- docs/zh/docs/tutorial/query-params.md | 20 +-- docs/zh/docs/tutorial/request-files.md | 20 +-- .../docs/tutorial/request-forms-and-files.md | 4 +- docs/zh/docs/tutorial/request-forms.md | 4 +- docs/zh/docs/tutorial/response-model.md | 30 ++-- docs/zh/docs/tutorial/response-status-code.md | 6 +- docs/zh/docs/tutorial/schema-extra-example.md | 18 +-- docs/zh/docs/tutorial/security/first-steps.md | 10 +- .../tutorial/security/get-current-user.md | 12 +- docs/zh/docs/tutorial/security/oauth2-jwt.md | 32 ++-- .../docs/tutorial/security/simple-oauth2.md | 10 +- docs/zh/docs/tutorial/sql-databases.md | 74 ++++----- docs/zh/docs/tutorial/static-files.md | 2 +- docs/zh/docs/tutorial/testing.md | 18 +-- 529 files changed, 4747 insertions(+), 4748 deletions(-) diff --git a/docs/bn/docs/python-types.md b/docs/bn/docs/python-types.md index d5304a65e..4a602b679 100644 --- a/docs/bn/docs/python-types.md +++ b/docs/bn/docs/python-types.md @@ -23,7 +23,7 @@ Python-এ ঐচ্ছিক "টাইপ হিন্ট" (যা "টাই চলুন একটি সাধারণ উদাহরণ দিয়ে শুরু করি: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` এই প্রোগ্রামটি কল করলে আউটপুট হয়: @@ -39,7 +39,7 @@ John Doe * তাদেরকে মাঝখানে একটি স্পেস দিয়ে concatenate করে। ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### এটি সম্পাদনা করুন @@ -83,7 +83,7 @@ John Doe এগুলিই "টাইপ হিন্ট": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` এটি ডিফল্ট ভ্যালু ঘোষণা করার মত নয় যেমন: @@ -113,7 +113,7 @@ John Doe এই ফাংশনটি দেখুন, এটিতে ইতিমধ্যে টাইপ হিন্ট রয়েছে: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` এডিটর ভেরিয়েবলগুলির টাইপ জানার কারণে, আপনি শুধুমাত্র অটোকমপ্লিশনই পান না, আপনি এরর চেকও পান: @@ -123,7 +123,7 @@ John Doe এখন আপনি জানেন যে আপনাকে এটি ঠিক করতে হবে, `age`-কে একটি স্ট্রিং হিসেবে রূপান্তর করতে `str(age)` ব্যবহার করতে হবে: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## টাইপ ঘোষণা @@ -144,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### টাইপ প্যারামিটার সহ জেনেরিক টাইপ @@ -182,7 +182,7 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে ব্যবহার করুন: ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006_py39.py!} +{!> ../../docs_src/python_types/tutorial006_py39.py!} ``` //// @@ -192,7 +192,7 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ `typing` থেকে `List` (বড় হাতের `L` দিয়ে) ইমপোর্ট করুন: ``` Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে। @@ -202,7 +202,7 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে করুন: ```Python hl_lines="4" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` //// @@ -240,7 +240,7 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial007_py39.py!} +{!> ../../docs_src/python_types/tutorial007_py39.py!} ``` //// @@ -248,7 +248,7 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial007.py!} +{!> ../../docs_src/python_types/tutorial007.py!} ``` //// @@ -269,7 +269,7 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008_py39.py!} +{!> ../../docs_src/python_types/tutorial008_py39.py!} ``` //// @@ -277,7 +277,7 @@ Python যত এগিয়ে যাচ্ছে, **নতুন সংস্ //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008.py!} +{!> ../../docs_src/python_types/tutorial008.py!} ``` //// @@ -299,7 +299,7 @@ Python 3.10-এ একটি **নতুন সিনট্যাক্স** আ //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +{!> ../../docs_src/python_types/tutorial008b_py310.py!} ``` //// @@ -307,7 +307,7 @@ Python 3.10-এ একটি **নতুন সিনট্যাক্স** আ //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008b.py!} +{!> ../../docs_src/python_types/tutorial008b.py!} ``` //// @@ -321,7 +321,7 @@ Python 3.10-এ একটি **নতুন সিনট্যাক্স** আ Python 3.6 এবং তার উপরের সংস্করণগুলিতে (Python 3.10 অনতর্ভুক্ত) আপনি `typing` মডিউল থেকে `Optional` ইমপোর্ট করে এটি ঘোষণা এবং ব্যবহার করতে পারেন। ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` `Optional[str]` ব্যবহার করা মানে হল শুধু `str` নয়, এটি হতে পারে `None`-ও, যা আপনার এডিটরকে সেই ত্রুটিগুলি শনাক্ত করতে সাহায্য করবে যেখানে আপনি ধরে নিচ্ছেন যে একটি মান সবসময় `str` হবে, অথচ এটি `None`-ও হতে পারেও। @@ -333,7 +333,7 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial009_py310.py!} +{!> ../../docs_src/python_types/tutorial009_py310.py!} ``` //// @@ -341,7 +341,7 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009.py!} +{!> ../../docs_src/python_types/tutorial009.py!} ``` //// @@ -349,7 +349,7 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি //// tab | Python 3.8+ বিকল্প ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009b.py!} +{!> ../../docs_src/python_types/tutorial009b.py!} ``` //// @@ -370,7 +370,7 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি একটি উদাহরণ হিসেবে, এই ফাংশনটি নিন: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c.py!} +{!../../docs_src/python_types/tutorial009c.py!} ``` `name` প্যারামিটারটি `Optional[str]` হিসেবে সংজ্ঞায়িত হয়েছে, কিন্তু এটি **অপশনাল নয়**, আপনি প্যারামিটার ছাড়া ফাংশনটি কল করতে পারবেন না: @@ -388,7 +388,7 @@ say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉 সুখবর হল, একবার আপনি Python 3.10 ব্যবহার করা শুরু করলে, আপনাকে এগুলোর ব্যাপারে আর চিন্তা করতে হবে না, যেহুতু আপনি | ব্যবহার করেই ইউনিয়ন ঘোষণা করতে পারবেন: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c_py310.py!} +{!../../docs_src/python_types/tutorial009c_py310.py!} ``` এবং তারপর আপনাকে নামগুলি যেমন `Optional` এবং `Union` নিয়ে আর চিন্তা করতে হবে না। 😎 @@ -452,13 +452,13 @@ Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্য ধরুন আপনার কাছে `Person` নামে একটি ক্লাস আছে, যার একটি নাম আছে: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` তারপর আপনি একটি ভেরিয়েবলকে `Person` টাইপের হিসেবে ঘোষণা করতে পারেন: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` এবং তারপর, আবার, আপনি এডিটর সাপোর্ট পেয়ে যাবেন: @@ -486,7 +486,7 @@ Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্য //// tab | Python 3.10+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py310.py!} +{!> ../../docs_src/python_types/tutorial011_py310.py!} ``` //// @@ -494,7 +494,7 @@ Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্য //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py39.py!} +{!> ../../docs_src/python_types/tutorial011_py39.py!} ``` //// @@ -502,7 +502,7 @@ Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্য //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/python_types/tutorial011.py!} +{!> ../../docs_src/python_types/tutorial011.py!} ``` //// @@ -532,7 +532,7 @@ Python-এ এমন একটি ফিচার আছে যা `Annotated` Python 3.9-এ, `Annotated` স্ট্যান্ডার্ড লাইব্রেরিতে অন্তর্ভুক্ত, তাই আপনি এটি `typing` থেকে ইমপোর্ট করতে পারেন। ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial013_py39.py!} +{!> ../../docs_src/python_types/tutorial013_py39.py!} ``` //// @@ -544,7 +544,7 @@ Python 3.9-এর নীচের সংস্করণগুলিতে, আ এটি **FastAPI** এর সাথে ইতিমদ্ধে ইনস্টল হয়ে থাকবে। ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial013.py!} +{!> ../../docs_src/python_types/tutorial013.py!} ``` //// diff --git a/docs/de/docs/advanced/additional-responses.md b/docs/de/docs/advanced/additional-responses.md index 6f2c4b2dd..a87c56491 100644 --- a/docs/de/docs/advanced/additional-responses.md +++ b/docs/de/docs/advanced/additional-responses.md @@ -27,7 +27,7 @@ Jedes dieser Response-`dict`s kann einen Schlüssel `model` haben, welcher ein P Um beispielsweise eine weitere Response mit dem Statuscode `404` und einem Pydantic-Modell `Message` zu deklarieren, können Sie schreiben: ```Python hl_lines="18 22" -{!../../../docs_src/additional_responses/tutorial001.py!} +{!../../docs_src/additional_responses/tutorial001.py!} ``` /// note | "Hinweis" @@ -178,7 +178,7 @@ Sie können denselben `responses`-Parameter verwenden, um verschiedene Medientyp Sie können beispielsweise einen zusätzlichen Medientyp `image/png` hinzufügen und damit deklarieren, dass Ihre *Pfadoperation* ein JSON-Objekt (mit dem Medientyp `application/json`) oder ein PNG-Bild zurückgeben kann: ```Python hl_lines="19-24 28" -{!../../../docs_src/additional_responses/tutorial002.py!} +{!../../docs_src/additional_responses/tutorial002.py!} ``` /// note | "Hinweis" @@ -208,7 +208,7 @@ Sie können beispielsweise eine Response mit dem Statuscode `404` deklarieren, d Und eine Response mit dem Statuscode `200`, die Ihr `response_model` verwendet, aber ein benutzerdefiniertes Beispiel (`example`) enthält: ```Python hl_lines="20-31" -{!../../../docs_src/additional_responses/tutorial003.py!} +{!../../docs_src/additional_responses/tutorial003.py!} ``` Es wird alles kombiniert und in Ihre OpenAPI eingebunden und in der API-Dokumentation angezeigt: @@ -244,7 +244,7 @@ Mit dieser Technik können Sie einige vordefinierte Responses in Ihren *Pfadoper Zum Beispiel: ```Python hl_lines="13-17 26" -{!../../../docs_src/additional_responses/tutorial004.py!} +{!../../docs_src/additional_responses/tutorial004.py!} ``` ## Weitere Informationen zu OpenAPI-Responses diff --git a/docs/de/docs/advanced/additional-status-codes.md b/docs/de/docs/advanced/additional-status-codes.md index 672efee51..fc8d09e4c 100644 --- a/docs/de/docs/advanced/additional-status-codes.md +++ b/docs/de/docs/advanced/additional-status-codes.md @@ -17,7 +17,7 @@ Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt //// tab | Python 3.10+ ```Python hl_lines="4 25" -{!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_an_py310.py!} ``` //// @@ -25,7 +25,7 @@ Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt //// tab | Python 3.9+ ```Python hl_lines="4 25" -{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_an_py39.py!} ``` //// @@ -33,7 +33,7 @@ Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt //// tab | Python 3.8+ ```Python hl_lines="4 26" -{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_an.py!} ``` //// @@ -47,7 +47,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="2 23" -{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_py310.py!} ``` //// @@ -61,7 +61,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="4 25" -{!> ../../../docs_src/additional_status_codes/tutorial001.py!} +{!> ../../docs_src/additional_status_codes/tutorial001.py!} ``` //// diff --git a/docs/de/docs/advanced/advanced-dependencies.md b/docs/de/docs/advanced/advanced-dependencies.md index f29970872..54351714e 100644 --- a/docs/de/docs/advanced/advanced-dependencies.md +++ b/docs/de/docs/advanced/advanced-dependencies.md @@ -21,7 +21,7 @@ Dazu deklarieren wir eine Methode `__call__`: //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -29,7 +29,7 @@ Dazu deklarieren wir eine Methode `__call__`: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -43,7 +43,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// @@ -57,7 +57,7 @@ Und jetzt können wir `__init__` verwenden, um die Parameter der Instanz zu dekl //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -65,7 +65,7 @@ Und jetzt können wir `__init__` verwenden, um die Parameter der Instanz zu dekl //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -79,7 +79,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// @@ -93,7 +93,7 @@ Wir könnten eine Instanz dieser Klasse erstellen mit: //// tab | Python 3.9+ ```Python hl_lines="18" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -101,7 +101,7 @@ Wir könnten eine Instanz dieser Klasse erstellen mit: //// tab | Python 3.8+ ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -115,7 +115,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// @@ -137,7 +137,7 @@ checker(q="somequery") //// tab | Python 3.9+ ```Python hl_lines="22" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -145,7 +145,7 @@ checker(q="somequery") //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -159,7 +159,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md index e56841faa..93ff84b8a 100644 --- a/docs/de/docs/advanced/async-tests.md +++ b/docs/de/docs/advanced/async-tests.md @@ -33,13 +33,13 @@ Betrachten wir als einfaches Beispiel eine Dateistruktur ähnlich der in [Größ Die Datei `main.py` hätte als Inhalt: ```Python -{!../../../docs_src/async_tests/main.py!} +{!../../docs_src/async_tests/main.py!} ``` Die Datei `test_main.py` hätte die Tests für `main.py`, das könnte jetzt so aussehen: ```Python -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` ## Es ausführen @@ -61,7 +61,7 @@ $ pytest Der Marker `@pytest.mark.anyio` teilt pytest mit, dass diese Testfunktion asynchron aufgerufen werden soll: ```Python hl_lines="7" -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` /// tip | "Tipp" @@ -73,7 +73,7 @@ Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wi Dann können wir einen `AsyncClient` mit der App erstellen und mit `await` asynchrone Requests an ihn senden. ```Python hl_lines="9-12" -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` Das ist das Äquivalent zu: diff --git a/docs/de/docs/advanced/behind-a-proxy.md b/docs/de/docs/advanced/behind-a-proxy.md index 18f90ebde..74b25308a 100644 --- a/docs/de/docs/advanced/behind-a-proxy.md +++ b/docs/de/docs/advanced/behind-a-proxy.md @@ -19,7 +19,7 @@ In diesem Fall würde der ursprüngliche Pfad `/app` tatsächlich unter `/api/v1 Auch wenn Ihr gesamter Code unter der Annahme geschrieben ist, dass es nur `/app` gibt. ```Python hl_lines="6" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} +{!../../docs_src/behind_a_proxy/tutorial001.py!} ``` Und der Proxy würde das **Pfadpräfix** on-the-fly **"entfernen**", bevor er die Anfrage an Uvicorn übermittelt, dafür sorgend, dass Ihre Anwendung davon überzeugt ist, dass sie unter `/app` bereitgestellt wird, sodass Sie nicht Ihren gesamten Code dahingehend aktualisieren müssen, das Präfix `/api/v1` zu verwenden. @@ -99,7 +99,7 @@ Sie können den aktuellen `root_path` abrufen, der von Ihrer Anwendung für jede Hier fügen wir ihn, nur zu Demonstrationszwecken, in die Nachricht ein. ```Python hl_lines="8" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} +{!../../docs_src/behind_a_proxy/tutorial001.py!} ``` Wenn Sie Uvicorn dann starten mit: @@ -128,7 +128,7 @@ wäre die Response etwa: Falls Sie keine Möglichkeit haben, eine Kommandozeilenoption wie `--root-path` oder ähnlich zu übergeben, können Sie als Alternative beim Erstellen Ihrer FastAPI-Anwendung den Parameter `root_path` setzen: ```Python hl_lines="3" -{!../../../docs_src/behind_a_proxy/tutorial002.py!} +{!../../docs_src/behind_a_proxy/tutorial002.py!} ``` Die Übergabe des `root_path` an `FastAPI` wäre das Äquivalent zur Übergabe der `--root-path`-Kommandozeilenoption an Uvicorn oder Hypercorn. @@ -310,7 +310,7 @@ Wenn Sie eine benutzerdefinierte Liste von Servern (`servers`) übergeben und es Zum Beispiel: ```Python hl_lines="4-7" -{!../../../docs_src/behind_a_proxy/tutorial003.py!} +{!../../docs_src/behind_a_proxy/tutorial003.py!} ``` Erzeugt ein OpenAPI-Schema, wie: @@ -359,7 +359,7 @@ Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server Wenn Sie nicht möchten, dass **FastAPI** einen automatischen Server inkludiert, welcher `root_path` verwendet, können Sie den Parameter `root_path_in_servers=False` verwenden: ```Python hl_lines="9" -{!../../../docs_src/behind_a_proxy/tutorial004.py!} +{!../../docs_src/behind_a_proxy/tutorial004.py!} ``` Dann wird er nicht in das OpenAPI-Schema aufgenommen. diff --git a/docs/de/docs/advanced/custom-response.md b/docs/de/docs/advanced/custom-response.md index 20d6a039a..357d2c562 100644 --- a/docs/de/docs/advanced/custom-response.md +++ b/docs/de/docs/advanced/custom-response.md @@ -31,7 +31,7 @@ Das liegt daran, dass FastAPI standardmäßig jedes enthaltene Element überprü Wenn Sie jedoch sicher sind, dass der von Ihnen zurückgegebene Inhalt **mit JSON serialisierbar** ist, können Sie ihn direkt an die Response-Klasse übergeben und die zusätzliche Arbeit vermeiden, die FastAPI hätte, indem es Ihren zurückgegebenen Inhalt durch den `jsonable_encoder` leitet, bevor es ihn an die Response-Klasse übergibt. ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001b.py!} +{!../../docs_src/custom_response/tutorial001b.py!} ``` /// info @@ -58,7 +58,7 @@ Um eine Response mit HTML direkt von **FastAPI** zurückzugeben, verwenden Sie ` * Übergeben Sie `HTMLResponse` als den Parameter `response_class` Ihres *Pfadoperation-Dekorators*. ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial002.py!} +{!../../docs_src/custom_response/tutorial002.py!} ``` /// info @@ -78,7 +78,7 @@ Wie in [Eine Response direkt zurückgeben](response-directly.md){.internal-link Das gleiche Beispiel von oben, das eine `HTMLResponse` zurückgibt, könnte so aussehen: ```Python hl_lines="2 7 19" -{!../../../docs_src/custom_response/tutorial003.py!} +{!../../docs_src/custom_response/tutorial003.py!} ``` /// warning | "Achtung" @@ -104,7 +104,7 @@ Die `response_class` wird dann nur zur Dokumentation der OpenAPI-Pfadoperation* Es könnte zum Beispiel so etwas sein: ```Python hl_lines="7 21 23" -{!../../../docs_src/custom_response/tutorial004.py!} +{!../../docs_src/custom_response/tutorial004.py!} ``` In diesem Beispiel generiert die Funktion `generate_html_response()` bereits eine `Response` und gibt sie zurück, anstatt das HTML in einem `str` zurückzugeben. @@ -145,7 +145,7 @@ Sie akzeptiert die folgenden Parameter: FastAPI (eigentlich Starlette) fügt automatisch einen Content-Length-Header ein. Außerdem wird es einen Content-Type-Header einfügen, der auf dem media_type basiert, und für Texttypen einen Zeichensatz (charset) anfügen. ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ### `HTMLResponse` @@ -157,7 +157,7 @@ Nimmt Text oder Bytes entgegen und gibt eine HTML-Response zurück, wie Sie oben Nimmt Text oder Bytes entgegen und gibt eine Plain-Text-Response zurück. ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial005.py!} +{!../../docs_src/custom_response/tutorial005.py!} ``` ### `JSONResponse` @@ -181,7 +181,7 @@ Eine alternative JSON-Response mit `dataclasses`: ```Python hl_lines="1 7-12 19-20" -{!../../../docs_src/dataclasses/tutorial001.py!} +{!../../docs_src/dataclasses/tutorial001.py!} ``` Das ist dank **Pydantic** ebenfalls möglich, da es `dataclasses` intern unterstützt. @@ -35,7 +35,7 @@ Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Tr Sie können `dataclasses` auch im Parameter `response_model` verwenden: ```Python hl_lines="1 7-13 19" -{!../../../docs_src/dataclasses/tutorial002.py!} +{!../../docs_src/dataclasses/tutorial002.py!} ``` Die Datenklasse wird automatisch in eine Pydantic-Datenklasse konvertiert. @@ -53,7 +53,7 @@ In einigen Fällen müssen Sie möglicherweise immer noch Pydantics Version von In diesem Fall können Sie einfach die Standard-`dataclasses` durch `pydantic.dataclasses` ersetzen, was einen direkten Ersatz darstellt: ```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } -{!../../../docs_src/dataclasses/tutorial003.py!} +{!../../docs_src/dataclasses/tutorial003.py!} ``` 1. Wir importieren `field` weiterhin von Standard-`dataclasses`. diff --git a/docs/de/docs/advanced/events.md b/docs/de/docs/advanced/events.md index e898db49b..b0c4d3922 100644 --- a/docs/de/docs/advanced/events.md +++ b/docs/de/docs/advanced/events.md @@ -31,7 +31,7 @@ Beginnen wir mit einem Beispiel und sehen es uns dann im Detail an. Wir erstellen eine asynchrone Funktion `lifespan()` mit `yield` wie folgt: ```Python hl_lines="16 19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` Hier simulieren wir das langsame *Hochfahren*, das Laden des Modells, indem wir die (Fake-)Modellfunktion vor dem `yield` in das Dictionary mit Modellen für maschinelles Lernen einfügen. Dieser Code wird ausgeführt, **bevor** die Anwendung **beginnt, Requests entgegenzunehmen**, während des *Hochfahrens*. @@ -51,7 +51,7 @@ Möglicherweise müssen Sie eine neue Version starten, oder Sie haben es einfach Das Erste, was auffällt, ist, dass wir eine asynchrone Funktion mit `yield` definieren. Das ist sehr ähnlich zu Abhängigkeiten mit `yield`. ```Python hl_lines="14-19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` Der erste Teil der Funktion, vor dem `yield`, wird ausgeführt **bevor** die Anwendung startet. @@ -65,7 +65,7 @@ Wie Sie sehen, ist die Funktion mit einem `@asynccontextmanager` versehen. Dadurch wird die Funktion in einen sogenannten „**asynchronen Kontextmanager**“ umgewandelt. ```Python hl_lines="1 13" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` Ein **Kontextmanager** in Python ist etwas, das Sie in einer `with`-Anweisung verwenden können, zum Beispiel kann `open()` als Kontextmanager verwendet werden: @@ -89,7 +89,7 @@ In unserem obigen Codebeispiel verwenden wir ihn nicht direkt, sondern übergebe Der Parameter `lifespan` der `FastAPI`-App benötigt einen **asynchronen Kontextmanager**, wir können ihm also unseren neuen asynchronen Kontextmanager `lifespan` übergeben. ```Python hl_lines="22" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` ## Alternative Events (deprecated) @@ -113,7 +113,7 @@ Diese Funktionen können mit `async def` oder normalem `def` deklariert werden. Um eine Funktion hinzuzufügen, die vor dem Start der Anwendung ausgeführt werden soll, deklarieren Sie diese mit dem Event `startup`: ```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} +{!../../docs_src/events/tutorial001.py!} ``` In diesem Fall initialisiert die Eventhandler-Funktion `startup` die „Datenbank“ der Items (nur ein `dict`) mit einigen Werten. @@ -127,7 +127,7 @@ Und Ihre Anwendung empfängt erst dann Anfragen, wenn alle `startup`-Eventhandle Um eine Funktion hinzuzufügen, die beim Herunterfahren der Anwendung ausgeführt werden soll, deklarieren Sie sie mit dem Event `shutdown`: ```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} +{!../../docs_src/events/tutorial002.py!} ``` Hier schreibt die `shutdown`-Eventhandler-Funktion eine Textzeile `"Application shutdown"` in eine Datei `log.txt`. diff --git a/docs/de/docs/advanced/generate-clients.md b/docs/de/docs/advanced/generate-clients.md index b8d66fdd7..80c44b3f9 100644 --- a/docs/de/docs/advanced/generate-clients.md +++ b/docs/de/docs/advanced/generate-clients.md @@ -31,7 +31,7 @@ Beginnen wir mit einer einfachen FastAPI-Anwendung: //// tab | Python 3.9+ ```Python hl_lines="7-9 12-13 16-17 21" -{!> ../../../docs_src/generate_clients/tutorial001_py39.py!} +{!> ../../docs_src/generate_clients/tutorial001_py39.py!} ``` //// @@ -39,7 +39,7 @@ Beginnen wir mit einer einfachen FastAPI-Anwendung: //// tab | Python 3.8+ ```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../../docs_src/generate_clients/tutorial001.py!} +{!> ../../docs_src/generate_clients/tutorial001.py!} ``` //// @@ -150,7 +150,7 @@ Beispielsweise könnten Sie einen Abschnitt für **Items (Artikel)** und einen w //// tab | Python 3.9+ ```Python hl_lines="21 26 34" -{!> ../../../docs_src/generate_clients/tutorial002_py39.py!} +{!> ../../docs_src/generate_clients/tutorial002_py39.py!} ``` //// @@ -158,7 +158,7 @@ Beispielsweise könnten Sie einen Abschnitt für **Items (Artikel)** und einen w //// tab | Python 3.8+ ```Python hl_lines="23 28 36" -{!> ../../../docs_src/generate_clients/tutorial002.py!} +{!> ../../docs_src/generate_clients/tutorial002.py!} ``` //// @@ -211,7 +211,7 @@ Anschließend können Sie diese benutzerdefinierte Funktion als Parameter `gener //// tab | Python 3.9+ ```Python hl_lines="6-7 10" -{!> ../../../docs_src/generate_clients/tutorial003_py39.py!} +{!> ../../docs_src/generate_clients/tutorial003_py39.py!} ``` //// @@ -219,7 +219,7 @@ Anschließend können Sie diese benutzerdefinierte Funktion als Parameter `gener //// tab | Python 3.8+ ```Python hl_lines="8-9 12" -{!> ../../../docs_src/generate_clients/tutorial003.py!} +{!> ../../docs_src/generate_clients/tutorial003.py!} ``` //// @@ -247,7 +247,7 @@ Wir könnten das OpenAPI-JSON in eine Datei `openapi.json` herunterladen und dan //// tab | Python ```Python -{!> ../../../docs_src/generate_clients/tutorial004.py!} +{!> ../../docs_src/generate_clients/tutorial004.py!} ``` //// @@ -255,7 +255,7 @@ Wir könnten das OpenAPI-JSON in eine Datei `openapi.json` herunterladen und dan //// tab | Node.js ```Javascript -{!> ../../../docs_src/generate_clients/tutorial004.js!} +{!> ../../docs_src/generate_clients/tutorial004.js!} ``` //// diff --git a/docs/de/docs/advanced/middleware.md b/docs/de/docs/advanced/middleware.md index 8912225fb..b4001efda 100644 --- a/docs/de/docs/advanced/middleware.md +++ b/docs/de/docs/advanced/middleware.md @@ -58,7 +58,7 @@ Erzwingt, dass alle eingehenden Requests entweder `https` oder `wss` sein müsse Alle eingehenden Requests an `http` oder `ws` werden stattdessen an das sichere Schema umgeleitet. ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial001.py!} +{!../../docs_src/advanced_middleware/tutorial001.py!} ``` ## `TrustedHostMiddleware` @@ -66,7 +66,7 @@ Alle eingehenden Requests an `http` oder `ws` werden stattdessen an das sichere Erzwingt, dass alle eingehenden Requests einen korrekt gesetzten `Host`-Header haben, um sich vor HTTP-Host-Header-Angriffen zu schützen. ```Python hl_lines="2 6-8" -{!../../../docs_src/advanced_middleware/tutorial002.py!} +{!../../docs_src/advanced_middleware/tutorial002.py!} ``` Die folgenden Argumente werden unterstützt: @@ -82,7 +82,7 @@ Verarbeitet GZip-Responses für alle Requests, die `"gzip"` im `Accept-Encoding` Diese Middleware verarbeitet sowohl Standard- als auch Streaming-Responses. ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial003.py!} +{!../../docs_src/advanced_middleware/tutorial003.py!} ``` Die folgenden Argumente werden unterstützt: diff --git a/docs/de/docs/advanced/openapi-callbacks.md b/docs/de/docs/advanced/openapi-callbacks.md index d7b5bc885..f407d5450 100644 --- a/docs/de/docs/advanced/openapi-callbacks.md +++ b/docs/de/docs/advanced/openapi-callbacks.md @@ -32,7 +32,7 @@ Sie verfügt über eine *Pfadoperation*, die einen `Invoice`-Body empfängt, und Dieser Teil ist ziemlich normal, der größte Teil des Codes ist Ihnen wahrscheinlich bereits bekannt: ```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` /// tip | "Tipp" @@ -93,7 +93,7 @@ Wenn Sie diese Sichtweise (des *externen Entwicklers*) vorübergehend übernehme Erstellen Sie zunächst einen neuen `APIRouter`, der einen oder mehrere Callbacks enthält. ```Python hl_lines="3 25" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` ### Die Callback-*Pfadoperation* erstellen @@ -106,7 +106,7 @@ Sie sollte wie eine normale FastAPI-*Pfadoperation* aussehen: * Und sie könnte auch eine Deklaration der Response enthalten, die zurückgegeben werden soll, z. B. `response_model=InvoiceEventReceived`. ```Python hl_lines="16-18 21-22 28-32" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` Es gibt zwei Hauptunterschiede zu einer normalen *Pfadoperation*: @@ -176,7 +176,7 @@ An diesem Punkt haben Sie die benötigte(n) *Callback-Pfadoperation(en)* (diejen Verwenden Sie nun den Parameter `callbacks` im *Pfadoperation-Dekorator Ihrer API*, um das Attribut `.routes` (das ist eigentlich nur eine `list`e von Routen/*Pfadoperationen*) dieses Callback-Routers zu übergeben: ```Python hl_lines="35" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` /// tip | "Tipp" diff --git a/docs/de/docs/advanced/openapi-webhooks.md b/docs/de/docs/advanced/openapi-webhooks.md index fb0daa908..9f1bb6959 100644 --- a/docs/de/docs/advanced/openapi-webhooks.md +++ b/docs/de/docs/advanced/openapi-webhooks.md @@ -33,7 +33,7 @@ Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.9 Wenn Sie eine **FastAPI**-Anwendung erstellen, gibt es ein `webhooks`-Attribut, mit dem Sie *Webhooks* definieren können, genauso wie Sie *Pfadoperationen* definieren würden, zum Beispiel mit `@app.webhooks.post()`. ```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_webhooks/tutorial001.py!} +{!../../docs_src/openapi_webhooks/tutorial001.py!} ``` Die von Ihnen definierten Webhooks landen im **OpenAPI**-Schema und der automatischen **Dokumentations-Oberfläche**. diff --git a/docs/de/docs/advanced/path-operation-advanced-configuration.md b/docs/de/docs/advanced/path-operation-advanced-configuration.md index c9cb82fe3..2d8b88be5 100644 --- a/docs/de/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/de/docs/advanced/path-operation-advanced-configuration.md @@ -13,7 +13,7 @@ Mit dem Parameter `operation_id` können Sie die OpenAPI `operationId` festlegen Sie müssten sicherstellen, dass sie für jede Operation eindeutig ist. ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} ``` ### Verwendung des Namens der *Pfadoperation-Funktion* als operationId @@ -23,7 +23,7 @@ Wenn Sie die Funktionsnamen Ihrer API als `operationId`s verwenden möchten, kö Sie sollten dies tun, nachdem Sie alle Ihre *Pfadoperationen* hinzugefügt haben. ```Python hl_lines="2 12-21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` /// tip | "Tipp" @@ -45,7 +45,7 @@ Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden. Um eine *Pfadoperation* aus dem generierten OpenAPI-Schema (und damit aus den automatischen Dokumentationssystemen) auszuschließen, verwenden Sie den Parameter `include_in_schema` und setzen Sie ihn auf `False`: ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} ``` ## Fortgeschrittene Beschreibung mittels Docstring @@ -57,7 +57,7 @@ Das Hinzufügen eines `\f` (ein maskiertes „Form Feed“-Zeichen) führt dazu, Sie wird nicht in der Dokumentation angezeigt, aber andere Tools (z. B. Sphinx) können den Rest verwenden. ```Python hl_lines="19-29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} ``` ## Zusätzliche Responses @@ -101,7 +101,7 @@ Sie können das OpenAPI-Schema für eine *Pfadoperation* erweitern, indem Sie de Dieses `openapi_extra` kann beispielsweise hilfreich sein, um OpenAPI-Erweiterungen zu deklarieren: ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial005.py!} ``` Wenn Sie die automatische API-Dokumentation öffnen, wird Ihre Erweiterung am Ende der spezifischen *Pfadoperation* angezeigt. @@ -150,7 +150,7 @@ Sie könnten sich beispielsweise dafür entscheiden, den Request mit Ihrem eigen Das könnte man mit `openapi_extra` machen: ```Python hl_lines="20-37 39-40" -{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial006.py!} ``` In diesem Beispiel haben wir kein Pydantic-Modell deklariert. Tatsächlich wird der Requestbody nicht einmal als JSON geparst, sondern direkt als `bytes` gelesen und die Funktion `magic_data_reader ()` wäre dafür verantwortlich, ihn in irgendeiner Weise zu parsen. @@ -168,7 +168,7 @@ In der folgenden Anwendung verwenden wir beispielsweise weder die integrierte Fu //// tab | Pydantic v2 ```Python hl_lines="17-22 24" -{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` //// @@ -176,7 +176,7 @@ In der folgenden Anwendung verwenden wir beispielsweise weder die integrierte Fu //// tab | Pydantic v1 ```Python hl_lines="17-22 24" -{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} ``` //// @@ -196,7 +196,7 @@ Und dann parsen wir in unserem Code diesen YAML-Inhalt direkt und verwenden dann //// tab | Pydantic v2 ```Python hl_lines="26-33" -{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` //// @@ -204,7 +204,7 @@ Und dann parsen wir in unserem Code diesen YAML-Inhalt direkt und verwenden dann //// tab | Pydantic v1 ```Python hl_lines="26-33" -{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} ``` //// diff --git a/docs/de/docs/advanced/response-change-status-code.md b/docs/de/docs/advanced/response-change-status-code.md index bba908a3e..202df0d87 100644 --- a/docs/de/docs/advanced/response-change-status-code.md +++ b/docs/de/docs/advanced/response-change-status-code.md @@ -21,7 +21,7 @@ Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* Anschließend können Sie den `status_code` in diesem *vorübergehenden* Response-Objekt festlegen. ```Python hl_lines="1 9 12" -{!../../../docs_src/response_change_status_code/tutorial001.py!} +{!../../docs_src/response_change_status_code/tutorial001.py!} ``` Und dann können Sie wie gewohnt jedes benötigte Objekt zurückgeben (ein `dict`, ein Datenbankmodell usw.). diff --git a/docs/de/docs/advanced/response-cookies.md b/docs/de/docs/advanced/response-cookies.md index 3d2043565..ba100870d 100644 --- a/docs/de/docs/advanced/response-cookies.md +++ b/docs/de/docs/advanced/response-cookies.md @@ -7,7 +7,7 @@ Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* Und dann können Sie Cookies in diesem *vorübergehenden* Response-Objekt setzen. ```Python hl_lines="1 8-9" -{!../../../docs_src/response_cookies/tutorial002.py!} +{!../../docs_src/response_cookies/tutorial002.py!} ``` Anschließend können Sie wie gewohnt jedes gewünschte Objekt zurückgeben (ein `dict`, ein Datenbankmodell, usw.). @@ -27,7 +27,7 @@ Dazu können Sie eine Response erstellen, wie unter [Eine Response direkt zurüc Setzen Sie dann Cookies darin und geben Sie sie dann zurück: ```Python hl_lines="10-12" -{!../../../docs_src/response_cookies/tutorial001.py!} +{!../../docs_src/response_cookies/tutorial001.py!} ``` /// tip | "Tipp" diff --git a/docs/de/docs/advanced/response-directly.md b/docs/de/docs/advanced/response-directly.md index 377490b56..70c045f57 100644 --- a/docs/de/docs/advanced/response-directly.md +++ b/docs/de/docs/advanced/response-directly.md @@ -35,7 +35,7 @@ Sie können beispielsweise kein Pydantic-Modell in eine `JSONResponse` einfügen In diesen Fällen können Sie den `jsonable_encoder` verwenden, um Ihre Daten zu konvertieren, bevor Sie sie an eine Response übergeben: ```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` /// note | "Technische Details" @@ -57,7 +57,7 @@ Nehmen wir an, Sie möchten eine ../../../docs_src/security/tutorial006_an_py39.py!} +{!> ../../docs_src/security/tutorial006_an_py39.py!} ``` //// @@ -31,7 +31,7 @@ Wenn Sie dann den Benutzernamen und das Passwort eingeben, sendet der Browser di //// tab | Python 3.8+ ```Python hl_lines="2 7 11" -{!> ../../../docs_src/security/tutorial006_an.py!} +{!> ../../docs_src/security/tutorial006_an.py!} ``` //// @@ -45,7 +45,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="2 6 10" -{!> ../../../docs_src/security/tutorial006.py!} +{!> ../../docs_src/security/tutorial006.py!} ``` //// @@ -71,7 +71,7 @@ Dann können wir `secrets.compare_digest()` verwenden, um sicherzustellen, dass //// tab | Python 3.9+ ```Python hl_lines="1 12-24" -{!> ../../../docs_src/security/tutorial007_an_py39.py!} +{!> ../../docs_src/security/tutorial007_an_py39.py!} ``` //// @@ -79,7 +79,7 @@ Dann können wir `secrets.compare_digest()` verwenden, um sicherzustellen, dass //// tab | Python 3.8+ ```Python hl_lines="1 12-24" -{!> ../../../docs_src/security/tutorial007_an.py!} +{!> ../../docs_src/security/tutorial007_an.py!} ``` //// @@ -93,7 +93,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1 11-21" -{!> ../../../docs_src/security/tutorial007.py!} +{!> ../../docs_src/security/tutorial007.py!} ``` //// @@ -163,7 +163,7 @@ Nachdem Sie festgestellt haben, dass die Anmeldeinformationen falsch sind, geben //// tab | Python 3.9+ ```Python hl_lines="26-30" -{!> ../../../docs_src/security/tutorial007_an_py39.py!} +{!> ../../docs_src/security/tutorial007_an_py39.py!} ``` //// @@ -171,7 +171,7 @@ Nachdem Sie festgestellt haben, dass die Anmeldeinformationen falsch sind, geben //// tab | Python 3.8+ ```Python hl_lines="26-30" -{!> ../../../docs_src/security/tutorial007_an.py!} +{!> ../../docs_src/security/tutorial007_an.py!} ``` //// @@ -185,7 +185,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="23-27" -{!> ../../../docs_src/security/tutorial007.py!} +{!> ../../docs_src/security/tutorial007.py!} ``` //// diff --git a/docs/de/docs/advanced/security/oauth2-scopes.md b/docs/de/docs/advanced/security/oauth2-scopes.md index f02707698..c0af2560a 100644 --- a/docs/de/docs/advanced/security/oauth2-scopes.md +++ b/docs/de/docs/advanced/security/oauth2-scopes.md @@ -65,7 +65,7 @@ Sehen wir uns zunächst kurz die Teile an, die sich gegenüber den Beispielen im //// tab | Python 3.10+ ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -73,7 +73,7 @@ Sehen wir uns zunächst kurz die Teile an, die sich gegenüber den Beispielen im //// tab | Python 3.9+ ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -81,7 +81,7 @@ Sehen wir uns zunächst kurz die Teile an, die sich gegenüber den Beispielen im //// tab | Python 3.8+ ```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -95,7 +95,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -109,7 +109,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -123,7 +123,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -139,7 +139,7 @@ Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und des //// tab | Python 3.10+ ```Python hl_lines="62-65" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -147,7 +147,7 @@ Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und des //// tab | Python 3.9+ ```Python hl_lines="62-65" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -155,7 +155,7 @@ Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und des //// tab | Python 3.8+ ```Python hl_lines="63-66" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -169,7 +169,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="61-64" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -183,7 +183,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="62-65" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -197,7 +197,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="62-65" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -229,7 +229,7 @@ Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwe //// tab | Python 3.10+ ```Python hl_lines="155" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -237,7 +237,7 @@ Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwe //// tab | Python 3.9+ ```Python hl_lines="155" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -245,7 +245,7 @@ Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwe //// tab | Python 3.8+ ```Python hl_lines="156" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -259,7 +259,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="154" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -273,7 +273,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="155" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -287,7 +287,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="155" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -319,7 +319,7 @@ Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen //// tab | Python 3.10+ ```Python hl_lines="4 139 170" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -327,7 +327,7 @@ Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen //// tab | Python 3.9+ ```Python hl_lines="4 139 170" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -335,7 +335,7 @@ Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen //// tab | Python 3.8+ ```Python hl_lines="4 140 171" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -349,7 +349,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="3 138 167" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -363,7 +363,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="4 139 168" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -377,7 +377,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="4 139 168" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -409,7 +409,7 @@ Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um d //// tab | Python 3.10+ ```Python hl_lines="8 105" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -417,7 +417,7 @@ Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um d //// tab | Python 3.9+ ```Python hl_lines="8 105" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -425,7 +425,7 @@ Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um d //// tab | Python 3.8+ ```Python hl_lines="8 106" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -439,7 +439,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7 104" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -453,7 +453,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8 105" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -467,7 +467,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8 105" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -487,7 +487,7 @@ In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als du //// tab | Python 3.10+ ```Python hl_lines="105 107-115" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -495,7 +495,7 @@ In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als du //// tab | Python 3.9+ ```Python hl_lines="105 107-115" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -503,7 +503,7 @@ In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als du //// tab | Python 3.8+ ```Python hl_lines="106 108-116" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -517,7 +517,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="104 106-114" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -531,7 +531,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="105 107-115" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -545,7 +545,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="105 107-115" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -567,7 +567,7 @@ Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, u //// tab | Python 3.10+ ```Python hl_lines="46 116-127" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -575,7 +575,7 @@ Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, u //// tab | Python 3.9+ ```Python hl_lines="46 116-127" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -583,7 +583,7 @@ Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, u //// tab | Python 3.8+ ```Python hl_lines="47 117-128" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -597,7 +597,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="45 115-126" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -611,7 +611,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="46 116-127" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -625,7 +625,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="46 116-127" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -639,7 +639,7 @@ Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen //// tab | Python 3.10+ ```Python hl_lines="128-134" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -647,7 +647,7 @@ Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen //// tab | Python 3.9+ ```Python hl_lines="128-134" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -655,7 +655,7 @@ Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen //// tab | Python 3.8+ ```Python hl_lines="129-135" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -669,7 +669,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="127-133" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -683,7 +683,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="128-134" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -697,7 +697,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="128-134" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// diff --git a/docs/de/docs/advanced/settings.md b/docs/de/docs/advanced/settings.md index 3cd4c6c7d..8b9ba2f48 100644 --- a/docs/de/docs/advanced/settings.md +++ b/docs/de/docs/advanced/settings.md @@ -181,7 +181,7 @@ Sie können dieselben Validierungs-Funktionen und -Tools verwenden, die Sie für //// tab | Pydantic v2 ```Python hl_lines="2 5-8 11" -{!> ../../../docs_src/settings/tutorial001.py!} +{!> ../../docs_src/settings/tutorial001.py!} ``` //// @@ -195,7 +195,7 @@ In Pydantic v1 würden Sie `BaseSettings` direkt von `pydantic` statt von `pydan /// ```Python hl_lines="2 5-8 11" -{!> ../../../docs_src/settings/tutorial001_pv1.py!} +{!> ../../docs_src/settings/tutorial001_pv1.py!} ``` //// @@ -215,7 +215,7 @@ Als Nächstes werden die Daten konvertiert und validiert. Wenn Sie also dieses ` Dann können Sie das neue `settings`-Objekt in Ihrer Anwendung verwenden: ```Python hl_lines="18-20" -{!../../../docs_src/settings/tutorial001.py!} +{!../../docs_src/settings/tutorial001.py!} ``` ### Den Server ausführen @@ -251,13 +251,13 @@ Sie könnten diese Einstellungen in eine andere Moduldatei einfügen, wie Sie in Sie könnten beispielsweise eine Datei `config.py` haben mit: ```Python -{!../../../docs_src/settings/app01/config.py!} +{!../../docs_src/settings/app01/config.py!} ``` Und dann verwenden Sie diese in einer Datei `main.py`: ```Python hl_lines="3 11-13" -{!../../../docs_src/settings/app01/main.py!} +{!../../docs_src/settings/app01/main.py!} ``` /// tip | "Tipp" @@ -277,7 +277,7 @@ Dies könnte besonders beim Testen nützlich sein, da es sehr einfach ist, eine Ausgehend vom vorherigen Beispiel könnte Ihre Datei `config.py` so aussehen: ```Python hl_lines="10" -{!../../../docs_src/settings/app02/config.py!} +{!../../docs_src/settings/app02/config.py!} ``` Beachten Sie, dass wir jetzt keine Standardinstanz `settings = Settings()` erstellen. @@ -289,7 +289,7 @@ Jetzt erstellen wir eine Abhängigkeit, die ein neues `config.Settings()` zurüc //// tab | Python 3.9+ ```Python hl_lines="6 12-13" -{!> ../../../docs_src/settings/app02_an_py39/main.py!} +{!> ../../docs_src/settings/app02_an_py39/main.py!} ``` //// @@ -297,7 +297,7 @@ Jetzt erstellen wir eine Abhängigkeit, die ein neues `config.Settings()` zurüc //// tab | Python 3.8+ ```Python hl_lines="6 12-13" -{!> ../../../docs_src/settings/app02_an/main.py!} +{!> ../../docs_src/settings/app02_an/main.py!} ``` //// @@ -311,7 +311,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="5 11-12" -{!> ../../../docs_src/settings/app02/main.py!} +{!> ../../docs_src/settings/app02/main.py!} ``` //// @@ -329,7 +329,7 @@ Und dann können wir das von der *Pfadoperation-Funktion* als Abhängigkeit einf //// tab | Python 3.9+ ```Python hl_lines="17 19-21" -{!> ../../../docs_src/settings/app02_an_py39/main.py!} +{!> ../../docs_src/settings/app02_an_py39/main.py!} ``` //// @@ -337,7 +337,7 @@ Und dann können wir das von der *Pfadoperation-Funktion* als Abhängigkeit einf //// tab | Python 3.8+ ```Python hl_lines="17 19-21" -{!> ../../../docs_src/settings/app02_an/main.py!} +{!> ../../docs_src/settings/app02_an/main.py!} ``` //// @@ -351,7 +351,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="16 18-20" -{!> ../../../docs_src/settings/app02/main.py!} +{!> ../../docs_src/settings/app02/main.py!} ``` //// @@ -361,7 +361,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. Dann wäre es sehr einfach, beim Testen ein anderes Einstellungsobjekt bereitzustellen, indem man eine Abhängigkeitsüberschreibung für `get_settings` erstellt: ```Python hl_lines="9-10 13 21" -{!../../../docs_src/settings/app02/test_main.py!} +{!../../docs_src/settings/app02/test_main.py!} ``` Bei der Abhängigkeitsüberschreibung legen wir einen neuen Wert für `admin_email` fest, wenn wir das neue `Settings`-Objekt erstellen, und geben dann dieses neue Objekt zurück. @@ -406,7 +406,7 @@ Und dann aktualisieren Sie Ihre `config.py` mit: //// tab | Pydantic v2 ```Python hl_lines="9" -{!> ../../../docs_src/settings/app03_an/config.py!} +{!> ../../docs_src/settings/app03_an/config.py!} ``` /// tip | "Tipp" @@ -420,7 +420,7 @@ Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. //// tab | Pydantic v1 ```Python hl_lines="9-10" -{!> ../../../docs_src/settings/app03_an/config_pv1.py!} +{!> ../../docs_src/settings/app03_an/config_pv1.py!} ``` /// tip | "Tipp" @@ -465,7 +465,7 @@ Da wir jedoch den `@lru_cache`-Dekorator oben verwenden, wird das `Settings`-Obj //// tab | Python 3.9+ ```Python hl_lines="1 11" -{!> ../../../docs_src/settings/app03_an_py39/main.py!} +{!> ../../docs_src/settings/app03_an_py39/main.py!} ``` //// @@ -473,7 +473,7 @@ Da wir jedoch den `@lru_cache`-Dekorator oben verwenden, wird das `Settings`-Obj //// tab | Python 3.8+ ```Python hl_lines="1 11" -{!> ../../../docs_src/settings/app03_an/main.py!} +{!> ../../docs_src/settings/app03_an/main.py!} ``` //// @@ -487,7 +487,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1 10" -{!> ../../../docs_src/settings/app03/main.py!} +{!> ../../docs_src/settings/app03/main.py!} ``` //// diff --git a/docs/de/docs/advanced/sub-applications.md b/docs/de/docs/advanced/sub-applications.md index 7dfaaa0cd..172b8d3c1 100644 --- a/docs/de/docs/advanced/sub-applications.md +++ b/docs/de/docs/advanced/sub-applications.md @@ -11,7 +11,7 @@ Wenn Sie zwei unabhängige FastAPI-Anwendungen mit deren eigenen unabhängigen O Erstellen Sie zunächst die Hauptanwendung **FastAPI** und deren *Pfadoperationen*: ```Python hl_lines="3 6-8" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Unteranwendung @@ -21,7 +21,7 @@ Erstellen Sie dann Ihre Unteranwendung und deren *Pfadoperationen*. Diese Unteranwendung ist nur eine weitere Standard-FastAPI-Anwendung, aber diese wird „gemountet“: ```Python hl_lines="11 14-16" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Die Unteranwendung mounten @@ -31,7 +31,7 @@ Mounten Sie in Ihrer Top-Level-Anwendung `app` die Unteranwendung `subapi`. In diesem Fall wird sie im Pfad `/subapi` gemountet: ```Python hl_lines="11 19" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Es in der automatischen API-Dokumentation betrachten diff --git a/docs/de/docs/advanced/templates.md b/docs/de/docs/advanced/templates.md index abc7624f1..6cb3fcf6c 100644 --- a/docs/de/docs/advanced/templates.md +++ b/docs/de/docs/advanced/templates.md @@ -28,7 +28,7 @@ $ pip install jinja2 * Verwenden Sie die von Ihnen erstellten `templates`, um eine `TemplateResponse` zu rendern und zurückzugeben, übergeben Sie den Namen des Templates, das Requestobjekt und ein „Kontext“-Dictionary mit Schlüssel-Wert-Paaren, die innerhalb des Jinja2-Templates verwendet werden sollen. ```Python hl_lines="4 11 15-18" -{!../../../docs_src/templates/tutorial001.py!} +{!../../docs_src/templates/tutorial001.py!} ``` /// note | "Hinweis" @@ -58,7 +58,7 @@ Sie können auch `from starlette.templating import Jinja2Templates` verwenden. Dann können Sie unter `templates/item.html` ein Template erstellen, mit z. B. folgendem Inhalt: ```jinja hl_lines="7" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` ### Template-Kontextwerte @@ -112,13 +112,13 @@ Mit beispielsweise der ID `42` würde dies Folgendes ergeben: Sie können `url_for()` innerhalb des Templates auch beispielsweise mit den `StaticFiles` verwenden, die Sie mit `name="static"` gemountet haben. ```jinja hl_lines="4" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` In diesem Beispiel würde das zu einer CSS-Datei unter `static/styles.css` verlinken, mit folgendem Inhalt: ```CSS hl_lines="4" -{!../../../docs_src/templates/static/styles.css!} +{!../../docs_src/templates/static/styles.css!} ``` Und da Sie `StaticFiles` verwenden, wird diese CSS-Datei automatisch von Ihrer **FastAPI**-Anwendung unter der URL `/static/styles.css` bereitgestellt. diff --git a/docs/de/docs/advanced/testing-dependencies.md b/docs/de/docs/advanced/testing-dependencies.md index f131d27cd..c565b30f2 100644 --- a/docs/de/docs/advanced/testing-dependencies.md +++ b/docs/de/docs/advanced/testing-dependencies.md @@ -31,7 +31,7 @@ Und dann ruft **FastAPI** diese Überschreibung anstelle der ursprünglichen Abh //// tab | Python 3.10+ ```Python hl_lines="26-27 30" -{!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} +{!> ../../docs_src/dependency_testing/tutorial001_an_py310.py!} ``` //// @@ -39,7 +39,7 @@ Und dann ruft **FastAPI** diese Überschreibung anstelle der ursprünglichen Abh //// tab | Python 3.9+ ```Python hl_lines="28-29 32" -{!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} +{!> ../../docs_src/dependency_testing/tutorial001_an_py39.py!} ``` //// @@ -47,7 +47,7 @@ Und dann ruft **FastAPI** diese Überschreibung anstelle der ursprünglichen Abh //// tab | Python 3.8+ ```Python hl_lines="29-30 33" -{!> ../../../docs_src/dependency_testing/tutorial001_an.py!} +{!> ../../docs_src/dependency_testing/tutorial001_an.py!} ``` //// @@ -61,7 +61,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="24-25 28" -{!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} +{!> ../../docs_src/dependency_testing/tutorial001_py310.py!} ``` //// @@ -75,7 +75,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="28-29 32" -{!> ../../../docs_src/dependency_testing/tutorial001.py!} +{!> ../../docs_src/dependency_testing/tutorial001.py!} ``` //// diff --git a/docs/de/docs/advanced/testing-events.md b/docs/de/docs/advanced/testing-events.md index f50093548..3e63791c6 100644 --- a/docs/de/docs/advanced/testing-events.md +++ b/docs/de/docs/advanced/testing-events.md @@ -3,5 +3,5 @@ Wenn Sie in Ihren Tests Ihre Event-Handler (`startup` und `shutdown`) ausführen wollen, können Sie den `TestClient` mit einer `with`-Anweisung verwenden: ```Python hl_lines="9-12 20-24" -{!../../../docs_src/app_testing/tutorial003.py!} +{!../../docs_src/app_testing/tutorial003.py!} ``` diff --git a/docs/de/docs/advanced/testing-websockets.md b/docs/de/docs/advanced/testing-websockets.md index 4cbc45c17..7ae7d92d6 100644 --- a/docs/de/docs/advanced/testing-websockets.md +++ b/docs/de/docs/advanced/testing-websockets.md @@ -5,7 +5,7 @@ Sie können den schon bekannten `TestClient` zum Testen von WebSockets verwenden Dazu verwenden Sie den `TestClient` in einer `with`-Anweisung, eine Verbindung zum WebSocket herstellend: ```Python hl_lines="27-31" -{!../../../docs_src/app_testing/tutorial002.py!} +{!../../docs_src/app_testing/tutorial002.py!} ``` /// note | "Hinweis" diff --git a/docs/de/docs/advanced/using-request-directly.md b/docs/de/docs/advanced/using-request-directly.md index 1d575a7cb..6a0b96680 100644 --- a/docs/de/docs/advanced/using-request-directly.md +++ b/docs/de/docs/advanced/using-request-directly.md @@ -30,7 +30,7 @@ Angenommen, Sie möchten auf die IP-Adresse/den Host des Clients in Ihrer *Pfado Dazu müssen Sie direkt auf den Request zugreifen. ```Python hl_lines="1 7-8" -{!../../../docs_src/using_request_directly/tutorial001.py!} +{!../../docs_src/using_request_directly/tutorial001.py!} ``` Durch die Deklaration eines *Pfadoperation-Funktionsparameters*, dessen Typ der `Request` ist, weiß **FastAPI**, dass es den `Request` diesem Parameter übergeben soll. diff --git a/docs/de/docs/advanced/websockets.md b/docs/de/docs/advanced/websockets.md index 6d772b6c9..cf13fa23c 100644 --- a/docs/de/docs/advanced/websockets.md +++ b/docs/de/docs/advanced/websockets.md @@ -39,7 +39,7 @@ In der Produktion hätten Sie eine der oben genannten Optionen. Aber es ist die einfachste Möglichkeit, sich auf die Serverseite von WebSockets zu konzentrieren und ein funktionierendes Beispiel zu haben: ```Python hl_lines="2 6-38 41-43" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` ## Einen `websocket` erstellen @@ -47,7 +47,7 @@ Aber es ist die einfachste Möglichkeit, sich auf die Serverseite von WebSockets Erstellen Sie in Ihrer **FastAPI**-Anwendung einen `websocket`: ```Python hl_lines="1 46-47" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` /// note | "Technische Details" @@ -63,7 +63,7 @@ Sie können auch `from starlette.websockets import WebSocket` verwenden. In Ihrer WebSocket-Route können Sie Nachrichten `await`en und Nachrichten senden. ```Python hl_lines="48-52" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` Sie können Binär-, Text- und JSON-Daten empfangen und senden. @@ -118,7 +118,7 @@ Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfa //// tab | Python 3.10+ ```Python hl_lines="68-69 82" -{!> ../../../docs_src/websockets/tutorial002_an_py310.py!} +{!> ../../docs_src/websockets/tutorial002_an_py310.py!} ``` //// @@ -126,7 +126,7 @@ Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfa //// tab | Python 3.9+ ```Python hl_lines="68-69 82" -{!> ../../../docs_src/websockets/tutorial002_an_py39.py!} +{!> ../../docs_src/websockets/tutorial002_an_py39.py!} ``` //// @@ -134,7 +134,7 @@ Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfa //// tab | Python 3.8+ ```Python hl_lines="69-70 83" -{!> ../../../docs_src/websockets/tutorial002_an.py!} +{!> ../../docs_src/websockets/tutorial002_an.py!} ``` //// @@ -148,7 +148,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="66-67 79" -{!> ../../../docs_src/websockets/tutorial002_py310.py!} +{!> ../../docs_src/websockets/tutorial002_py310.py!} ``` //// @@ -162,7 +162,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="68-69 81" -{!> ../../../docs_src/websockets/tutorial002.py!} +{!> ../../docs_src/websockets/tutorial002.py!} ``` //// @@ -213,7 +213,7 @@ Wenn eine WebSocket-Verbindung geschlossen wird, löst `await websocket.receive_ //// tab | Python 3.9+ ```Python hl_lines="79-81" -{!> ../../../docs_src/websockets/tutorial003_py39.py!} +{!> ../../docs_src/websockets/tutorial003_py39.py!} ``` //// @@ -221,7 +221,7 @@ Wenn eine WebSocket-Verbindung geschlossen wird, löst `await websocket.receive_ //// tab | Python 3.8+ ```Python hl_lines="81-83" -{!> ../../../docs_src/websockets/tutorial003.py!} +{!> ../../docs_src/websockets/tutorial003.py!} ``` //// diff --git a/docs/de/docs/advanced/wsgi.md b/docs/de/docs/advanced/wsgi.md index 19ff90a90..50abc84d1 100644 --- a/docs/de/docs/advanced/wsgi.md +++ b/docs/de/docs/advanced/wsgi.md @@ -13,7 +13,7 @@ Wrappen Sie dann die WSGI-Anwendung (z. B. Flask) mit der Middleware. Und dann mounten Sie das auf einem Pfad. ```Python hl_lines="2-3 23" -{!../../../docs_src/wsgi/tutorial001.py!} +{!../../docs_src/wsgi/tutorial001.py!} ``` ## Es ansehen diff --git a/docs/de/docs/how-to/conditional-openapi.md b/docs/de/docs/how-to/conditional-openapi.md index 7f277bb88..a0a4983bb 100644 --- a/docs/de/docs/how-to/conditional-openapi.md +++ b/docs/de/docs/how-to/conditional-openapi.md @@ -30,7 +30,7 @@ Sie können problemlos dieselben Pydantic-Einstellungen verwenden, um Ihre gener Zum Beispiel: ```Python hl_lines="6 11" -{!../../../docs_src/conditional_openapi/tutorial001.py!} +{!../../docs_src/conditional_openapi/tutorial001.py!} ``` Hier deklarieren wir die Einstellung `openapi_url` mit dem gleichen Defaultwert `"/openapi.json"`. diff --git a/docs/de/docs/how-to/configure-swagger-ui.md b/docs/de/docs/how-to/configure-swagger-ui.md index 7d62a14d3..31b9cd290 100644 --- a/docs/de/docs/how-to/configure-swagger-ui.md +++ b/docs/de/docs/how-to/configure-swagger-ui.md @@ -19,7 +19,7 @@ Ohne Änderung der Einstellungen ist die Syntaxhervorhebung standardmäßig akti Sie können sie jedoch deaktivieren, indem Sie `syntaxHighlight` auf `False` setzen: ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial001.py!} +{!../../docs_src/configure_swagger_ui/tutorial001.py!} ``` ... und dann zeigt die Swagger-Oberfläche die Syntaxhervorhebung nicht mehr an: @@ -31,7 +31,7 @@ Sie können sie jedoch deaktivieren, indem Sie `syntaxHighlight` auf `False` set Auf die gleiche Weise könnten Sie das Theme der Syntaxhervorhebung mit dem Schlüssel `syntaxHighlight.theme` festlegen (beachten Sie, dass er einen Punkt in der Mitte hat): ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial002.py!} +{!../../docs_src/configure_swagger_ui/tutorial002.py!} ``` Obige Konfiguration würde das Theme für die Farbe der Syntaxhervorhebung ändern: @@ -45,7 +45,7 @@ FastAPI enthält einige Defaultkonfigurationsparameter, die für die meisten Anw Es umfasst die folgenden Defaultkonfigurationen: ```Python -{!../../../fastapi/openapi/docs.py[ln:7-23]!} +{!../../fastapi/openapi/docs.py[ln:7-23]!} ``` Sie können jede davon überschreiben, indem Sie im Argument `swagger_ui_parameters` einen anderen Wert festlegen. @@ -53,7 +53,7 @@ Sie können jede davon überschreiben, indem Sie im Argument `swagger_ui_paramet Um beispielsweise `deepLinking` zu deaktivieren, könnten Sie folgende Einstellungen an `swagger_ui_parameters` übergeben: ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial003.py!} +{!../../docs_src/configure_swagger_ui/tutorial003.py!} ``` ## Andere Parameter der Swagger-Oberfläche diff --git a/docs/de/docs/how-to/custom-docs-ui-assets.md b/docs/de/docs/how-to/custom-docs-ui-assets.md index e8750f7c2..e5fd20a10 100644 --- a/docs/de/docs/how-to/custom-docs-ui-assets.md +++ b/docs/de/docs/how-to/custom-docs-ui-assets.md @@ -19,7 +19,7 @@ Der erste Schritt besteht darin, die automatischen Dokumentationen zu deaktivier Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: ```Python hl_lines="8" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} +{!../../docs_src/custom_docs_ui/tutorial001.py!} ``` ### Die benutzerdefinierten Dokumentationen hinzufügen @@ -37,7 +37,7 @@ Sie können die internen Funktionen von FastAPI wiederverwenden, um die HTML-Sei Und genau so für ReDoc ... ```Python hl_lines="2-6 11-19 22-24 27-33" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} +{!../../docs_src/custom_docs_ui/tutorial001.py!} ``` /// tip | "Tipp" @@ -55,7 +55,7 @@ Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „U Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: ```Python hl_lines="36-38" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} +{!../../docs_src/custom_docs_ui/tutorial001.py!} ``` ### Es ausprobieren @@ -125,7 +125,7 @@ Danach könnte Ihre Dateistruktur wie folgt aussehen: * „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad. ```Python hl_lines="7 11" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` ### Die statischen Dateien testen @@ -159,7 +159,7 @@ Wie bei der Verwendung eines benutzerdefinierten CDN besteht der erste Schritt d Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: ```Python hl_lines="9" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` ### Die benutzerdefinierten Dokumentationen, mit statischen Dateien, hinzufügen @@ -177,7 +177,7 @@ Auch hier können Sie die internen Funktionen von FastAPI wiederverwenden, um di Und genau so für ReDoc ... ```Python hl_lines="2-6 14-22 25-27 30-36" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` /// tip | "Tipp" @@ -195,7 +195,7 @@ Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „U Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: ```Python hl_lines="39-41" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` ### Benutzeroberfläche, mit statischen Dateien, testen diff --git a/docs/de/docs/how-to/custom-request-and-route.md b/docs/de/docs/how-to/custom-request-and-route.md index a0c4a0e0c..f81fa1da3 100644 --- a/docs/de/docs/how-to/custom-request-and-route.md +++ b/docs/de/docs/how-to/custom-request-and-route.md @@ -43,7 +43,7 @@ Wenn der Header kein `gzip` enthält, wird nicht versucht, den Body zu dekomprim Auf diese Weise kann dieselbe Routenklasse gzip-komprimierte oder unkomprimierte Requests verarbeiten. ```Python hl_lines="8-15" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} +{!../../docs_src/custom_request_and_route/tutorial001.py!} ``` ### Eine benutzerdefinierte `GzipRoute`-Klasse erstellen @@ -57,7 +57,7 @@ Diese Methode gibt eine Funktion zurück. Und diese Funktion empfängt einen Req Hier verwenden wir sie, um aus dem ursprünglichen Request einen `GzipRequest` zu erstellen. ```Python hl_lines="18-26" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} +{!../../docs_src/custom_request_and_route/tutorial001.py!} ``` /// note | "Technische Details" @@ -97,13 +97,13 @@ Wir können denselben Ansatz auch verwenden, um in einem Exceptionhandler auf de Alles, was wir tun müssen, ist, den Request innerhalb eines `try`/`except`-Blocks zu handhaben: ```Python hl_lines="13 15" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} +{!../../docs_src/custom_request_and_route/tutorial002.py!} ``` Wenn eine Exception auftritt, befindet sich die `Request`-Instanz weiterhin im Gültigkeitsbereich, sodass wir den Requestbody lesen und bei der Fehlerbehandlung verwenden können: ```Python hl_lines="16-18" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} +{!../../docs_src/custom_request_and_route/tutorial002.py!} ``` ## Benutzerdefinierte `APIRoute`-Klasse in einem Router @@ -111,11 +111,11 @@ Wenn eine Exception auftritt, befindet sich die `Request`-Instanz weiterhin im G Sie können auch den Parameter `route_class` eines `APIRouter` festlegen: ```Python hl_lines="26" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} +{!../../docs_src/custom_request_and_route/tutorial003.py!} ``` In diesem Beispiel verwenden die *Pfadoperationen* unter dem `router` die benutzerdefinierte `TimedRoute`-Klasse und haben in der Response einen zusätzlichen `X-Response-Time`-Header mit der Zeit, die zum Generieren der Response benötigt wurde: ```Python hl_lines="13-20" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} +{!../../docs_src/custom_request_and_route/tutorial003.py!} ``` diff --git a/docs/de/docs/how-to/extending-openapi.md b/docs/de/docs/how-to/extending-openapi.md index 347c5bed3..c895fb860 100644 --- a/docs/de/docs/how-to/extending-openapi.md +++ b/docs/de/docs/how-to/extending-openapi.md @@ -44,7 +44,7 @@ Fügen wir beispielsweise Strawberry-Dokumentation. diff --git a/docs/de/docs/how-to/separate-openapi-schemas.md b/docs/de/docs/how-to/separate-openapi-schemas.md index eaecb27de..974341dd2 100644 --- a/docs/de/docs/how-to/separate-openapi-schemas.md +++ b/docs/de/docs/how-to/separate-openapi-schemas.md @@ -13,7 +13,7 @@ Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} # Code unterhalb weggelassen 👇 ``` @@ -22,7 +22,7 @@ Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: 👀 Vollständige Dateivorschau ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} ``` @@ -32,7 +32,7 @@ Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} # Code unterhalb weggelassen 👇 ``` @@ -41,7 +41,7 @@ Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: 👀 Vollständige Dateivorschau ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} ``` @@ -51,7 +51,7 @@ Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} # Code unterhalb weggelassen 👇 ``` @@ -60,7 +60,7 @@ Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: 👀 Vollständige Dateivorschau ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} ``` @@ -74,7 +74,7 @@ Wenn Sie dieses Modell wie hier als Eingabe verwenden: //// tab | Python 3.10+ ```Python hl_lines="14" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} # Code unterhalb weggelassen 👇 ``` @@ -83,7 +83,7 @@ Wenn Sie dieses Modell wie hier als Eingabe verwenden: 👀 Vollständige Dateivorschau ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} ``` @@ -93,7 +93,7 @@ Wenn Sie dieses Modell wie hier als Eingabe verwenden: //// tab | Python 3.9+ ```Python hl_lines="16" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} # Code unterhalb weggelassen 👇 ``` @@ -102,7 +102,7 @@ Wenn Sie dieses Modell wie hier als Eingabe verwenden: 👀 Vollständige Dateivorschau ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} ``` @@ -112,7 +112,7 @@ Wenn Sie dieses Modell wie hier als Eingabe verwenden: //// tab | Python 3.8+ ```Python hl_lines="16" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} # Code unterhalb weggelassen 👇 ``` @@ -121,7 +121,7 @@ Wenn Sie dieses Modell wie hier als Eingabe verwenden: 👀 Vollständige Dateivorschau ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} ``` @@ -145,7 +145,7 @@ Wenn Sie jedoch dasselbe Modell als Ausgabe verwenden, wie hier: //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} ``` //// @@ -153,7 +153,7 @@ Wenn Sie jedoch dasselbe Modell als Ausgabe verwenden, wie hier: //// tab | Python 3.9+ ```Python hl_lines="21" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} ``` //// @@ -161,7 +161,7 @@ Wenn Sie jedoch dasselbe Modell als Ausgabe verwenden, wie hier: //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} ``` //// @@ -226,7 +226,7 @@ Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` h //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} ``` //// @@ -234,7 +234,7 @@ Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` h //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} ``` //// @@ -242,7 +242,7 @@ Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` h //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial002.py!} ``` //// diff --git a/docs/de/docs/python-types.md b/docs/de/docs/python-types.md index 9bbff83d3..a43bf5ffe 100644 --- a/docs/de/docs/python-types.md +++ b/docs/de/docs/python-types.md @@ -23,7 +23,7 @@ Wenn Sie ein Python-Experte sind und bereits alles über Typhinweise wissen, üb Fangen wir mit einem einfachen Beispiel an: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Dieses Programm gibt aus: @@ -39,7 +39,7 @@ Die Funktion macht Folgendes: * Verkettet sie mit einem Leerzeichen in der Mitte. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Bearbeiten Sie es @@ -83,7 +83,7 @@ Das war's. Das sind die „Typhinweise“: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` Das ist nicht das gleiche wie das Deklarieren von Defaultwerten, wie es hier der Fall ist: @@ -113,7 +113,7 @@ Hier können Sie durch die Optionen blättern, bis Sie diejenige finden, bei der Sehen Sie sich diese Funktion an, sie hat bereits Typhinweise: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervollständigung, sondern auch eine Fehlerprüfung: @@ -123,7 +123,7 @@ Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervoll Jetzt, da Sie wissen, dass Sie das reparieren müssen, konvertieren Sie `age` mittels `str(age)` in einen String: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Deklarieren von Typen @@ -144,7 +144,7 @@ Zum Beispiel diese: * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Generische Typen mit Typ-Parametern @@ -182,7 +182,7 @@ Als Typ nehmen Sie `list`. Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst: ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006_py39.py!} +{!> ../../docs_src/python_types/tutorial006_py39.py!} ``` //// @@ -192,7 +192,7 @@ Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckige Von `typing` importieren Sie `List` (mit Großbuchstaben `L`): ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`). @@ -202,7 +202,7 @@ Als Typ nehmen Sie das `List`, das Sie von `typing` importiert haben. Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst: ```Python hl_lines="4" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` //// @@ -240,7 +240,7 @@ Das Gleiche gilt für die Deklaration eines Tupels – `tuple` – und einer Men //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial007_py39.py!} +{!> ../../docs_src/python_types/tutorial007_py39.py!} ``` //// @@ -248,7 +248,7 @@ Das Gleiche gilt für die Deklaration eines Tupels – `tuple` – und einer Men //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial007.py!} +{!> ../../docs_src/python_types/tutorial007.py!} ``` //// @@ -269,7 +269,7 @@ Der zweite Typ-Parameter ist für die Werte des `dict`: //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008_py39.py!} +{!> ../../docs_src/python_types/tutorial008_py39.py!} ``` //// @@ -277,7 +277,7 @@ Der zweite Typ-Parameter ist für die Werte des `dict`: //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008.py!} +{!> ../../docs_src/python_types/tutorial008.py!} ``` //// @@ -299,7 +299,7 @@ In Python 3.10 gibt es zusätzlich eine **neue Syntax**, die es erlaubt, die mö //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +{!> ../../docs_src/python_types/tutorial008b_py310.py!} ``` //// @@ -307,7 +307,7 @@ In Python 3.10 gibt es zusätzlich eine **neue Syntax**, die es erlaubt, die mö //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008b.py!} +{!> ../../docs_src/python_types/tutorial008b.py!} ``` //// @@ -321,7 +321,7 @@ Sie können deklarieren, dass ein Wert ein `str`, aber vielleicht auch `None` se In Python 3.6 und darüber (inklusive Python 3.10) können Sie das deklarieren, indem Sie `Optional` vom `typing` Modul importieren und verwenden. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Wenn Sie `Optional[str]` anstelle von nur `str` verwenden, wird Ihr Editor Ihnen dabei helfen, Fehler zu erkennen, bei denen Sie annehmen könnten, dass ein Wert immer eine String (`str`) ist, obwohl er auch `None` sein könnte. @@ -333,7 +333,7 @@ Das bedeutet auch, dass Sie in Python 3.10 `Something | None` verwenden können: //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial009_py310.py!} +{!> ../../docs_src/python_types/tutorial009_py310.py!} ``` //// @@ -341,7 +341,7 @@ Das bedeutet auch, dass Sie in Python 3.10 `Something | None` verwenden können: //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009.py!} +{!> ../../docs_src/python_types/tutorial009.py!} ``` //// @@ -349,7 +349,7 @@ Das bedeutet auch, dass Sie in Python 3.10 `Something | None` verwenden können: //// tab | Python 3.8+ Alternative ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009b.py!} +{!> ../../docs_src/python_types/tutorial009b.py!} ``` //// @@ -370,7 +370,7 @@ Es geht nur um Wörter und Namen. Aber diese Worte können beeinflussen, wie Sie Nehmen wir zum Beispiel diese Funktion: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c.py!} +{!../../docs_src/python_types/tutorial009c.py!} ``` Der Parameter `name` ist definiert als `Optional[str]`, aber er ist **nicht optional**, Sie können die Funktion nicht ohne diesen Parameter aufrufen: @@ -388,7 +388,7 @@ say_hi(name=None) # Das funktioniert, None is gültig 🎉 Die gute Nachricht ist, dass Sie sich darüber keine Sorgen mehr machen müssen, wenn Sie Python 3.10 verwenden, da Sie einfach `|` verwenden können, um Vereinigungen von Typen zu definieren: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c_py310.py!} +{!../../docs_src/python_types/tutorial009c_py310.py!} ``` Und dann müssen Sie sich nicht mehr um Namen wie `Optional` und `Union` kümmern. 😎 @@ -452,13 +452,13 @@ Sie können auch eine Klasse als Typ einer Variablen deklarieren. Nehmen wir an, Sie haben eine Klasse `Person`, mit einem Namen: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Dann können Sie eine Variable vom Typ `Person` deklarieren: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Und wiederum bekommen Sie die volle Editor-Unterstützung: @@ -486,7 +486,7 @@ Ein Beispiel aus der offiziellen Pydantic Dokumentation: //// tab | Python 3.10+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py310.py!} +{!> ../../docs_src/python_types/tutorial011_py310.py!} ``` //// @@ -494,7 +494,7 @@ Ein Beispiel aus der offiziellen Pydantic Dokumentation: //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py39.py!} +{!> ../../docs_src/python_types/tutorial011_py39.py!} ``` //// @@ -502,7 +502,7 @@ Ein Beispiel aus der offiziellen Pydantic Dokumentation: //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/python_types/tutorial011.py!} +{!> ../../docs_src/python_types/tutorial011.py!} ``` //// @@ -532,7 +532,7 @@ Python bietet auch die Möglichkeit, **zusätzliche Metadaten** in Typhinweisen In Python 3.9 ist `Annotated` ein Teil der Standardbibliothek, Sie können es von `typing` importieren. ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial013_py39.py!} +{!> ../../docs_src/python_types/tutorial013_py39.py!} ``` //// @@ -544,7 +544,7 @@ In Versionen niedriger als Python 3.9 importieren Sie `Annotated` von `typing_ex Es wird bereits mit **FastAPI** installiert sein. ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial013.py!} +{!> ../../docs_src/python_types/tutorial013.py!} ``` //// diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md index 0852288d5..cd857f5e7 100644 --- a/docs/de/docs/tutorial/background-tasks.md +++ b/docs/de/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ Hierzu zählen beispielsweise: Importieren Sie zunächst `BackgroundTasks` und definieren Sie einen Parameter in Ihrer *Pfadoperation-Funktion* mit der Typdeklaration `BackgroundTasks`: ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** erstellt für Sie das Objekt vom Typ `BackgroundTasks` und übergibt es als diesen Parameter. @@ -34,7 +34,7 @@ In diesem Fall schreibt die Taskfunktion in eine Datei (den Versand einer E-Mail Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir die Funktion mit normalem `def`: ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## Den Hintergrundtask hinzufügen @@ -42,7 +42,7 @@ Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir di Übergeben Sie innerhalb Ihrer *Pfadoperation-Funktion* Ihre Taskfunktion mit der Methode `.add_task()` an das *Hintergrundtasks*-Objekt: ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` erhält als Argumente: @@ -60,7 +60,7 @@ Die Verwendung von `BackgroundTasks` funktioniert auch mit dem ../../../docs_src/background_tasks/tutorial002_an_py310.py!} +{!> ../../docs_src/background_tasks/tutorial002_an_py310.py!} ``` //// @@ -68,7 +68,7 @@ Die Verwendung von `BackgroundTasks` funktioniert auch mit dem ../../../docs_src/background_tasks/tutorial002_an_py39.py!} +{!> ../../docs_src/background_tasks/tutorial002_an_py39.py!} ``` //// @@ -76,7 +76,7 @@ Die Verwendung von `BackgroundTasks` funktioniert auch mit dem ../../../docs_src/background_tasks/tutorial002_an.py!} +{!> ../../docs_src/background_tasks/tutorial002_an.py!} ``` //// @@ -90,7 +90,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11 13 20 23" -{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +{!> ../../docs_src/background_tasks/tutorial002_py310.py!} ``` //// @@ -104,7 +104,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002.py!} +{!> ../../docs_src/background_tasks/tutorial002.py!} ``` //// diff --git a/docs/de/docs/tutorial/bigger-applications.md b/docs/de/docs/tutorial/bigger-applications.md index 986a99a38..000fa1f43 100644 --- a/docs/de/docs/tutorial/bigger-applications.md +++ b/docs/de/docs/tutorial/bigger-applications.md @@ -86,7 +86,7 @@ Sie können die *Pfadoperationen* für dieses Modul mit `APIRouter` erstellen. Sie importieren ihn und erstellen eine „Instanz“ auf die gleiche Weise wie mit der Klasse `FastAPI`: ```Python hl_lines="1 3" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` ### *Pfadoperationen* mit `APIRouter` @@ -96,7 +96,7 @@ Und dann verwenden Sie ihn, um Ihre *Pfadoperationen* zu deklarieren. Verwenden Sie ihn auf die gleiche Weise wie die Klasse `FastAPI`: ```Python hl_lines="6 11 16" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` Sie können sich `APIRouter` als eine „Mini-`FastAPI`“-Klasse vorstellen. @@ -124,7 +124,7 @@ Wir werden nun eine einfache Abhängigkeit verwenden, um einen benutzerdefiniert //// tab | Python 3.9+ ```Python hl_lines="3 6-8" title="app/dependencies.py" -{!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!} ``` //// @@ -132,7 +132,7 @@ Wir werden nun eine einfache Abhängigkeit verwenden, um einen benutzerdefiniert //// tab | Python 3.8+ ```Python hl_lines="1 5-7" title="app/dependencies.py" -{!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} +{!> ../../docs_src/bigger_applications/app_an/dependencies.py!} ``` //// @@ -146,7 +146,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1 4-6" title="app/dependencies.py" -{!> ../../../docs_src/bigger_applications/app/dependencies.py!} +{!> ../../docs_src/bigger_applications/app/dependencies.py!} ``` //// @@ -182,7 +182,7 @@ Wir wissen, dass alle *Pfadoperationen* in diesem Modul folgendes haben: Anstatt also alles zu jeder *Pfadoperation* hinzuzufügen, können wir es dem `APIRouter` hinzufügen. ```Python hl_lines="5-10 16 21" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` Da der Pfad jeder *Pfadoperation* mit `/` beginnen muss, wie in: @@ -243,7 +243,7 @@ Und wir müssen die Abhängigkeitsfunktion aus dem Modul `app.dependencies` impo Daher verwenden wir einen relativen Import mit `..` für die Abhängigkeiten: ```Python hl_lines="3" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` #### Wie relative Importe funktionieren @@ -316,7 +316,7 @@ Wir fügen weder das Präfix `/items` noch `tags=["items"]` zu jeder *Pfadoperat Aber wir können immer noch _mehr_ `tags` hinzufügen, die auf eine bestimmte *Pfadoperation* angewendet werden, sowie einige zusätzliche `responses`, die speziell für diese *Pfadoperation* gelten: ```Python hl_lines="30-31" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` /// tip | "Tipp" @@ -344,7 +344,7 @@ Sie importieren und erstellen wie gewohnt eine `FastAPI`-Klasse. Und wir können sogar [globale Abhängigkeiten](dependencies/global-dependencies.md){.internal-link target=_blank} deklarieren, die mit den Abhängigkeiten für jeden `APIRouter` kombiniert werden: ```Python hl_lines="1 3 7" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### Den `APIRouter` importieren @@ -352,7 +352,7 @@ Und wir können sogar [globale Abhängigkeiten](dependencies/global-dependencies Jetzt importieren wir die anderen Submodule, die `APIRouter` haben: ```Python hl_lines="4-5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` Da es sich bei den Dateien `app/routers/users.py` und `app/routers/items.py` um Submodule handelt, die Teil desselben Python-Packages `app` sind, können wir einen einzelnen Punkt `.` verwenden, um sie mit „relativen Imports“ zu importieren. @@ -417,7 +417,7 @@ würde der `router` von `users` den von `items` überschreiben und wir könnten Um also beide in derselben Datei verwenden zu können, importieren wir die Submodule direkt: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` @@ -426,7 +426,7 @@ Um also beide in derselben Datei verwenden zu können, importieren wir die Submo Inkludieren wir nun die `router` aus diesen Submodulen `users` und `items`: ```Python hl_lines="10-11" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` /// info @@ -468,7 +468,7 @@ Sie enthält einen `APIRouter` mit einigen administrativen *Pfadoperationen*, di In diesem Beispiel wird es ganz einfach sein. Nehmen wir jedoch an, dass wir, da sie mit anderen Projekten in der Organisation geteilt wird, sie nicht ändern und kein `prefix`, `dependencies`, `tags`, usw. direkt zum `APIRouter` hinzufügen können: ```Python hl_lines="3" title="app/internal/admin.py" -{!../../../docs_src/bigger_applications/app/internal/admin.py!} +{!../../docs_src/bigger_applications/app/internal/admin.py!} ``` Aber wir möchten immer noch ein benutzerdefiniertes `prefix` festlegen, wenn wir den `APIRouter` einbinden, sodass alle seine *Pfadoperationen* mit `/admin` beginnen, wir möchten es mit den `dependencies` sichern, die wir bereits für dieses Projekt haben, und wir möchten `tags` und `responses` hinzufügen. @@ -476,7 +476,7 @@ Aber wir möchten immer noch ein benutzerdefiniertes `prefix` festlegen, wenn wi Wir können das alles deklarieren, ohne den ursprünglichen `APIRouter` ändern zu müssen, indem wir diese Parameter an `app.include_router()` übergeben: ```Python hl_lines="14-17" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` Auf diese Weise bleibt der ursprüngliche `APIRouter` unverändert, sodass wir dieselbe `app/internal/admin.py`-Datei weiterhin mit anderen Projekten in der Organisation teilen können. @@ -499,7 +499,7 @@ Wir können *Pfadoperationen* auch direkt zur `FastAPI`-App hinzufügen. Hier machen wir es ... nur um zu zeigen, dass wir es können 🤷: ```Python hl_lines="21-23" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` und es wird korrekt funktionieren, zusammen mit allen anderen *Pfadoperationen*, die mit `app.include_router()` hinzugefügt wurden. diff --git a/docs/de/docs/tutorial/body-fields.md b/docs/de/docs/tutorial/body-fields.md index 33f7713ee..d22524c67 100644 --- a/docs/de/docs/tutorial/body-fields.md +++ b/docs/de/docs/tutorial/body-fields.md @@ -9,7 +9,7 @@ Importieren Sie es zuerst: //// tab | Python 3.10+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ Importieren Sie es zuerst: //// tab | Python 3.9+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Importieren Sie es zuerst: //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="2" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// @@ -71,7 +71,7 @@ Dann können Sie `Field` mit Modellattributen deklarieren: //// tab | Python 3.10+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -79,7 +79,7 @@ Dann können Sie `Field` mit Modellattributen deklarieren: //// tab | Python 3.9+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -87,7 +87,7 @@ Dann können Sie `Field` mit Modellattributen deklarieren: //// tab | Python 3.8+ ```Python hl_lines="12-15" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -101,7 +101,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9-12" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -115,7 +115,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// diff --git a/docs/de/docs/tutorial/body-multiple-params.md b/docs/de/docs/tutorial/body-multiple-params.md index 977e17671..26ae73ebc 100644 --- a/docs/de/docs/tutorial/body-multiple-params.md +++ b/docs/de/docs/tutorial/body-multiple-params.md @@ -11,7 +11,7 @@ Und Sie können auch Body-Parameter als optional kennzeichnen, indem Sie den Def //// tab | Python 3.10+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} ``` //// @@ -19,7 +19,7 @@ Und Sie können auch Body-Parameter als optional kennzeichnen, indem Sie den Def //// tab | Python 3.9+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} ``` //// @@ -27,7 +27,7 @@ Und Sie können auch Body-Parameter als optional kennzeichnen, indem Sie den Def //// tab | Python 3.8+ ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} ``` //// @@ -41,7 +41,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="17-19" -{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} ``` //// @@ -55,7 +55,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +{!> ../../docs_src/body_multiple_params/tutorial001.py!} ``` //// @@ -84,7 +84,7 @@ Aber Sie können auch mehrere Body-Parameter deklarieren, z. B. `item` und `user //// tab | Python 3.10+ ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} ``` //// @@ -92,7 +92,7 @@ Aber Sie können auch mehrere Body-Parameter deklarieren, z. B. `item` und `user //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +{!> ../../docs_src/body_multiple_params/tutorial002.py!} ``` //// @@ -139,7 +139,7 @@ Aber Sie können **FastAPI** instruieren, ihn als weiteren Body-Schlüssel zu er //// tab | Python 3.10+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} ``` //// @@ -147,7 +147,7 @@ Aber Sie können **FastAPI** instruieren, ihn als weiteren Body-Schlüssel zu er //// tab | Python 3.9+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} ``` //// @@ -155,7 +155,7 @@ Aber Sie können **FastAPI** instruieren, ihn als weiteren Body-Schlüssel zu er //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} ``` //// @@ -169,7 +169,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} ``` //// @@ -183,7 +183,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +{!> ../../docs_src/body_multiple_params/tutorial003.py!} ``` //// @@ -229,7 +229,7 @@ Zum Beispiel: //// tab | Python 3.10+ ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} ``` //// @@ -237,7 +237,7 @@ Zum Beispiel: //// tab | Python 3.9+ ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} ``` //// @@ -245,7 +245,7 @@ Zum Beispiel: //// tab | Python 3.8+ ```Python hl_lines="28" -{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} ``` //// @@ -259,7 +259,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="25" -{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` //// @@ -273,7 +273,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +{!> ../../docs_src/body_multiple_params/tutorial004.py!} ``` //// @@ -301,7 +301,7 @@ so wie in: //// tab | Python 3.10+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} ``` //// @@ -309,7 +309,7 @@ so wie in: //// tab | Python 3.9+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} ``` //// @@ -317,7 +317,7 @@ so wie in: //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} ``` //// @@ -331,7 +331,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="15" -{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} ``` //// @@ -345,7 +345,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +{!> ../../docs_src/body_multiple_params/tutorial005.py!} ``` //// diff --git a/docs/de/docs/tutorial/body-nested-models.md b/docs/de/docs/tutorial/body-nested-models.md index 8aef965f4..13153aa68 100644 --- a/docs/de/docs/tutorial/body-nested-models.md +++ b/docs/de/docs/tutorial/body-nested-models.md @@ -9,7 +9,7 @@ Sie können ein Attribut als Kindtyp definieren, zum Beispiel eine Python-`list` //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ Sie können ein Attribut als Kindtyp definieren, zum Beispiel eine Python-`list` //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial001.py!} +{!> ../../docs_src/body_nested_models/tutorial001.py!} ``` //// @@ -35,7 +35,7 @@ In Python 3.9 oder darüber können Sie einfach `list` verwenden, um diese Typan In Python-Versionen vor 3.9 (3.6 und darüber), müssen Sie zuerst `List` von Pythons Standardmodul `typing` importieren. ```Python hl_lines="1" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` ### Eine `list`e mit einem Typ-Parameter deklarieren @@ -68,7 +68,7 @@ In unserem Beispiel können wir also bewirken, dass `tags` spezifisch eine „Li //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} ``` //// @@ -76,7 +76,7 @@ In unserem Beispiel können wir also bewirken, dass `tags` spezifisch eine „Li //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} ``` //// @@ -84,7 +84,7 @@ In unserem Beispiel können wir also bewirken, dass `tags` spezifisch eine „Li //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` //// @@ -100,7 +100,7 @@ Deklarieren wir also `tags` als Set von Strings. //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} ``` //// @@ -108,7 +108,7 @@ Deklarieren wir also `tags` als Set von Strings. //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} ``` //// @@ -116,7 +116,7 @@ Deklarieren wir also `tags` als Set von Strings. //// tab | Python 3.8+ ```Python hl_lines="1 14" -{!> ../../../docs_src/body_nested_models/tutorial003.py!} +{!> ../../docs_src/body_nested_models/tutorial003.py!} ``` //// @@ -144,7 +144,7 @@ Wir können zum Beispiel ein `Image`-Modell definieren. //// tab | Python 3.10+ ```Python hl_lines="7-9" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -152,7 +152,7 @@ Wir können zum Beispiel ein `Image`-Modell definieren. //// tab | Python 3.9+ ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -160,7 +160,7 @@ Wir können zum Beispiel ein `Image`-Modell definieren. //// tab | Python 3.8+ ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -172,7 +172,7 @@ Und dann können wir es als Typ eines Attributes verwenden. //// tab | Python 3.10+ ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -180,7 +180,7 @@ Und dann können wir es als Typ eines Attributes verwenden. //// tab | Python 3.9+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -188,7 +188,7 @@ Und dann können wir es als Typ eines Attributes verwenden. //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -227,7 +227,7 @@ Da wir zum Beispiel im `Image`-Modell ein Feld `url` haben, können wir deklarie //// tab | Python 3.10+ ```Python hl_lines="2 8" -{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} ``` //// @@ -235,7 +235,7 @@ Da wir zum Beispiel im `Image`-Modell ein Feld `url` haben, können wir deklarie //// tab | Python 3.9+ ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} ``` //// @@ -243,7 +243,7 @@ Da wir zum Beispiel im `Image`-Modell ein Feld `url` haben, können wir deklarie //// tab | Python 3.8+ ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005.py!} +{!> ../../docs_src/body_nested_models/tutorial005.py!} ``` //// @@ -257,7 +257,7 @@ Sie können Pydantic-Modelle auch als Typen innerhalb von `list`, `set`, usw. ve //// tab | Python 3.10+ ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} ``` //// @@ -265,7 +265,7 @@ Sie können Pydantic-Modelle auch als Typen innerhalb von `list`, `set`, usw. ve //// tab | Python 3.9+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} ``` //// @@ -273,7 +273,7 @@ Sie können Pydantic-Modelle auch als Typen innerhalb von `list`, `set`, usw. ve //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006.py!} +{!> ../../docs_src/body_nested_models/tutorial006.py!} ``` //// @@ -317,7 +317,7 @@ Sie können beliebig tief verschachtelte Modelle definieren: //// tab | Python 3.10+ ```Python hl_lines="7 12 18 21 25" -{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} ``` //// @@ -325,7 +325,7 @@ Sie können beliebig tief verschachtelte Modelle definieren: //// tab | Python 3.9+ ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} ``` //// @@ -333,7 +333,7 @@ Sie können beliebig tief verschachtelte Modelle definieren: //// tab | Python 3.8+ ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007.py!} +{!> ../../docs_src/body_nested_models/tutorial007.py!} ``` //// @@ -363,7 +363,7 @@ so wie in: //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} ``` //// @@ -371,7 +371,7 @@ so wie in: //// tab | Python 3.8+ ```Python hl_lines="15" -{!> ../../../docs_src/body_nested_models/tutorial008.py!} +{!> ../../docs_src/body_nested_models/tutorial008.py!} ``` //// @@ -407,7 +407,7 @@ Im folgenden Beispiel akzeptieren Sie irgendein `dict`, solange es `int`-Schlüs //// tab | Python 3.9+ ```Python hl_lines="7" -{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} ``` //// @@ -415,7 +415,7 @@ Im folgenden Beispiel akzeptieren Sie irgendein `dict`, solange es `int`-Schlüs //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/body_nested_models/tutorial009.py!} +{!> ../../docs_src/body_nested_models/tutorial009.py!} ``` //// diff --git a/docs/de/docs/tutorial/body-updates.md b/docs/de/docs/tutorial/body-updates.md index b83554914..ed5c1890f 100644 --- a/docs/de/docs/tutorial/body-updates.md +++ b/docs/de/docs/tutorial/body-updates.md @@ -9,7 +9,7 @@ Sie können den `jsonable_encoder` verwenden, um die empfangenen Daten in etwas //// tab | Python 3.10+ ```Python hl_lines="28-33" -{!> ../../../docs_src/body_updates/tutorial001_py310.py!} +{!> ../../docs_src/body_updates/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ Sie können den `jsonable_encoder` verwenden, um die empfangenen Daten in etwas //// tab | Python 3.9+ ```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001_py39.py!} +{!> ../../docs_src/body_updates/tutorial001_py39.py!} ``` //// @@ -25,7 +25,7 @@ Sie können den `jsonable_encoder` verwenden, um die empfangenen Daten in etwas //// tab | Python 3.8+ ```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001.py!} +{!> ../../docs_src/body_updates/tutorial001.py!} ``` //// @@ -87,7 +87,7 @@ Sie können das verwenden, um ein `dict` zu erstellen, das nur die (im Request) //// tab | Python 3.10+ ```Python hl_lines="32" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -95,7 +95,7 @@ Sie können das verwenden, um ein `dict` zu erstellen, das nur die (im Request) //// tab | Python 3.9+ ```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -103,7 +103,7 @@ Sie können das verwenden, um ein `dict` zu erstellen, das nur die (im Request) //// tab | Python 3.8+ ```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// @@ -125,7 +125,7 @@ Wie in `stored_item_model.model_copy(update=update_data)`: //// tab | Python 3.10+ ```Python hl_lines="33" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -133,7 +133,7 @@ Wie in `stored_item_model.model_copy(update=update_data)`: //// tab | Python 3.9+ ```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -141,7 +141,7 @@ Wie in `stored_item_model.model_copy(update=update_data)`: //// tab | Python 3.8+ ```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// @@ -164,7 +164,7 @@ Zusammengefasst, um Teil-Ersetzungen vorzunehmen: //// tab | Python 3.10+ ```Python hl_lines="28-35" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -172,7 +172,7 @@ Zusammengefasst, um Teil-Ersetzungen vorzunehmen: //// tab | Python 3.9+ ```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -180,7 +180,7 @@ Zusammengefasst, um Teil-Ersetzungen vorzunehmen: //// tab | Python 3.8+ ```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// diff --git a/docs/de/docs/tutorial/body.md b/docs/de/docs/tutorial/body.md index 3fdd4ade3..3a64e747e 100644 --- a/docs/de/docs/tutorial/body.md +++ b/docs/de/docs/tutorial/body.md @@ -25,7 +25,7 @@ Zuerst müssen Sie `BaseModel` von `pydantic` importieren: //// tab | Python 3.10+ ```Python hl_lines="2" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -33,7 +33,7 @@ Zuerst müssen Sie `BaseModel` von `pydantic` importieren: //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -47,7 +47,7 @@ Verwenden Sie Standard-Python-Typen für die Klassenattribute: //// tab | Python 3.10+ ```Python hl_lines="5-9" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -55,7 +55,7 @@ Verwenden Sie Standard-Python-Typen für die Klassenattribute: //// tab | Python 3.8+ ```Python hl_lines="7-11" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -89,7 +89,7 @@ Um es zu Ihrer *Pfadoperation* hinzuzufügen, deklarieren Sie es auf die gleiche //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -97,7 +97,7 @@ Um es zu Ihrer *Pfadoperation* hinzuzufügen, deklarieren Sie es auf die gleiche //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -170,7 +170,7 @@ Innerhalb der Funktion können Sie alle Attribute des Modells direkt verwenden: //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/body/tutorial002_py310.py!} +{!> ../../docs_src/body/tutorial002_py310.py!} ``` //// @@ -178,7 +178,7 @@ Innerhalb der Funktion können Sie alle Attribute des Modells direkt verwenden: //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/body/tutorial002.py!} +{!> ../../docs_src/body/tutorial002.py!} ``` //// @@ -192,7 +192,7 @@ Sie können Pfad- und Requestbody-Parameter gleichzeitig deklarieren. //// tab | Python 3.10+ ```Python hl_lines="15-16" -{!> ../../../docs_src/body/tutorial003_py310.py!} +{!> ../../docs_src/body/tutorial003_py310.py!} ``` //// @@ -200,7 +200,7 @@ Sie können Pfad- und Requestbody-Parameter gleichzeitig deklarieren. //// tab | Python 3.8+ ```Python hl_lines="17-18" -{!> ../../../docs_src/body/tutorial003.py!} +{!> ../../docs_src/body/tutorial003.py!} ``` //// @@ -214,7 +214,7 @@ Sie können auch zur gleichen Zeit **Body-**, **Pfad-** und **Query-Parameter** //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial004_py310.py!} +{!> ../../docs_src/body/tutorial004_py310.py!} ``` //// @@ -222,7 +222,7 @@ Sie können auch zur gleichen Zeit **Body-**, **Pfad-** und **Query-Parameter** //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial004.py!} +{!> ../../docs_src/body/tutorial004.py!} ``` //// diff --git a/docs/de/docs/tutorial/cookie-params.md b/docs/de/docs/tutorial/cookie-params.md index 0060db8e8..4714a59ae 100644 --- a/docs/de/docs/tutorial/cookie-params.md +++ b/docs/de/docs/tutorial/cookie-params.md @@ -9,7 +9,7 @@ Importieren Sie zuerst `Cookie`: //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ Importieren Sie zuerst `Cookie`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Importieren Sie zuerst `Cookie`: //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -67,7 +67,7 @@ Der erste Wert ist der Typ. Sie können `Cookie` die gehabten Extra Validierungs //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -75,7 +75,7 @@ Der erste Wert ist der Typ. Sie können `Cookie` die gehabten Extra Validierungs //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ Der erste Wert ist der Typ. Sie können `Cookie` die gehabten Extra Validierungs //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -97,7 +97,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -111,7 +111,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// diff --git a/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md index 0a9f05bf9..a660ab337 100644 --- a/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md @@ -9,7 +9,7 @@ Im vorherigen Beispiel haben wir ein `dict` von unserer Abhängigkeit („Depend //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ Im vorherigen Beispiel haben wir ein `dict` von unserer Abhängigkeit („Depend //// tab | Python 3.9+ ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Im vorherigen Beispiel haben wir ein `dict` von unserer Abhängigkeit („Depend //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -122,7 +122,7 @@ Dann können wir das „Dependable“ `common_parameters` der Abhängigkeit von //// tab | Python 3.10+ ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -130,7 +130,7 @@ Dann können wir das „Dependable“ `common_parameters` der Abhängigkeit von //// tab | Python 3.9+ ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -138,7 +138,7 @@ Dann können wir das „Dependable“ `common_parameters` der Abhängigkeit von //// tab | Python 3.8+ ```Python hl_lines="12-16" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -152,7 +152,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9-13" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -166,7 +166,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -176,7 +176,7 @@ Achten Sie auf die Methode `__init__`, die zum Erstellen der Instanz der Klasse //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -184,7 +184,7 @@ Achten Sie auf die Methode `__init__`, die zum Erstellen der Instanz der Klasse //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -192,7 +192,7 @@ Achten Sie auf die Methode `__init__`, die zum Erstellen der Instanz der Klasse //// tab | Python 3.8+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -206,7 +206,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -220,7 +220,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -230,7 +230,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -238,7 +238,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -246,7 +246,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -260,7 +260,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="6" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -274,7 +274,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -296,7 +296,7 @@ Jetzt können Sie Ihre Abhängigkeit mithilfe dieser Klasse deklarieren. //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -304,7 +304,7 @@ Jetzt können Sie Ihre Abhängigkeit mithilfe dieser Klasse deklarieren. //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -312,7 +312,7 @@ Jetzt können Sie Ihre Abhängigkeit mithilfe dieser Klasse deklarieren. //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -326,7 +326,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -340,7 +340,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -440,7 +440,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_an_py310.py!} ``` //// @@ -448,7 +448,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial003_an_py39.py!} ``` //// @@ -456,7 +456,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial003_an.py!} +{!> ../../docs_src/dependencies/tutorial003_an.py!} ``` //// @@ -470,7 +470,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_py310.py!} ``` //// @@ -484,7 +484,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003.py!} +{!> ../../docs_src/dependencies/tutorial003.py!} ``` //// @@ -578,7 +578,7 @@ Dasselbe Beispiel würde dann so aussehen: //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_an_py310.py!} ``` //// @@ -586,7 +586,7 @@ Dasselbe Beispiel würde dann so aussehen: //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial004_an_py39.py!} ``` //// @@ -594,7 +594,7 @@ Dasselbe Beispiel würde dann so aussehen: //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial004_an.py!} +{!> ../../docs_src/dependencies/tutorial004_an.py!} ``` //// @@ -608,7 +608,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_py310.py!} ``` //// @@ -622,7 +622,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004.py!} +{!> ../../docs_src/dependencies/tutorial004.py!} ``` //// diff --git a/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 47d6453c2..3bb261e44 100644 --- a/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -17,7 +17,7 @@ Es sollte eine `list`e von `Depends()` sein: //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Es sollte eine `list`e von `Depends()` sein: //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -39,7 +39,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -75,7 +75,7 @@ Sie können Anforderungen für einen Request (wie Header) oder andere Unterabhä //// tab | Python 3.9+ ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ Sie können Anforderungen für einen Request (wie Header) oder andere Unterabhä //// tab | Python 3.8+ ```Python hl_lines="7 12" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -97,7 +97,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="6 11" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -109,7 +109,7 @@ Die Abhängigkeiten können Exceptions `raise`n, genau wie normale Abhängigkeit //// tab | Python 3.9+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -117,7 +117,7 @@ Die Abhängigkeiten können Exceptions `raise`n, genau wie normale Abhängigkeit //// tab | Python 3.8+ ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -131,7 +131,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -145,7 +145,7 @@ Sie können also eine normale Abhängigkeit (die einen Wert zurückgibt), die Si //// tab | Python 3.9+ ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -153,7 +153,7 @@ Sie können also eine normale Abhängigkeit (die einen Wert zurückgibt), die Si //// tab | Python 3.8+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -167,7 +167,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// diff --git a/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md index 9c2e6dd86..48b057e28 100644 --- a/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md @@ -30,19 +30,19 @@ Sie könnten damit beispielsweise eine Datenbanksession erstellen und diese nach Nur der Code vor und einschließlich der `yield`-Anweisung wird ausgeführt, bevor eine Response erzeugt wird: ```Python hl_lines="2-4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` Der ge`yield`ete Wert ist das, was in *Pfadoperationen* und andere Abhängigkeiten eingefügt wird: ```Python hl_lines="4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` Der auf die `yield`-Anweisung folgende Code wird ausgeführt, nachdem die Response gesendet wurde: ```Python hl_lines="5-6" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` /// tip | "Tipp" @@ -64,7 +64,7 @@ Sie können also mit `except SomeException` diese bestimmte Exception innerhalb Auf die gleiche Weise können Sie `finally` verwenden, um sicherzustellen, dass die Exit-Schritte ausgeführt werden, unabhängig davon, ob eine Exception geworfen wurde oder nicht. ```Python hl_lines="3 5" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` ## Unterabhängigkeiten mit `yield`. @@ -78,7 +78,7 @@ Beispielsweise kann `dependency_c` von `dependency_b` und `dependency_b` von `de //// tab | Python 3.9+ ```Python hl_lines="6 14 22" -{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} ``` //// @@ -86,7 +86,7 @@ Beispielsweise kann `dependency_c` von `dependency_b` und `dependency_b` von `de //// tab | Python 3.8+ ```Python hl_lines="5 13 21" -{!> ../../../docs_src/dependencies/tutorial008_an.py!} +{!> ../../docs_src/dependencies/tutorial008_an.py!} ``` //// @@ -100,7 +100,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="4 12 20" -{!> ../../../docs_src/dependencies/tutorial008.py!} +{!> ../../docs_src/dependencies/tutorial008.py!} ``` //// @@ -114,7 +114,7 @@ Und wiederum benötigt `dependency_b` den Wert von `dependency_a` (hier `dep_a` //// tab | Python 3.9+ ```Python hl_lines="18-19 26-27" -{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} ``` //// @@ -122,7 +122,7 @@ Und wiederum benötigt `dependency_b` den Wert von `dependency_a` (hier `dep_a` //// tab | Python 3.8+ ```Python hl_lines="17-18 25-26" -{!> ../../../docs_src/dependencies/tutorial008_an.py!} +{!> ../../docs_src/dependencies/tutorial008_an.py!} ``` //// @@ -136,7 +136,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="16-17 24-25" -{!> ../../../docs_src/dependencies/tutorial008.py!} +{!> ../../docs_src/dependencies/tutorial008.py!} ``` //// @@ -174,7 +174,7 @@ Aber es ist für Sie da, wenn Sie es brauchen. 🤓 //// tab | Python 3.9+ ```Python hl_lines="18-22 31" -{!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008b_an_py39.py!} ``` //// @@ -182,7 +182,7 @@ Aber es ist für Sie da, wenn Sie es brauchen. 🤓 //// tab | Python 3.8+ ```Python hl_lines="17-21 30" -{!> ../../../docs_src/dependencies/tutorial008b_an.py!} +{!> ../../docs_src/dependencies/tutorial008b_an.py!} ``` //// @@ -196,7 +196,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="16-20 29" -{!> ../../../docs_src/dependencies/tutorial008b.py!} +{!> ../../docs_src/dependencies/tutorial008b.py!} ``` //// @@ -321,7 +321,7 @@ In Python können Sie Kontextmanager erstellen, indem Sie ../../../docs_src/dependencies/tutorial012_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} ``` //// @@ -17,7 +17,7 @@ In diesem Fall werden sie auf alle *Pfadoperationen* in der Anwendung angewendet //// tab | Python 3.8+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial012_an.py!} +{!> ../../docs_src/dependencies/tutorial012_an.py!} ``` //// @@ -31,7 +31,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="15" -{!> ../../../docs_src/dependencies/tutorial012.py!} +{!> ../../docs_src/dependencies/tutorial012.py!} ``` //// diff --git a/docs/de/docs/tutorial/dependencies/index.md b/docs/de/docs/tutorial/dependencies/index.md index f7d9ed510..494708d19 100644 --- a/docs/de/docs/tutorial/dependencies/index.md +++ b/docs/de/docs/tutorial/dependencies/index.md @@ -33,7 +33,7 @@ Es handelt sich einfach um eine Funktion, die die gleichen Parameter entgegennim //// tab | Python 3.10+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -41,7 +41,7 @@ Es handelt sich einfach um eine Funktion, die die gleichen Parameter entgegennim //// tab | Python 3.9+ ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -49,7 +49,7 @@ Es handelt sich einfach um eine Funktion, die die gleichen Parameter entgegennim //// tab | Python 3.8+ ```Python hl_lines="9-12" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -63,7 +63,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -77,7 +77,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -115,7 +115,7 @@ Bitte [aktualisieren Sie FastAPI](../../deployment/versions.md#upgrade-der-fasta //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -123,7 +123,7 @@ Bitte [aktualisieren Sie FastAPI](../../deployment/versions.md#upgrade-der-fasta //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -131,7 +131,7 @@ Bitte [aktualisieren Sie FastAPI](../../deployment/versions.md#upgrade-der-fasta //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -145,7 +145,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -159,7 +159,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -171,7 +171,7 @@ So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ih //// tab | Python 3.10+ ```Python hl_lines="13 18" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -179,7 +179,7 @@ So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ih //// tab | Python 3.9+ ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -187,7 +187,7 @@ So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ih //// tab | Python 3.8+ ```Python hl_lines="16 21" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -201,7 +201,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -215,7 +215,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -278,7 +278,7 @@ Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in eine //// tab | Python 3.10+ ```Python hl_lines="12 16 21" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} ``` //// @@ -286,7 +286,7 @@ Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in eine //// tab | Python 3.9+ ```Python hl_lines="14 18 23" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} ``` //// @@ -294,7 +294,7 @@ Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in eine //// tab | Python 3.8+ ```Python hl_lines="15 19 24" -{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an.py!} ``` //// diff --git a/docs/de/docs/tutorial/dependencies/sub-dependencies.md b/docs/de/docs/tutorial/dependencies/sub-dependencies.md index 12664a8cd..a20aed63b 100644 --- a/docs/de/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/de/docs/tutorial/dependencies/sub-dependencies.md @@ -13,7 +13,7 @@ Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen: //// tab | Python 3.10+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -21,7 +21,7 @@ Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen: //// tab | Python 3.9+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -29,7 +29,7 @@ Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen: //// tab | Python 3.8+ ```Python hl_lines="9-10" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -43,7 +43,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -57,7 +57,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -73,7 +73,7 @@ Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erst //// tab | Python 3.10+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -81,7 +81,7 @@ Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erst //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -89,7 +89,7 @@ Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erst //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -103,7 +103,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -117,7 +117,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -136,7 +136,7 @@ Diese Abhängigkeit verwenden wir nun wie folgt: //// tab | Python 3.10+ ```Python hl_lines="23" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -144,7 +144,7 @@ Diese Abhängigkeit verwenden wir nun wie folgt: //// tab | Python 3.9+ ```Python hl_lines="23" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -152,7 +152,7 @@ Diese Abhängigkeit verwenden wir nun wie folgt: //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -166,7 +166,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -180,7 +180,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="22" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// diff --git a/docs/de/docs/tutorial/encoder.md b/docs/de/docs/tutorial/encoder.md index 38a881b4f..0ab72b8dd 100644 --- a/docs/de/docs/tutorial/encoder.md +++ b/docs/de/docs/tutorial/encoder.md @@ -23,7 +23,7 @@ Es nimmt ein Objekt entgegen, wie etwa ein Pydantic-Modell, und gibt eine JSON-k //// tab | Python 3.10+ ```Python hl_lines="4 21" -{!> ../../../docs_src/encoder/tutorial001_py310.py!} +{!> ../../docs_src/encoder/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ Es nimmt ein Objekt entgegen, wie etwa ein Pydantic-Modell, und gibt eine JSON-k //// tab | Python 3.8+ ```Python hl_lines="5 22" -{!> ../../../docs_src/encoder/tutorial001.py!} +{!> ../../docs_src/encoder/tutorial001.py!} ``` //// diff --git a/docs/de/docs/tutorial/extra-data-types.md b/docs/de/docs/tutorial/extra-data-types.md index 334a232a8..7581b4f87 100644 --- a/docs/de/docs/tutorial/extra-data-types.md +++ b/docs/de/docs/tutorial/extra-data-types.md @@ -58,7 +58,7 @@ Hier ist ein Beispiel für eine *Pfadoperation* mit Parametern, die einige der o //// tab | Python 3.10+ ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} ``` //// @@ -66,7 +66,7 @@ Hier ist ein Beispiel für eine *Pfadoperation* mit Parametern, die einige der o //// tab | Python 3.9+ ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` //// @@ -74,7 +74,7 @@ Hier ist ein Beispiel für eine *Pfadoperation* mit Parametern, die einige der o //// tab | Python 3.8+ ```Python hl_lines="1 3 13-17" -{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} ``` //// @@ -88,7 +88,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1 2 11-15" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -102,7 +102,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1 2 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// @@ -112,7 +112,7 @@ Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Daten //// tab | Python 3.10+ ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} ``` //// @@ -120,7 +120,7 @@ Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Daten //// tab | Python 3.9+ ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` //// @@ -128,7 +128,7 @@ Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Daten //// tab | Python 3.8+ ```Python hl_lines="19-20" -{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} ``` //// @@ -142,7 +142,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="17-18" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -156,7 +156,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// diff --git a/docs/de/docs/tutorial/extra-models.md b/docs/de/docs/tutorial/extra-models.md index cfd0230eb..14e842065 100644 --- a/docs/de/docs/tutorial/extra-models.md +++ b/docs/de/docs/tutorial/extra-models.md @@ -23,7 +23,7 @@ Hier der generelle Weg, wie die Modelle mit ihren Passwort-Feldern aussehen kön //// tab | Python 3.10+ ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +{!> ../../docs_src/extra_models/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ Hier der generelle Weg, wie die Modelle mit ihren Passwort-Feldern aussehen kön //// tab | Python 3.8+ ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../../docs_src/extra_models/tutorial001.py!} +{!> ../../docs_src/extra_models/tutorial001.py!} ``` //// @@ -179,7 +179,7 @@ Auf diese Weise beschreiben wir nur noch die Unterschiede zwischen den Modellen //// tab | Python 3.10+ ```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +{!> ../../docs_src/extra_models/tutorial002_py310.py!} ``` //// @@ -187,7 +187,7 @@ Auf diese Weise beschreiben wir nur noch die Unterschiede zwischen den Modellen //// tab | Python 3.8+ ```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../../docs_src/extra_models/tutorial002.py!} +{!> ../../docs_src/extra_models/tutorial002.py!} ``` //// @@ -209,7 +209,7 @@ Listen Sie, wenn Sie eine ../../../docs_src/extra_models/tutorial003_py310.py!} +{!> ../../docs_src/extra_models/tutorial003_py310.py!} ``` //// @@ -217,7 +217,7 @@ Listen Sie, wenn Sie eine ../../../docs_src/extra_models/tutorial003.py!} +{!> ../../docs_src/extra_models/tutorial003.py!} ``` //// @@ -245,7 +245,7 @@ Verwenden Sie dafür Pythons Standard `typing.List` (oder nur `list` in Python 3 //// tab | Python 3.9+ ```Python hl_lines="18" -{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +{!> ../../docs_src/extra_models/tutorial004_py39.py!} ``` //// @@ -253,7 +253,7 @@ Verwenden Sie dafür Pythons Standard `typing.List` (oder nur `list` in Python 3 //// tab | Python 3.8+ ```Python hl_lines="1 20" -{!> ../../../docs_src/extra_models/tutorial004.py!} +{!> ../../docs_src/extra_models/tutorial004.py!} ``` //// @@ -269,7 +269,7 @@ In diesem Fall können Sie `typing.Dict` verwenden (oder nur `dict` in Python 3. //// tab | Python 3.9+ ```Python hl_lines="6" -{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +{!> ../../docs_src/extra_models/tutorial005_py39.py!} ``` //// @@ -277,7 +277,7 @@ In diesem Fall können Sie `typing.Dict` verwenden (oder nur `dict` in Python 3. //// tab | Python 3.8+ ```Python hl_lines="1 8" -{!> ../../../docs_src/extra_models/tutorial005.py!} +{!> ../../docs_src/extra_models/tutorial005.py!} ``` //// diff --git a/docs/de/docs/tutorial/first-steps.md b/docs/de/docs/tutorial/first-steps.md index b9e38707c..fe3886b70 100644 --- a/docs/de/docs/tutorial/first-steps.md +++ b/docs/de/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ Die einfachste FastAPI-Datei könnte wie folgt aussehen: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Kopieren Sie dies in eine Datei `main.py`. @@ -134,7 +134,7 @@ Ebenfalls können Sie es verwenden, um automatisch Code für Clients zu generier ### Schritt 1: Importieren von `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` ist eine Python-Klasse, die die gesamte Funktionalität für Ihre API bereitstellt. @@ -150,7 +150,7 @@ Sie können alle ../../../docs_src/header_params/tutorial001_an_py310.py!} +{!> ../../docs_src/header_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ Importieren Sie zuerst `Header`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +{!> ../../docs_src/header_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Importieren Sie zuerst `Header`: //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001_an.py!} +{!> ../../docs_src/header_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1" -{!> ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -67,7 +67,7 @@ Der erste Wert ist der Typ. Sie können `Header` die gehabten Extra Validierungs //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +{!> ../../docs_src/header_params/tutorial001_an_py310.py!} ``` //// @@ -75,7 +75,7 @@ Der erste Wert ist der Typ. Sie können `Header` die gehabten Extra Validierungs //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +{!> ../../docs_src/header_params/tutorial001_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ Der erste Wert ist der Typ. Sie können `Header` die gehabten Extra Validierungs //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial001_an.py!} +{!> ../../docs_src/header_params/tutorial001_an.py!} ``` //// @@ -97,7 +97,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -111,7 +111,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -149,7 +149,7 @@ Wenn Sie aus irgendeinem Grund das automatische Konvertieren von Unterstrichen z //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial002_an_py310.py!} +{!> ../../docs_src/header_params/tutorial002_an_py310.py!} ``` //// @@ -157,7 +157,7 @@ Wenn Sie aus irgendeinem Grund das automatische Konvertieren von Unterstrichen z //// tab | Python 3.9+ ```Python hl_lines="11" -{!> ../../../docs_src/header_params/tutorial002_an_py39.py!} +{!> ../../docs_src/header_params/tutorial002_an_py39.py!} ``` //// @@ -165,7 +165,7 @@ Wenn Sie aus irgendeinem Grund das automatische Konvertieren von Unterstrichen z //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/header_params/tutorial002_an.py!} +{!> ../../docs_src/header_params/tutorial002_an.py!} ``` //// @@ -179,7 +179,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8" -{!> ../../../docs_src/header_params/tutorial002_py310.py!} +{!> ../../docs_src/header_params/tutorial002_py310.py!} ``` //// @@ -193,7 +193,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial002.py!} +{!> ../../docs_src/header_params/tutorial002.py!} ``` //// @@ -217,7 +217,7 @@ Um zum Beispiel einen Header `X-Token` zu deklarieren, der mehrmals vorkommen ka //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_an_py310.py!} +{!> ../../docs_src/header_params/tutorial003_an_py310.py!} ``` //// @@ -225,7 +225,7 @@ Um zum Beispiel einen Header `X-Token` zu deklarieren, der mehrmals vorkommen ka //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_an_py39.py!} +{!> ../../docs_src/header_params/tutorial003_an_py39.py!} ``` //// @@ -233,7 +233,7 @@ Um zum Beispiel einen Header `X-Token` zu deklarieren, der mehrmals vorkommen ka //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial003_an.py!} +{!> ../../docs_src/header_params/tutorial003_an.py!} ``` //// @@ -247,7 +247,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial003_py310.py!} +{!> ../../docs_src/header_params/tutorial003_py310.py!} ``` //// @@ -261,7 +261,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_py39.py!} +{!> ../../docs_src/header_params/tutorial003_py39.py!} ``` //// @@ -275,7 +275,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003.py!} +{!> ../../docs_src/header_params/tutorial003.py!} ``` //// diff --git a/docs/de/docs/tutorial/metadata.md b/docs/de/docs/tutorial/metadata.md index 3ab56ff3e..98724e1e8 100644 --- a/docs/de/docs/tutorial/metadata.md +++ b/docs/de/docs/tutorial/metadata.md @@ -19,7 +19,7 @@ Sie können die folgenden Felder festlegen, welche in der OpenAPI-Spezifikation Sie können diese wie folgt setzen: ```Python hl_lines="3-16 19-32" -{!../../../docs_src/metadata/tutorial001.py!} +{!../../docs_src/metadata/tutorial001.py!} ``` /// tip | "Tipp" @@ -39,7 +39,7 @@ Seit OpenAPI 3.1.0 und FastAPI 0.99.0 können Sie die `license_info` auch mit ei Zum Beispiel: ```Python hl_lines="31" -{!../../../docs_src/metadata/tutorial001_1.py!} +{!../../docs_src/metadata/tutorial001_1.py!} ``` ## Metadaten für Tags @@ -63,7 +63,7 @@ Versuchen wir das an einem Beispiel mit Tags für `users` und `items`. Erstellen Sie Metadaten für Ihre Tags und übergeben Sie sie an den Parameter `openapi_tags`: ```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` Beachten Sie, dass Sie Markdown in den Beschreibungen verwenden können. Beispielsweise wird „login“ in Fettschrift (**login**) und „fancy“ in Kursivschrift (_fancy_) angezeigt. @@ -79,7 +79,7 @@ Sie müssen nicht für alle von Ihnen verwendeten Tags Metadaten hinzufügen. Verwenden Sie den Parameter `tags` mit Ihren *Pfadoperationen* (und `APIRouter`n), um diese verschiedenen Tags zuzuweisen: ```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` /// info @@ -109,7 +109,7 @@ Sie können das aber mit dem Parameter `openapi_url` konfigurieren. Um beispielsweise festzulegen, dass es unter `/api/v1/openapi.json` bereitgestellt wird: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} +{!../../docs_src/metadata/tutorial002.py!} ``` Wenn Sie das OpenAPI-Schema vollständig deaktivieren möchten, können Sie `openapi_url=None` festlegen, wodurch auch die Dokumentationsbenutzeroberflächen deaktiviert werden, die es verwenden. @@ -128,5 +128,5 @@ Sie können die beiden enthaltenen Dokumentationsbenutzeroberflächen konfigurie Um beispielsweise Swagger UI so einzustellen, dass sie unter `/documentation` bereitgestellt wird, und ReDoc zu deaktivieren: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} +{!../../docs_src/metadata/tutorial003.py!} ``` diff --git a/docs/de/docs/tutorial/middleware.md b/docs/de/docs/tutorial/middleware.md index 62a0d1613..410dc0247 100644 --- a/docs/de/docs/tutorial/middleware.md +++ b/docs/de/docs/tutorial/middleware.md @@ -32,7 +32,7 @@ Die Middleware-Funktion erhält: * Sie können die `response` dann weiter modifizieren, bevor Sie sie zurückgeben. ```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` /// tip | "Tipp" @@ -60,7 +60,7 @@ Und auch nachdem die `response` generiert wurde, bevor sie zurückgegeben wird. Sie könnten beispielsweise einen benutzerdefinierten Header `X-Process-Time` hinzufügen, der die Zeit in Sekunden enthält, die benötigt wurde, um den Request zu verarbeiten und eine Response zu generieren: ```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` ## Andere Middlewares diff --git a/docs/de/docs/tutorial/path-operation-configuration.md b/docs/de/docs/tutorial/path-operation-configuration.md index 03980b7dd..411916e9c 100644 --- a/docs/de/docs/tutorial/path-operation-configuration.md +++ b/docs/de/docs/tutorial/path-operation-configuration.md @@ -19,7 +19,7 @@ Aber falls Sie sich nicht mehr erinnern, wofür jede Nummer steht, können Sie d //// tab | Python 3.10+ ```Python hl_lines="1 15" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} ``` //// @@ -27,7 +27,7 @@ Aber falls Sie sich nicht mehr erinnern, wofür jede Nummer steht, können Sie d //// tab | Python 3.9+ ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} ``` //// @@ -35,7 +35,7 @@ Aber falls Sie sich nicht mehr erinnern, wofür jede Nummer steht, können Sie d //// tab | Python 3.8+ ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001.py!} ``` //// @@ -57,7 +57,7 @@ Sie können Ihrer *Pfadoperation* Tags hinzufügen, mittels des Parameters `tags //// tab | Python 3.10+ ```Python hl_lines="15 20 25" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} ``` //// @@ -65,7 +65,7 @@ Sie können Ihrer *Pfadoperation* Tags hinzufügen, mittels des Parameters `tags //// tab | Python 3.9+ ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} ``` //// @@ -73,7 +73,7 @@ Sie können Ihrer *Pfadoperation* Tags hinzufügen, mittels des Parameters `tags //// tab | Python 3.8+ ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002.py!} ``` //// @@ -91,7 +91,7 @@ In diesem Fall macht es Sinn, die Tags in einem `Enum` zu speichern. **FastAPI** unterstützt diese genauso wie einfache Strings: ```Python hl_lines="1 8-10 13 18" -{!../../../docs_src/path_operation_configuration/tutorial002b.py!} +{!../../docs_src/path_operation_configuration/tutorial002b.py!} ``` ## Zusammenfassung und Beschreibung @@ -101,7 +101,7 @@ Sie können eine Zusammenfassung (`summary`) und eine Beschreibung (`description //// tab | Python 3.10+ ```Python hl_lines="18-19" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} ``` //// @@ -109,7 +109,7 @@ Sie können eine Zusammenfassung (`summary`) und eine Beschreibung (`description //// tab | Python 3.9+ ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} ``` //// @@ -117,7 +117,7 @@ Sie können eine Zusammenfassung (`summary`) und eine Beschreibung (`description //// tab | Python 3.8+ ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003.py!} ``` //// @@ -131,7 +131,7 @@ Sie können im Docstring ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} ``` //// @@ -139,7 +139,7 @@ Sie können im Docstring ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} ``` //// @@ -147,7 +147,7 @@ Sie können im Docstring ../../../docs_src/path_operation_configuration/tutorial004.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004.py!} ``` //// @@ -163,7 +163,7 @@ Die Response können Sie mit dem Parameter `response_description` beschreiben: //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} ``` //// @@ -171,7 +171,7 @@ Die Response können Sie mit dem Parameter `response_description` beschreiben: //// tab | Python 3.9+ ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} ``` //// @@ -179,7 +179,7 @@ Die Response können Sie mit dem Parameter `response_description` beschreiben: //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005.py!} ``` //// @@ -205,7 +205,7 @@ Daher, wenn Sie keine vergeben, wird **FastAPI** automatisch eine für „Erfolg Wenn Sie eine *Pfadoperation* als deprecated kennzeichnen möchten, ohne sie zu entfernen, fügen Sie den Parameter `deprecated` hinzu: ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` Sie wird in der interaktiven Dokumentation gut sichtbar als deprecated markiert werden: diff --git a/docs/de/docs/tutorial/path-params-numeric-validations.md b/docs/de/docs/tutorial/path-params-numeric-validations.md index 3908a0b2d..fc2d5dff1 100644 --- a/docs/de/docs/tutorial/path-params-numeric-validations.md +++ b/docs/de/docs/tutorial/path-params-numeric-validations.md @@ -9,7 +9,7 @@ Importieren Sie zuerst `Path` von `fastapi`, und importieren Sie `Annotated`. //// tab | Python 3.10+ ```Python hl_lines="1 3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ Importieren Sie zuerst `Path` von `fastapi`, und importieren Sie `Annotated`. //// tab | Python 3.9+ ```Python hl_lines="1 3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Importieren Sie zuerst `Path` von `fastapi`, und importieren Sie `Annotated`. //// tab | Python 3.8+ ```Python hl_lines="3-4" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -77,7 +77,7 @@ Um zum Beispiel einen `title`-Metadaten-Wert für den Pfad-Parameter `item_id` z //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} ``` //// @@ -85,7 +85,7 @@ Um zum Beispiel einen `title`-Metadaten-Wert für den Pfad-Parameter `item_id` z //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` //// @@ -93,7 +93,7 @@ Um zum Beispiel einen `title`-Metadaten-Wert für den Pfad-Parameter `item_id` z //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} ``` //// @@ -107,7 +107,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -121,7 +121,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -167,7 +167,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` //// @@ -177,7 +177,7 @@ Aber bedenken Sie, dass Sie dieses Problem nicht haben, wenn Sie `Annotated` ver //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} ``` //// @@ -185,7 +185,7 @@ Aber bedenken Sie, dass Sie dieses Problem nicht haben, wenn Sie `Annotated` ver //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002_an.py!} ``` //// @@ -214,7 +214,7 @@ Wenn Sie eines der folgenden Dinge tun möchten: Python macht nichts mit diesem `*`, aber es wird wissen, dass alle folgenden Parameter als Keyword-Argumente (Schlüssel-Wert-Paare), auch bekannt als kwargs, verwendet werden. Selbst wenn diese keinen Defaultwert haben. ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ### Besser mit `Annotated` @@ -224,7 +224,7 @@ Bedenken Sie, dass Sie, wenn Sie `Annotated` verwenden, dieses Problem nicht hab //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} ``` //// @@ -232,7 +232,7 @@ Bedenken Sie, dass Sie, wenn Sie `Annotated` verwenden, dieses Problem nicht hab //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial003_an.py!} ``` //// @@ -245,7 +245,7 @@ Hier, mit `ge=1`, wird festgelegt, dass `item_id` eine Ganzzahl benötigt, die g //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} ``` //// @@ -253,7 +253,7 @@ Hier, mit `ge=1`, wird festgelegt, dass `item_id` eine Ganzzahl benötigt, die g //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!} ``` //// @@ -267,7 +267,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` //// @@ -282,7 +282,7 @@ Das Gleiche trifft zu auf: //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} ``` //// @@ -290,7 +290,7 @@ Das Gleiche trifft zu auf: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005_an.py!} ``` //// @@ -304,7 +304,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` //// @@ -322,7 +322,7 @@ Das gleiche gilt für lt ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} ``` //// @@ -330,7 +330,7 @@ Das gleiche gilt für lt ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.py!} ``` //// @@ -344,7 +344,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` //// diff --git a/docs/de/docs/tutorial/path-params.md b/docs/de/docs/tutorial/path-params.md index 2c1b691a8..9cb172c94 100644 --- a/docs/de/docs/tutorial/path-params.md +++ b/docs/de/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ Sie können Pfad-„Parameter“ oder -„Variablen“ mit der gleichen Syntax deklarieren, welche in Python-Format-Strings verwendet wird: ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` Der Wert des Pfad-Parameters `item_id` wird Ihrer Funktion als das Argument `item_id` übergeben. @@ -19,7 +19,7 @@ Wenn Sie dieses Beispiel ausführen und auf ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} ``` //// @@ -15,7 +15,7 @@ Nehmen wir als Beispiel die folgende Anwendung: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial001.py!} +{!> ../../docs_src/query_params_str_validations/tutorial001.py!} ``` //// @@ -46,7 +46,7 @@ Importieren Sie zuerst: In Python 3.9 oder darüber, ist `Annotated` Teil der Standardbibliothek, also können Sie es von `typing` importieren. ```Python hl_lines="1 3" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} ``` //// @@ -58,7 +58,7 @@ In Versionen unter Python 3.9 importieren Sie `Annotated` von `typing_extensions Es wird bereits mit FastAPI installiert sein. ```Python hl_lines="3-4" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} ``` //// @@ -126,7 +126,7 @@ Jetzt, da wir `Annotated` für unsere Metadaten deklariert haben, fügen Sie `Qu //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} ``` //// @@ -134,7 +134,7 @@ Jetzt, da wir `Annotated` für unsere Metadaten deklariert haben, fügen Sie `Qu //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} ``` //// @@ -164,7 +164,7 @@ So würden Sie `Query()` als Defaultwert Ihres Funktionsparameters verwenden, de //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} ``` //// @@ -172,7 +172,7 @@ So würden Sie `Query()` als Defaultwert Ihres Funktionsparameters verwenden, de //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002.py!} ``` //// @@ -278,7 +278,7 @@ Sie können auch einen Parameter `min_length` hinzufügen: //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} ``` //// @@ -286,7 +286,7 @@ Sie können auch einen Parameter `min_length` hinzufügen: //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} ``` //// @@ -294,7 +294,7 @@ Sie können auch einen Parameter `min_length` hinzufügen: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_an.py!} ``` //// @@ -308,7 +308,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} ``` //// @@ -322,7 +322,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003.py!} ``` //// @@ -334,7 +334,7 @@ Sie können einen ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} ``` //// @@ -342,7 +342,7 @@ Sie können einen ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} ``` //// @@ -350,7 +350,7 @@ Sie können einen ../../../docs_src/query_params_str_validations/tutorial004_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an.py!} ``` //// @@ -364,7 +364,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} ``` //// @@ -378,7 +378,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial004.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004.py!} ``` //// @@ -402,7 +402,7 @@ Sie könnten immer noch Code sehen, der den alten Namen verwendet: //// tab | Python 3.10+ Pydantic v1 ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} ``` //// @@ -418,7 +418,7 @@ Beispielsweise könnten Sie den `q` Query-Parameter so deklarieren, dass er eine //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} ``` //// @@ -426,7 +426,7 @@ Beispielsweise könnten Sie den `q` Query-Parameter so deklarieren, dass er eine //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial005_an.py!} ``` //// @@ -440,7 +440,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial005.py!} +{!> ../../docs_src/query_params_str_validations/tutorial005.py!} ``` //// @@ -488,7 +488,7 @@ Wenn Sie einen Parameter erforderlich machen wollen, während Sie `Query` verwen //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} ``` //// @@ -496,7 +496,7 @@ Wenn Sie einen Parameter erforderlich machen wollen, während Sie `Query` verwen //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006_an.py!} ``` //// @@ -510,7 +510,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006.py!} ``` /// tip | "Tipp" @@ -530,7 +530,7 @@ Es gibt eine Alternative, die explizit deklariert, dass ein Wert erforderlich is //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} ``` //// @@ -538,7 +538,7 @@ Es gibt eine Alternative, die explizit deklariert, dass ein Wert erforderlich is //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006b_an.py!} ``` //// @@ -552,7 +552,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006b.py!} ``` //// @@ -576,7 +576,7 @@ Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwe //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} ``` //// @@ -584,7 +584,7 @@ Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwe //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} ``` //// @@ -592,7 +592,7 @@ Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwe //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_an.py!} ``` //// @@ -606,7 +606,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} ``` //// @@ -620,7 +620,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} ``` //// @@ -646,7 +646,7 @@ Um zum Beispiel einen Query-Parameter `q` zu deklarieren, der mehrere Male in de //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} ``` //// @@ -654,7 +654,7 @@ Um zum Beispiel einen Query-Parameter `q` zu deklarieren, der mehrere Male in de //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} ``` //// @@ -662,7 +662,7 @@ Um zum Beispiel einen Query-Parameter `q` zu deklarieren, der mehrere Male in de //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_an.py!} ``` //// @@ -676,7 +676,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} ``` //// @@ -690,7 +690,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} ``` //// @@ -704,7 +704,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011.py!} ``` //// @@ -745,7 +745,7 @@ Und Sie können auch eine Default-`list`e von Werten definieren, wenn keine übe //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} ``` //// @@ -753,7 +753,7 @@ Und Sie können auch eine Default-`list`e von Werten definieren, wenn keine übe //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_an.py!} ``` //// @@ -767,7 +767,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} ``` //// @@ -781,7 +781,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial012.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012.py!} ``` //// @@ -810,7 +810,7 @@ Sie können auch `list` direkt verwenden, anstelle von `List[str]` (oder `list[s //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} ``` //// @@ -818,7 +818,7 @@ Sie können auch `list` direkt verwenden, anstelle von `List[str]` (oder `list[s //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial013_an.py!} ``` //// @@ -832,7 +832,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial013.py!} +{!> ../../docs_src/query_params_str_validations/tutorial013.py!} ``` //// @@ -864,7 +864,7 @@ Sie können einen Titel hinzufügen – `title`: //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} ``` //// @@ -872,7 +872,7 @@ Sie können einen Titel hinzufügen – `title`: //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} ``` //// @@ -880,7 +880,7 @@ Sie können einen Titel hinzufügen – `title`: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_an.py!} ``` //// @@ -894,7 +894,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} ``` //// @@ -908,7 +908,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007.py!} ``` //// @@ -918,7 +918,7 @@ Und eine Beschreibung – `description`: //// tab | Python 3.10+ ```Python hl_lines="14" -{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} ``` //// @@ -926,7 +926,7 @@ Und eine Beschreibung – `description`: //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} ``` //// @@ -934,7 +934,7 @@ Und eine Beschreibung – `description`: //// tab | Python 3.8+ ```Python hl_lines="15" -{!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_an.py!} ``` //// @@ -948,7 +948,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} ``` //// @@ -962,7 +962,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="13" -{!> ../../../docs_src/query_params_str_validations/tutorial008.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008.py!} ``` //// @@ -988,7 +988,7 @@ Dann können Sie einen `alias` deklarieren, und dieser Alias wird verwendet, um //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} ``` //// @@ -996,7 +996,7 @@ Dann können Sie einen `alias` deklarieren, und dieser Alias wird verwendet, um //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} ``` //// @@ -1004,7 +1004,7 @@ Dann können Sie einen `alias` deklarieren, und dieser Alias wird verwendet, um //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_an.py!} ``` //// @@ -1018,7 +1018,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} ``` //// @@ -1032,7 +1032,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009.py!} ``` //// @@ -1048,7 +1048,7 @@ In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu. //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} ``` //// @@ -1056,7 +1056,7 @@ In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu. //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} ``` //// @@ -1064,7 +1064,7 @@ In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu. //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_an.py!} ``` //// @@ -1078,7 +1078,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="16" -{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} ``` //// @@ -1092,7 +1092,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="18" -{!> ../../../docs_src/query_params_str_validations/tutorial010.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010.py!} ``` //// @@ -1108,7 +1108,7 @@ Um einen Query-Parameter vom generierten OpenAPI-Schema auszuschließen (und dah //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} ``` //// @@ -1116,7 +1116,7 @@ Um einen Query-Parameter vom generierten OpenAPI-Schema auszuschließen (und dah //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} ``` //// @@ -1124,7 +1124,7 @@ Um einen Query-Parameter vom generierten OpenAPI-Schema auszuschließen (und dah //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!} ``` //// @@ -1138,7 +1138,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} ``` //// @@ -1152,7 +1152,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014.py!} ``` //// diff --git a/docs/de/docs/tutorial/query-params.md b/docs/de/docs/tutorial/query-params.md index 136852216..bb1dbdf9c 100644 --- a/docs/de/docs/tutorial/query-params.md +++ b/docs/de/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ Wenn Sie in ihrer Funktion Parameter deklarieren, die nicht Teil der Pfad-Parameter sind, dann werden diese automatisch als „Query“-Parameter interpretiert. ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` Query-Parameter (Deutsch: Abfrage-Parameter) sind die Schlüssel-Wert-Paare, die nach dem `?` in einer URL aufgelistet sind, getrennt durch `&`-Zeichen. @@ -66,7 +66,7 @@ Auf die gleiche Weise können Sie optionale Query-Parameter deklarieren, indem S //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial002_py310.py!} +{!> ../../docs_src/query_params/tutorial002_py310.py!} ``` //// @@ -74,7 +74,7 @@ Auf die gleiche Weise können Sie optionale Query-Parameter deklarieren, indem S //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial002.py!} +{!> ../../docs_src/query_params/tutorial002.py!} ``` //// @@ -94,7 +94,7 @@ Sie können auch `bool`-Typen deklarieren und sie werden konvertiert: //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial003_py310.py!} +{!> ../../docs_src/query_params/tutorial003_py310.py!} ``` //// @@ -102,7 +102,7 @@ Sie können auch `bool`-Typen deklarieren und sie werden konvertiert: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial003.py!} +{!> ../../docs_src/query_params/tutorial003.py!} ``` //// @@ -150,7 +150,7 @@ Parameter werden anhand ihres Namens erkannt: //// tab | Python 3.10+ ```Python hl_lines="6 8" -{!> ../../../docs_src/query_params/tutorial004_py310.py!} +{!> ../../docs_src/query_params/tutorial004_py310.py!} ``` //// @@ -158,7 +158,7 @@ Parameter werden anhand ihres Namens erkannt: //// tab | Python 3.8+ ```Python hl_lines="8 10" -{!> ../../../docs_src/query_params/tutorial004.py!} +{!> ../../docs_src/query_params/tutorial004.py!} ``` //// @@ -172,7 +172,7 @@ Wenn Sie keinen spezifischen Wert haben wollen, sondern der Parameter einfach op Aber wenn Sie wollen, dass ein Query-Parameter erforderlich ist, vergeben Sie einfach keinen Defaultwert: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` Hier ist `needy` ein erforderlicher Query-Parameter vom Typ `str`. @@ -222,7 +222,7 @@ Und natürlich können Sie einige Parameter als erforderlich, einige mit Default //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params/tutorial006_py310.py!} +{!> ../../docs_src/query_params/tutorial006_py310.py!} ``` //// @@ -230,7 +230,7 @@ Und natürlich können Sie einige Parameter als erforderlich, einige mit Default //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params/tutorial006.py!} +{!> ../../docs_src/query_params/tutorial006.py!} ``` //// diff --git a/docs/de/docs/tutorial/request-files.md b/docs/de/docs/tutorial/request-files.md index cf44df5f0..c0d0ef3f2 100644 --- a/docs/de/docs/tutorial/request-files.md +++ b/docs/de/docs/tutorial/request-files.md @@ -19,7 +19,7 @@ Importieren Sie `File` und `UploadFile` von `fastapi`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -27,7 +27,7 @@ Importieren Sie `File` und `UploadFile` von `fastapi`: //// tab | Python 3.8+ ```Python hl_lines="1" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -41,7 +41,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -53,7 +53,7 @@ Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen w //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -61,7 +61,7 @@ Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen w //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -75,7 +75,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -109,7 +109,7 @@ Definieren Sie einen Datei-Parameter mit dem Typ `UploadFile`: //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -117,7 +117,7 @@ Definieren Sie einen Datei-Parameter mit dem Typ `UploadFile`: //// tab | Python 3.8+ ```Python hl_lines="13" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -131,7 +131,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="12" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -220,7 +220,7 @@ Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwe //// tab | Python 3.10+ ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} +{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} ``` //// @@ -228,7 +228,7 @@ Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwe //// tab | Python 3.9+ ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} ``` //// @@ -236,7 +236,7 @@ Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwe //// tab | Python 3.8+ ```Python hl_lines="10 18" -{!> ../../../docs_src/request_files/tutorial001_02_an.py!} +{!> ../../docs_src/request_files/tutorial001_02_an.py!} ``` //// @@ -250,7 +250,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7 15" -{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +{!> ../../docs_src/request_files/tutorial001_02_py310.py!} ``` //// @@ -264,7 +264,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02.py!} +{!> ../../docs_src/request_files/tutorial001_02.py!} ``` //// @@ -276,7 +276,7 @@ Sie können auch `File()` zusammen mit `UploadFile` verwenden, um zum Beispiel z //// tab | Python 3.9+ ```Python hl_lines="9 15" -{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} ``` //// @@ -284,7 +284,7 @@ Sie können auch `File()` zusammen mit `UploadFile` verwenden, um zum Beispiel z //// tab | Python 3.8+ ```Python hl_lines="8 14" -{!> ../../../docs_src/request_files/tutorial001_03_an.py!} +{!> ../../docs_src/request_files/tutorial001_03_an.py!} ``` //// @@ -298,7 +298,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7 13" -{!> ../../../docs_src/request_files/tutorial001_03.py!} +{!> ../../docs_src/request_files/tutorial001_03.py!} ``` //// @@ -314,7 +314,7 @@ Um das zu machen, deklarieren Sie eine Liste von `bytes` oder `UploadFile`s: //// tab | Python 3.9+ ```Python hl_lines="10 15" -{!> ../../../docs_src/request_files/tutorial002_an_py39.py!} +{!> ../../docs_src/request_files/tutorial002_an_py39.py!} ``` //// @@ -322,7 +322,7 @@ Um das zu machen, deklarieren Sie eine Liste von `bytes` oder `UploadFile`s: //// tab | Python 3.8+ ```Python hl_lines="11 16" -{!> ../../../docs_src/request_files/tutorial002_an.py!} +{!> ../../docs_src/request_files/tutorial002_an.py!} ``` //// @@ -336,7 +336,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8 13" -{!> ../../../docs_src/request_files/tutorial002_py39.py!} +{!> ../../docs_src/request_files/tutorial002_py39.py!} ``` //// @@ -350,7 +350,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10 15" -{!> ../../../docs_src/request_files/tutorial002.py!} +{!> ../../docs_src/request_files/tutorial002.py!} ``` //// @@ -372,7 +372,7 @@ Und so wie zuvor können Sie `File()` verwenden, um zusätzliche Parameter zu se //// tab | Python 3.9+ ```Python hl_lines="11 18-20" -{!> ../../../docs_src/request_files/tutorial003_an_py39.py!} +{!> ../../docs_src/request_files/tutorial003_an_py39.py!} ``` //// @@ -380,7 +380,7 @@ Und so wie zuvor können Sie `File()` verwenden, um zusätzliche Parameter zu se //// tab | Python 3.8+ ```Python hl_lines="12 19-21" -{!> ../../../docs_src/request_files/tutorial003_an.py!} +{!> ../../docs_src/request_files/tutorial003_an.py!} ``` //// @@ -394,7 +394,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="9 16" -{!> ../../../docs_src/request_files/tutorial003_py39.py!} +{!> ../../docs_src/request_files/tutorial003_py39.py!} ``` //// @@ -408,7 +408,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="11 18" -{!> ../../../docs_src/request_files/tutorial003.py!} +{!> ../../docs_src/request_files/tutorial003.py!} ``` //// diff --git a/docs/de/docs/tutorial/request-forms-and-files.md b/docs/de/docs/tutorial/request-forms-and-files.md index e109595d1..2b89edbb4 100644 --- a/docs/de/docs/tutorial/request-forms-and-files.md +++ b/docs/de/docs/tutorial/request-forms-and-files.md @@ -15,7 +15,7 @@ Z. B. `pip install python-multipart`. //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} ``` //// @@ -23,7 +23,7 @@ Z. B. `pip install python-multipart`. //// tab | Python 3.8+ ```Python hl_lines="1" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} ``` //// @@ -37,7 +37,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1" -{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001.py!} ``` //// @@ -49,7 +49,7 @@ Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` und `Q //// tab | Python 3.9+ ```Python hl_lines="10-12" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} ``` //// @@ -57,7 +57,7 @@ Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` und `Q //// tab | Python 3.8+ ```Python hl_lines="9-11" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} ``` //// @@ -71,7 +71,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="8" -{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001.py!} ``` //// diff --git a/docs/de/docs/tutorial/request-forms.md b/docs/de/docs/tutorial/request-forms.md index 391788aff..0784aa8c0 100644 --- a/docs/de/docs/tutorial/request-forms.md +++ b/docs/de/docs/tutorial/request-forms.md @@ -17,7 +17,7 @@ Importieren Sie `Form` von `fastapi`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Importieren Sie `Form` von `fastapi`: //// tab | Python 3.8+ ```Python hl_lines="1" -{!> ../../../docs_src/request_forms/tutorial001_an.py!} +{!> ../../docs_src/request_forms/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1" -{!> ../../../docs_src/request_forms/tutorial001.py!} +{!> ../../docs_src/request_forms/tutorial001.py!} ``` //// @@ -51,7 +51,7 @@ Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` mach //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} ``` //// @@ -59,7 +59,7 @@ Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` mach //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/request_forms/tutorial001_an.py!} +{!> ../../docs_src/request_forms/tutorial001_an.py!} ``` //// @@ -73,7 +73,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7" -{!> ../../../docs_src/request_forms/tutorial001.py!} +{!> ../../docs_src/request_forms/tutorial001.py!} ``` //// diff --git a/docs/de/docs/tutorial/response-model.md b/docs/de/docs/tutorial/response-model.md index b480780bc..31ad73c77 100644 --- a/docs/de/docs/tutorial/response-model.md +++ b/docs/de/docs/tutorial/response-model.md @@ -7,7 +7,7 @@ Hierbei können Sie **Typannotationen** genauso verwenden, wie Sie es bei Werten //// tab | Python 3.10+ ```Python hl_lines="16 21" -{!> ../../../docs_src/response_model/tutorial001_01_py310.py!} +{!> ../../docs_src/response_model/tutorial001_01_py310.py!} ``` //// @@ -15,7 +15,7 @@ Hierbei können Sie **Typannotationen** genauso verwenden, wie Sie es bei Werten //// tab | Python 3.9+ ```Python hl_lines="18 23" -{!> ../../../docs_src/response_model/tutorial001_01_py39.py!} +{!> ../../docs_src/response_model/tutorial001_01_py39.py!} ``` //// @@ -23,7 +23,7 @@ Hierbei können Sie **Typannotationen** genauso verwenden, wie Sie es bei Werten //// tab | Python 3.8+ ```Python hl_lines="18 23" -{!> ../../../docs_src/response_model/tutorial001_01.py!} +{!> ../../docs_src/response_model/tutorial001_01.py!} ``` //// @@ -62,7 +62,7 @@ Sie können `response_model` in jeder möglichen *Pfadoperation* verwenden: //// tab | Python 3.10+ ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001_py310.py!} +{!> ../../docs_src/response_model/tutorial001_py310.py!} ``` //// @@ -70,7 +70,7 @@ Sie können `response_model` in jeder möglichen *Pfadoperation* verwenden: //// tab | Python 3.9+ ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001_py39.py!} +{!> ../../docs_src/response_model/tutorial001_py39.py!} ``` //// @@ -78,7 +78,7 @@ Sie können `response_model` in jeder möglichen *Pfadoperation* verwenden: //// tab | Python 3.8+ ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001.py!} +{!> ../../docs_src/response_model/tutorial001.py!} ``` //// @@ -116,7 +116,7 @@ Im Folgenden deklarieren wir ein `UserIn`-Modell; es enthält ein Klartext-Passw //// tab | Python 3.10+ ```Python hl_lines="7 9" -{!> ../../../docs_src/response_model/tutorial002_py310.py!} +{!> ../../docs_src/response_model/tutorial002_py310.py!} ``` //// @@ -124,7 +124,7 @@ Im Folgenden deklarieren wir ein `UserIn`-Modell; es enthält ein Klartext-Passw //// tab | Python 3.8+ ```Python hl_lines="9 11" -{!> ../../../docs_src/response_model/tutorial002.py!} +{!> ../../docs_src/response_model/tutorial002.py!} ``` //// @@ -143,7 +143,7 @@ Wir verwenden dieses Modell, um sowohl unsere Eingabe- als auch Ausgabedaten zu //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/response_model/tutorial002_py310.py!} +{!> ../../docs_src/response_model/tutorial002_py310.py!} ``` //// @@ -151,7 +151,7 @@ Wir verwenden dieses Modell, um sowohl unsere Eingabe- als auch Ausgabedaten zu //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/response_model/tutorial002.py!} +{!> ../../docs_src/response_model/tutorial002.py!} ``` //// @@ -175,7 +175,7 @@ Wir können stattdessen ein Eingabemodell mit dem Klartext-Passwort, und ein Aus //// tab | Python 3.10+ ```Python hl_lines="9 11 16" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -183,7 +183,7 @@ Wir können stattdessen ein Eingabemodell mit dem Klartext-Passwort, und ein Aus //// tab | Python 3.8+ ```Python hl_lines="9 11 16" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -193,7 +193,7 @@ Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zur //// tab | Python 3.10+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -201,7 +201,7 @@ Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zur //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -211,7 +211,7 @@ Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zur //// tab | Python 3.10+ ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -219,7 +219,7 @@ Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zur //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -249,7 +249,7 @@ Und in solchen Fällen können wir Klassen und Vererbung verwenden, um Vorteil a //// tab | Python 3.10+ ```Python hl_lines="7-10 13-14 18" -{!> ../../../docs_src/response_model/tutorial003_01_py310.py!} +{!> ../../docs_src/response_model/tutorial003_01_py310.py!} ``` //// @@ -257,7 +257,7 @@ Und in solchen Fällen können wir Klassen und Vererbung verwenden, um Vorteil a //// tab | Python 3.8+ ```Python hl_lines="9-13 15-16 20" -{!> ../../../docs_src/response_model/tutorial003_01.py!} +{!> ../../docs_src/response_model/tutorial003_01.py!} ``` //// @@ -303,7 +303,7 @@ Es kann Fälle geben, bei denen Sie etwas zurückgeben, das kein gültiges Pydan Der häufigste Anwendungsfall ist, wenn Sie [eine Response direkt zurückgeben, wie es später im Handbuch für fortgeschrittene Benutzer erläutert wird](../advanced/response-directly.md){.internal-link target=_blank}. ```Python hl_lines="8 10-11" -{!> ../../../docs_src/response_model/tutorial003_02.py!} +{!> ../../docs_src/response_model/tutorial003_02.py!} ``` Dieser einfache Anwendungsfall wird automatisch von FastAPI gehandhabt, weil die Annotation des Rückgabetyps die Klasse (oder eine Unterklasse von) `Response` ist. @@ -315,7 +315,7 @@ Und Tools werden auch glücklich sein, weil sowohl `RedirectResponse` als auch ` Sie können auch eine Unterklasse von `Response` in der Typannotation verwenden. ```Python hl_lines="8-9" -{!> ../../../docs_src/response_model/tutorial003_03.py!} +{!> ../../docs_src/response_model/tutorial003_03.py!} ``` Das wird ebenfalls funktionieren, weil `RedirectResponse` eine Unterklasse von `Response` ist, und FastAPI sich um diesen einfachen Anwendungsfall automatisch kümmert. @@ -329,7 +329,7 @@ Das gleiche wird passieren, wenn Sie eine ../../../docs_src/response_model/tutorial003_04.py!} +{!> ../../docs_src/response_model/tutorial003_04.py!} ``` //// @@ -355,7 +355,7 @@ In diesem Fall können Sie die Generierung des Responsemodells abschalten, indem //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/response_model/tutorial003_05_py310.py!} +{!> ../../docs_src/response_model/tutorial003_05_py310.py!} ``` //// @@ -363,7 +363,7 @@ In diesem Fall können Sie die Generierung des Responsemodells abschalten, indem //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/response_model/tutorial003_05.py!} +{!> ../../docs_src/response_model/tutorial003_05.py!} ``` //// @@ -377,7 +377,7 @@ Ihr Responsemodell könnte Defaultwerte haben, wie: //// tab | Python 3.10+ ```Python hl_lines="9 11-12" -{!> ../../../docs_src/response_model/tutorial004_py310.py!} +{!> ../../docs_src/response_model/tutorial004_py310.py!} ``` //// @@ -385,7 +385,7 @@ Ihr Responsemodell könnte Defaultwerte haben, wie: //// tab | Python 3.9+ ```Python hl_lines="11 13-14" -{!> ../../../docs_src/response_model/tutorial004_py39.py!} +{!> ../../docs_src/response_model/tutorial004_py39.py!} ``` //// @@ -393,7 +393,7 @@ Ihr Responsemodell könnte Defaultwerte haben, wie: //// tab | Python 3.8+ ```Python hl_lines="11 13-14" -{!> ../../../docs_src/response_model/tutorial004.py!} +{!> ../../docs_src/response_model/tutorial004.py!} ``` //// @@ -413,7 +413,7 @@ Sie können den *Pfadoperation-Dekorator*-Parameter `response_model_exclude_unse //// tab | Python 3.10+ ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial004_py310.py!} +{!> ../../docs_src/response_model/tutorial004_py310.py!} ``` //// @@ -421,7 +421,7 @@ Sie können den *Pfadoperation-Dekorator*-Parameter `response_model_exclude_unse //// tab | Python 3.9+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial004_py39.py!} +{!> ../../docs_src/response_model/tutorial004_py39.py!} ``` //// @@ -429,7 +429,7 @@ Sie können den *Pfadoperation-Dekorator*-Parameter `response_model_exclude_unse //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial004.py!} +{!> ../../docs_src/response_model/tutorial004.py!} ``` //// @@ -532,7 +532,7 @@ Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert. //// tab | Python 3.10+ ```Python hl_lines="29 35" -{!> ../../../docs_src/response_model/tutorial005_py310.py!} +{!> ../../docs_src/response_model/tutorial005_py310.py!} ``` //// @@ -540,7 +540,7 @@ Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert. //// tab | Python 3.8+ ```Python hl_lines="31 37" -{!> ../../../docs_src/response_model/tutorial005.py!} +{!> ../../docs_src/response_model/tutorial005.py!} ``` //// @@ -560,7 +560,7 @@ Wenn Sie vergessen, ein `set` zu verwenden, und stattdessen eine `list`e oder ei //// tab | Python 3.10+ ```Python hl_lines="29 35" -{!> ../../../docs_src/response_model/tutorial006_py310.py!} +{!> ../../docs_src/response_model/tutorial006_py310.py!} ``` //// @@ -568,7 +568,7 @@ Wenn Sie vergessen, ein `set` zu verwenden, und stattdessen eine `list`e oder ei //// tab | Python 3.8+ ```Python hl_lines="31 37" -{!> ../../../docs_src/response_model/tutorial006.py!} +{!> ../../docs_src/response_model/tutorial006.py!} ``` //// diff --git a/docs/de/docs/tutorial/response-status-code.md b/docs/de/docs/tutorial/response-status-code.md index 5f96b83e4..872007a12 100644 --- a/docs/de/docs/tutorial/response-status-code.md +++ b/docs/de/docs/tutorial/response-status-code.md @@ -9,7 +9,7 @@ So wie ein Responsemodell, können Sie auch einen HTTP-Statuscode für die Respo * usw. ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` /// note | "Hinweis" @@ -77,7 +77,7 @@ Um mehr über Statuscodes zu lernen, und welcher wofür verwendet wird, lesen Si Schauen wir uns das vorherige Beispiel noch einmal an: ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` `201` ist der Statuscode für „Created“ („Erzeugt“). @@ -87,7 +87,7 @@ Aber Sie müssen sich nicht daran erinnern, welcher dieser Codes was bedeutet. Sie können die Hilfsvariablen von `fastapi.status` verwenden. ```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} +{!../../docs_src/response_status_code/tutorial002.py!} ``` Diese sind nur eine Annehmlichkeit und enthalten dieselbe Nummer, aber auf diese Weise können Sie die Autovervollständigung Ihres Editors verwenden, um sie zu finden: diff --git a/docs/de/docs/tutorial/schema-extra-example.md b/docs/de/docs/tutorial/schema-extra-example.md index 07b4bb759..0da1a4ea4 100644 --- a/docs/de/docs/tutorial/schema-extra-example.md +++ b/docs/de/docs/tutorial/schema-extra-example.md @@ -11,7 +11,7 @@ Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, w //// tab | Python 3.10+ Pydantic v2 ```Python hl_lines="13-24" -{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} ``` //// @@ -19,7 +19,7 @@ Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, w //// tab | Python 3.10+ Pydantic v1 ```Python hl_lines="13-23" -{!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} ``` //// @@ -27,7 +27,7 @@ Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, w //// tab | Python 3.8+ Pydantic v2 ```Python hl_lines="15-26" -{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +{!> ../../docs_src/schema_extra_example/tutorial001.py!} ``` //// @@ -35,7 +35,7 @@ Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, w //// tab | Python 3.8+ Pydantic v1 ```Python hl_lines="15-25" -{!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_pv1.py!} ``` //// @@ -83,7 +83,7 @@ Wenn Sie `Field()` mit Pydantic-Modellen verwenden, können Sie ebenfalls zusät //// tab | Python 3.10+ ```Python hl_lines="2 8-11" -{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} ``` //// @@ -91,7 +91,7 @@ Wenn Sie `Field()` mit Pydantic-Modellen verwenden, können Sie ebenfalls zusät //// tab | Python 3.8+ ```Python hl_lines="4 10-13" -{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +{!> ../../docs_src/schema_extra_example/tutorial002.py!} ``` //// @@ -117,7 +117,7 @@ Hier übergeben wir `examples`, welches ein einzelnes Beispiel für die in `Body //// tab | Python 3.10+ ```Python hl_lines="22-29" -{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} ``` //// @@ -125,7 +125,7 @@ Hier übergeben wir `examples`, welches ein einzelnes Beispiel für die in `Body //// tab | Python 3.9+ ```Python hl_lines="22-29" -{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} ``` //// @@ -133,7 +133,7 @@ Hier übergeben wir `examples`, welches ein einzelnes Beispiel für die in `Body //// tab | Python 3.8+ ```Python hl_lines="23-30" -{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} ``` //// @@ -147,7 +147,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="18-25" -{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} ``` //// @@ -161,7 +161,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="20-27" -{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +{!> ../../docs_src/schema_extra_example/tutorial003.py!} ``` //// @@ -179,7 +179,7 @@ Sie können natürlich auch mehrere `examples` übergeben: //// tab | Python 3.10+ ```Python hl_lines="23-38" -{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!} ``` //// @@ -187,7 +187,7 @@ Sie können natürlich auch mehrere `examples` übergeben: //// tab | Python 3.9+ ```Python hl_lines="23-38" -{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!} ``` //// @@ -195,7 +195,7 @@ Sie können natürlich auch mehrere `examples` übergeben: //// tab | Python 3.8+ ```Python hl_lines="24-39" -{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an.py!} ``` //// @@ -209,7 +209,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="19-34" -{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} ``` //// @@ -223,7 +223,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="21-36" -{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +{!> ../../docs_src/schema_extra_example/tutorial004.py!} ``` //// @@ -270,7 +270,7 @@ Sie können es so verwenden: //// tab | Python 3.10+ ```Python hl_lines="23-49" -{!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_an_py310.py!} ``` //// @@ -278,7 +278,7 @@ Sie können es so verwenden: //// tab | Python 3.9+ ```Python hl_lines="23-49" -{!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_an_py39.py!} ``` //// @@ -286,7 +286,7 @@ Sie können es so verwenden: //// tab | Python 3.8+ ```Python hl_lines="24-50" -{!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_an.py!} ``` //// @@ -300,7 +300,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="19-45" -{!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_py310.py!} ``` //// @@ -314,7 +314,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="21-47" -{!> ../../../docs_src/schema_extra_example/tutorial005.py!} +{!> ../../docs_src/schema_extra_example/tutorial005.py!} ``` //// diff --git a/docs/de/docs/tutorial/security/first-steps.md b/docs/de/docs/tutorial/security/first-steps.md index 6bc42cf6c..c552a681b 100644 --- a/docs/de/docs/tutorial/security/first-steps.md +++ b/docs/de/docs/tutorial/security/first-steps.md @@ -23,7 +23,7 @@ Kopieren Sie das Beispiel in eine Datei `main.py`: //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -31,7 +31,7 @@ Kopieren Sie das Beispiel in eine Datei `main.py`: //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -45,7 +45,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// @@ -157,7 +157,7 @@ Wenn wir eine Instanz der Klasse `OAuth2PasswordBearer` erstellen, übergeben wi //// tab | Python 3.9+ ```Python hl_lines="8" -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -165,7 +165,7 @@ Wenn wir eine Instanz der Klasse `OAuth2PasswordBearer` erstellen, übergeben wi //// tab | Python 3.8+ ```Python hl_lines="7" -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -179,7 +179,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="6" -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// @@ -223,7 +223,7 @@ Jetzt können Sie dieses `oauth2_scheme` als Abhängigkeit `Depends` übergeben. //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -231,7 +231,7 @@ Jetzt können Sie dieses `oauth2_scheme` als Abhängigkeit `Depends` übergeben. //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -245,7 +245,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10" -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// diff --git a/docs/de/docs/tutorial/security/get-current-user.md b/docs/de/docs/tutorial/security/get-current-user.md index 8a68deeef..a9478a36e 100644 --- a/docs/de/docs/tutorial/security/get-current-user.md +++ b/docs/de/docs/tutorial/security/get-current-user.md @@ -5,7 +5,7 @@ Im vorherigen Kapitel hat das Sicherheitssystem (das auf dem Dependency Injectio //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -13,7 +13,7 @@ Im vorherigen Kapitel hat das Sicherheitssystem (das auf dem Dependency Injectio //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -27,7 +27,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="10" -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// @@ -45,7 +45,7 @@ So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch üb //// tab | Python 3.10+ ```Python hl_lines="5 12-16" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -53,7 +53,7 @@ So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch üb //// tab | Python 3.9+ ```Python hl_lines="5 12-16" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -61,7 +61,7 @@ So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch üb //// tab | Python 3.8+ ```Python hl_lines="5 13-17" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -75,7 +75,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="3 10-14" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -89,7 +89,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="5 12-16" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -107,7 +107,7 @@ So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere //// tab | Python 3.10+ ```Python hl_lines="25" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -115,7 +115,7 @@ So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere //// tab | Python 3.9+ ```Python hl_lines="25" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -123,7 +123,7 @@ So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere //// tab | Python 3.8+ ```Python hl_lines="26" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -137,7 +137,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="23" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -151,7 +151,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="25" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -163,7 +163,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.10+ ```Python hl_lines="19-22 26-27" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -171,7 +171,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.9+ ```Python hl_lines="19-22 26-27" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -179,7 +179,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ ```Python hl_lines="20-23 27-28" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -193,7 +193,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="17-20 24-25" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -207,7 +207,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="19-22 26-27" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -219,7 +219,7 @@ Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der * //// tab | Python 3.10+ ```Python hl_lines="31" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -227,7 +227,7 @@ Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der * //// tab | Python 3.9+ ```Python hl_lines="31" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -235,7 +235,7 @@ Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der * //// tab | Python 3.8+ ```Python hl_lines="32" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -249,7 +249,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="29" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -263,7 +263,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="31" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -323,7 +323,7 @@ Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein //// tab | Python 3.10+ ```Python hl_lines="30-32" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -331,7 +331,7 @@ Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein //// tab | Python 3.9+ ```Python hl_lines="30-32" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -339,7 +339,7 @@ Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein //// tab | Python 3.8+ ```Python hl_lines="31-33" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -353,7 +353,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="28-30" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -367,7 +367,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="30-32" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// diff --git a/docs/de/docs/tutorial/security/oauth2-jwt.md b/docs/de/docs/tutorial/security/oauth2-jwt.md index 88f0dbe42..79e817840 100644 --- a/docs/de/docs/tutorial/security/oauth2-jwt.md +++ b/docs/de/docs/tutorial/security/oauth2-jwt.md @@ -121,7 +121,7 @@ Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben. //// tab | Python 3.10+ ```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../../docs_src/security/tutorial004_an_py310.py!} +{!> ../../docs_src/security/tutorial004_an_py310.py!} ``` //// @@ -129,7 +129,7 @@ Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben. //// tab | Python 3.9+ ```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../../docs_src/security/tutorial004_an_py39.py!} +{!> ../../docs_src/security/tutorial004_an_py39.py!} ``` //// @@ -137,7 +137,7 @@ Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben. //// tab | Python 3.8+ ```Python hl_lines="7 49 56-57 60-61 70-76" -{!> ../../../docs_src/security/tutorial004_an.py!} +{!> ../../docs_src/security/tutorial004_an.py!} ``` //// @@ -151,7 +151,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="6 47 54-55 58-59 68-74" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -165,7 +165,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -207,7 +207,7 @@ Erstellen Sie eine Hilfsfunktion, um einen neuen Zugriffstoken zu generieren. //// tab | Python 3.10+ ```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../../docs_src/security/tutorial004_an_py310.py!} +{!> ../../docs_src/security/tutorial004_an_py310.py!} ``` //// @@ -215,7 +215,7 @@ Erstellen Sie eine Hilfsfunktion, um einen neuen Zugriffstoken zu generieren. //// tab | Python 3.9+ ```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../../docs_src/security/tutorial004_an_py39.py!} +{!> ../../docs_src/security/tutorial004_an_py39.py!} ``` //// @@ -223,7 +223,7 @@ Erstellen Sie eine Hilfsfunktion, um einen neuen Zugriffstoken zu generieren. //// tab | Python 3.8+ ```Python hl_lines="6 13-15 29-31 79-87" -{!> ../../../docs_src/security/tutorial004_an.py!} +{!> ../../docs_src/security/tutorial004_an.py!} ``` //// @@ -237,7 +237,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="5 11-13 27-29 77-85" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -251,7 +251,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -267,7 +267,7 @@ Wenn der Token ungültig ist, geben Sie sofort einen HTTP-Fehler zurück. //// tab | Python 3.10+ ```Python hl_lines="89-106" -{!> ../../../docs_src/security/tutorial004_an_py310.py!} +{!> ../../docs_src/security/tutorial004_an_py310.py!} ``` //// @@ -275,7 +275,7 @@ Wenn der Token ungültig ist, geben Sie sofort einen HTTP-Fehler zurück. //// tab | Python 3.9+ ```Python hl_lines="89-106" -{!> ../../../docs_src/security/tutorial004_an_py39.py!} +{!> ../../docs_src/security/tutorial004_an_py39.py!} ``` //// @@ -283,7 +283,7 @@ Wenn der Token ungültig ist, geben Sie sofort einen HTTP-Fehler zurück. //// tab | Python 3.8+ ```Python hl_lines="90-107" -{!> ../../../docs_src/security/tutorial004_an.py!} +{!> ../../docs_src/security/tutorial004_an.py!} ``` //// @@ -297,7 +297,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="88-105" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -311,7 +311,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="89-106" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -325,7 +325,7 @@ Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück. //// tab | Python 3.10+ ```Python hl_lines="117-132" -{!> ../../../docs_src/security/tutorial004_an_py310.py!} +{!> ../../docs_src/security/tutorial004_an_py310.py!} ``` //// @@ -333,7 +333,7 @@ Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück. //// tab | Python 3.9+ ```Python hl_lines="117-132" -{!> ../../../docs_src/security/tutorial004_an_py39.py!} +{!> ../../docs_src/security/tutorial004_an_py39.py!} ``` //// @@ -341,7 +341,7 @@ Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück. //// tab | Python 3.8+ ```Python hl_lines="118-133" -{!> ../../../docs_src/security/tutorial004_an.py!} +{!> ../../docs_src/security/tutorial004_an.py!} ``` //// @@ -355,7 +355,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="114-129" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -369,7 +369,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="115-130" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// diff --git a/docs/de/docs/tutorial/security/simple-oauth2.md b/docs/de/docs/tutorial/security/simple-oauth2.md index 3b1c4ae28..4c20fae55 100644 --- a/docs/de/docs/tutorial/security/simple-oauth2.md +++ b/docs/de/docs/tutorial/security/simple-oauth2.md @@ -55,7 +55,7 @@ Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als A //// tab | Python 3.10+ ```Python hl_lines="4 78" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -63,7 +63,7 @@ Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als A //// tab | Python 3.9+ ```Python hl_lines="4 78" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -71,7 +71,7 @@ Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als A //// tab | Python 3.8+ ```Python hl_lines="4 79" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -85,7 +85,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="2 74" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -99,7 +99,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="4 76" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -153,7 +153,7 @@ Für den Fehler verwenden wir die Exception `HTTPException`: //// tab | Python 3.10+ ```Python hl_lines="3 79-81" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -161,7 +161,7 @@ Für den Fehler verwenden wir die Exception `HTTPException`: //// tab | Python 3.9+ ```Python hl_lines="3 79-81" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -169,7 +169,7 @@ Für den Fehler verwenden wir die Exception `HTTPException`: //// tab | Python 3.8+ ```Python hl_lines="3 80-82" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -183,7 +183,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="1 75-77" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -197,7 +197,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="3 77-79" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -229,7 +229,7 @@ Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen Sy //// tab | Python 3.10+ ```Python hl_lines="82-85" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -237,7 +237,7 @@ Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen Sy //// tab | Python 3.9+ ```Python hl_lines="82-85" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -245,7 +245,7 @@ Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen Sy //// tab | Python 3.8+ ```Python hl_lines="83-86" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -259,7 +259,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="78-81" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -273,7 +273,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="80-83" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -321,7 +321,7 @@ Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benö //// tab | Python 3.10+ ```Python hl_lines="87" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -329,7 +329,7 @@ Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benö //// tab | Python 3.9+ ```Python hl_lines="87" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -337,7 +337,7 @@ Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benö //// tab | Python 3.8+ ```Python hl_lines="88" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -351,7 +351,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="83" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -365,7 +365,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="85" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -397,7 +397,7 @@ In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer //// tab | Python 3.10+ ```Python hl_lines="58-66 69-74 94" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -405,7 +405,7 @@ In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer //// tab | Python 3.9+ ```Python hl_lines="58-66 69-74 94" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -413,7 +413,7 @@ In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer //// tab | Python 3.8+ ```Python hl_lines="59-67 70-75 95" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -427,7 +427,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="56-64 67-70 88" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -441,7 +441,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python hl_lines="58-66 69-72 90" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// diff --git a/docs/de/docs/tutorial/static-files.md b/docs/de/docs/tutorial/static-files.md index cca8cd0ea..4afd251aa 100644 --- a/docs/de/docs/tutorial/static-files.md +++ b/docs/de/docs/tutorial/static-files.md @@ -8,7 +8,7 @@ Mit `StaticFiles` können Sie statische Dateien aus einem Verzeichnis automatisc * „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad. ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` /// note | "Technische Details" diff --git a/docs/de/docs/tutorial/testing.md b/docs/de/docs/tutorial/testing.md index 43ced2aae..bda6d7d60 100644 --- a/docs/de/docs/tutorial/testing.md +++ b/docs/de/docs/tutorial/testing.md @@ -27,7 +27,7 @@ Verwenden Sie das `TestClient`-Objekt auf die gleiche Weise wie `httpx`. Schreiben Sie einfache `assert`-Anweisungen mit den Standard-Python-Ausdrücken, die Sie überprüfen müssen (wiederum, Standard-`pytest`). ```Python hl_lines="2 12 15-18" -{!../../../docs_src/app_testing/tutorial001.py!} +{!../../docs_src/app_testing/tutorial001.py!} ``` /// tip | "Tipp" @@ -75,7 +75,7 @@ In der Datei `main.py` haben Sie Ihre **FastAPI**-Anwendung: ```Python -{!../../../docs_src/app_testing/main.py!} +{!../../docs_src/app_testing/main.py!} ``` ### Testdatei @@ -93,7 +93,7 @@ Dann könnten Sie eine Datei `test_main.py` mit Ihren Tests haben. Sie könnte s Da sich diese Datei im selben Package befindet, können Sie relative Importe verwenden, um das Objekt `app` aus dem `main`-Modul (`main.py`) zu importieren: ```Python hl_lines="3" -{!../../../docs_src/app_testing/test_main.py!} +{!../../docs_src/app_testing/test_main.py!} ``` ... und haben den Code für die Tests wie zuvor. @@ -125,7 +125,7 @@ Beide *Pfadoperationen* erfordern einen `X-Token`-Header. //// tab | Python 3.10+ ```Python -{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} ``` //// @@ -133,7 +133,7 @@ Beide *Pfadoperationen* erfordern einen `X-Token`-Header. //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} ``` //// @@ -141,7 +141,7 @@ Beide *Pfadoperationen* erfordern einen `X-Token`-Header. //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/app_testing/app_b_an/main.py!} +{!> ../../docs_src/app_testing/app_b_an/main.py!} ``` //// @@ -155,7 +155,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python -{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_py310/main.py!} ``` //// @@ -169,7 +169,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. /// ```Python -{!> ../../../docs_src/app_testing/app_b/main.py!} +{!> ../../docs_src/app_testing/app_b/main.py!} ``` //// @@ -179,7 +179,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. Anschließend könnten Sie `test_main.py` mit den erweiterten Tests aktualisieren: ```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} +{!> ../../docs_src/app_testing/app_b/test_main.py!} ``` Wenn Sie möchten, dass der Client Informationen im Request übergibt und Sie nicht wissen, wie das geht, können Sie suchen (googeln), wie es mit `httpx` gemacht wird, oder sogar, wie es mit `requests` gemacht wird, da das Design von HTTPX auf dem Design von Requests basiert. diff --git a/docs/em/docs/advanced/additional-responses.md b/docs/em/docs/advanced/additional-responses.md index 7a70718c5..e4442135e 100644 --- a/docs/em/docs/advanced/additional-responses.md +++ b/docs/em/docs/advanced/additional-responses.md @@ -27,7 +27,7 @@ 🖼, 📣 ➕1️⃣ 📨 ⏮️ 👔 📟 `404` & Pydantic 🏷 `Message`, 👆 💪 ✍: ```Python hl_lines="18 22" -{!../../../docs_src/additional_responses/tutorial001.py!} +{!../../docs_src/additional_responses/tutorial001.py!} ``` /// note @@ -178,7 +178,7 @@ 🖼, 👆 💪 🚮 🌖 📻 🆎 `image/png`, 📣 👈 👆 *➡ 🛠️* 💪 📨 🎻 🎚 (⏮️ 📻 🆎 `application/json`) ⚖️ 🇩🇴 🖼: ```Python hl_lines="19-24 28" -{!../../../docs_src/additional_responses/tutorial002.py!} +{!../../docs_src/additional_responses/tutorial002.py!} ``` /// note @@ -208,7 +208,7 @@ & 📨 ⏮️ 👔 📟 `200` 👈 ⚙️ 👆 `response_model`, ✋️ 🔌 🛃 `example`: ```Python hl_lines="20-31" -{!../../../docs_src/additional_responses/tutorial003.py!} +{!../../docs_src/additional_responses/tutorial003.py!} ``` ⚫️ 🔜 🌐 🌀 & 🔌 👆 🗄, & 🎦 🛠️ 🩺: @@ -244,7 +244,7 @@ new_dict = {**old_dict, "new key": "new value"} 🖼: ```Python hl_lines="13-17 26" -{!../../../docs_src/additional_responses/tutorial004.py!} +{!../../docs_src/additional_responses/tutorial004.py!} ``` ## 🌖 ℹ 🔃 🗄 📨 diff --git a/docs/em/docs/advanced/additional-status-codes.md b/docs/em/docs/advanced/additional-status-codes.md index 3f3b0aea4..7a50e1bca 100644 --- a/docs/em/docs/advanced/additional-status-codes.md +++ b/docs/em/docs/advanced/additional-status-codes.md @@ -15,7 +15,7 @@ 🏆 👈, 🗄 `JSONResponse`, & 📨 👆 🎚 📤 🔗, ⚒ `status_code` 👈 👆 💚: ```Python hl_lines="4 25" -{!../../../docs_src/additional_status_codes/tutorial001.py!} +{!../../docs_src/additional_status_codes/tutorial001.py!} ``` /// warning diff --git a/docs/em/docs/advanced/advanced-dependencies.md b/docs/em/docs/advanced/advanced-dependencies.md index 22044c783..721428ce4 100644 --- a/docs/em/docs/advanced/advanced-dependencies.md +++ b/docs/em/docs/advanced/advanced-dependencies.md @@ -19,7 +19,7 @@ 👈, 👥 📣 👩‍🔬 `__call__`: ```Python hl_lines="10" -{!../../../docs_src/dependencies/tutorial011.py!} +{!../../docs_src/dependencies/tutorial011.py!} ``` 👉 💼, 👉 `__call__` ⚫️❔ **FastAPI** 🔜 ⚙️ ✅ 🌖 🔢 & 🎧-🔗, & 👉 ⚫️❔ 🔜 🤙 🚶‍♀️ 💲 🔢 👆 *➡ 🛠️ 🔢* ⏪. @@ -29,7 +29,7 @@ & 🔜, 👥 💪 ⚙️ `__init__` 📣 🔢 👐 👈 👥 💪 ⚙️ "🔗" 🔗: ```Python hl_lines="7" -{!../../../docs_src/dependencies/tutorial011.py!} +{!../../docs_src/dependencies/tutorial011.py!} ``` 👉 💼, **FastAPI** 🏆 🚫 ⏱ 👆 ⚖️ 💅 🔃 `__init__`, 👥 🔜 ⚙️ ⚫️ 🔗 👆 📟. @@ -39,7 +39,7 @@ 👥 💪 ✍ 👐 👉 🎓 ⏮️: ```Python hl_lines="16" -{!../../../docs_src/dependencies/tutorial011.py!} +{!../../docs_src/dependencies/tutorial011.py!} ``` & 👈 🌌 👥 💪 "🔗" 👆 🔗, 👈 🔜 ✔️ `"bar"` 🔘 ⚫️, 🔢 `checker.fixed_content`. @@ -57,7 +57,7 @@ checker(q="somequery") ...& 🚶‍♀️ ⚫️❔ 👈 📨 💲 🔗 👆 *➡ 🛠️ 🔢* 🔢 `fixed_content_included`: ```Python hl_lines="20" -{!../../../docs_src/dependencies/tutorial011.py!} +{!../../docs_src/dependencies/tutorial011.py!} ``` /// tip diff --git a/docs/em/docs/advanced/async-tests.md b/docs/em/docs/advanced/async-tests.md index 11f885fe6..4d468acd4 100644 --- a/docs/em/docs/advanced/async-tests.md +++ b/docs/em/docs/advanced/async-tests.md @@ -33,13 +33,13 @@ 📁 `main.py` 🔜 ✔️: ```Python -{!../../../docs_src/async_tests/main.py!} +{!../../docs_src/async_tests/main.py!} ``` 📁 `test_main.py` 🔜 ✔️ 💯 `main.py`, ⚫️ 💪 👀 💖 👉 🔜: ```Python -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` ## 🏃 ⚫️ @@ -61,7 +61,7 @@ $ pytest 📑 `@pytest.mark.anyio` 💬 ✳ 👈 👉 💯 🔢 🔜 🤙 🔁: ```Python hl_lines="7" -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` /// tip @@ -73,7 +73,7 @@ $ pytest ⤴️ 👥 💪 ✍ `AsyncClient` ⏮️ 📱, & 📨 🔁 📨 ⚫️, ⚙️ `await`. ```Python hl_lines="9-12" -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` 👉 🌓: diff --git a/docs/em/docs/advanced/behind-a-proxy.md b/docs/em/docs/advanced/behind-a-proxy.md index bb65e1487..e66ddccf7 100644 --- a/docs/em/docs/advanced/behind-a-proxy.md +++ b/docs/em/docs/advanced/behind-a-proxy.md @@ -95,7 +95,7 @@ $ uvicorn main:app --root-path /api/v1 📥 👥 ✅ ⚫️ 📧 🎦 🎯. ```Python hl_lines="8" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} +{!../../docs_src/behind_a_proxy/tutorial001.py!} ``` ⤴️, 🚥 👆 ▶️ Uvicorn ⏮️: @@ -124,7 +124,7 @@ $ uvicorn main:app --root-path /api/v1 👐, 🚥 👆 🚫 ✔️ 🌌 🚚 📋 ⏸ 🎛 💖 `--root-path` ⚖️ 🌓, 👆 💪 ⚒ `root_path` 🔢 🕐❔ 🏗 👆 FastAPI 📱: ```Python hl_lines="3" -{!../../../docs_src/behind_a_proxy/tutorial002.py!} +{!../../docs_src/behind_a_proxy/tutorial002.py!} ``` 🚶‍♀️ `root_path` `FastAPI` 🔜 🌓 🚶‍♀️ `--root-path` 📋 ⏸ 🎛 Uvicorn ⚖️ Hypercorn. @@ -306,7 +306,7 @@ $ uvicorn main:app --root-path /api/v1 🖼: ```Python hl_lines="4-7" -{!../../../docs_src/behind_a_proxy/tutorial003.py!} +{!../../docs_src/behind_a_proxy/tutorial003.py!} ``` 🔜 🏗 🗄 🔗 💖: @@ -355,7 +355,7 @@ $ uvicorn main:app --root-path /api/v1 🚥 👆 🚫 💚 **FastAPI** 🔌 🏧 💽 ⚙️ `root_path`, 👆 💪 ⚙️ 🔢 `root_path_in_servers=False`: ```Python hl_lines="9" -{!../../../docs_src/behind_a_proxy/tutorial004.py!} +{!../../docs_src/behind_a_proxy/tutorial004.py!} ``` & ⤴️ ⚫️ 🏆 🚫 🔌 ⚫️ 🗄 🔗. diff --git a/docs/em/docs/advanced/custom-response.md b/docs/em/docs/advanced/custom-response.md index eec87b91b..7147a4536 100644 --- a/docs/em/docs/advanced/custom-response.md +++ b/docs/em/docs/advanced/custom-response.md @@ -31,7 +31,7 @@ ✋️ 🚥 👆 🎯 👈 🎚 👈 👆 🛬 **🎻 ⏮️ 🎻**, 👆 💪 🚶‍♀️ ⚫️ 🔗 📨 🎓 & ❎ ➕ 🌥 👈 FastAPI 🔜 ✔️ 🚶‍♀️ 👆 📨 🎚 🔘 `jsonable_encoder` ⏭ 🚶‍♀️ ⚫️ 📨 🎓. ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001b.py!} +{!../../docs_src/custom_response/tutorial001b.py!} ``` /// info @@ -58,7 +58,7 @@ * 🚶‍♀️ `HTMLResponse` 🔢 `response_class` 👆 *➡ 🛠️ 👨‍🎨*. ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial002.py!} +{!../../docs_src/custom_response/tutorial002.py!} ``` /// info @@ -78,7 +78,7 @@ 🎏 🖼 ⚪️➡️ 🔛, 🛬 `HTMLResponse`, 💪 👀 💖: ```Python hl_lines="2 7 19" -{!../../../docs_src/custom_response/tutorial003.py!} +{!../../docs_src/custom_response/tutorial003.py!} ``` /// warning @@ -104,7 +104,7 @@ 🖼, ⚫️ 💪 🕳 💖: ```Python hl_lines="7 21 23" -{!../../../docs_src/custom_response/tutorial004.py!} +{!../../docs_src/custom_response/tutorial004.py!} ``` 👉 🖼, 🔢 `generate_html_response()` ⏪ 🏗 & 📨 `Response` ↩️ 🛬 🕸 `str`. @@ -145,7 +145,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🎚, ⚓️ 🔛 = & 🔁 = ✍ 🆎. ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ### `HTMLResponse` @@ -157,7 +157,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 ✊ ✍ ⚖️ 🔢 & 📨 ✅ ✍ 📨. ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial005.py!} +{!../../docs_src/custom_response/tutorial005.py!} ``` ### `JSONResponse` @@ -181,7 +181,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 /// ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001.py!} +{!../../docs_src/custom_response/tutorial001.py!} ``` /// tip @@ -197,7 +197,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👆 💪 📨 `RedirectResponse` 🔗: ```Python hl_lines="2 9" -{!../../../docs_src/custom_response/tutorial006.py!} +{!../../docs_src/custom_response/tutorial006.py!} ``` --- @@ -206,7 +206,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial006b.py!} +{!../../docs_src/custom_response/tutorial006b.py!} ``` 🚥 👆 👈, ⤴️ 👆 💪 📨 📛 🔗 ⚪️➡️ 👆 *➡ 🛠️* 🔢. @@ -218,7 +218,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👆 💪 ⚙️ `status_code` 🔢 🌀 ⏮️ `response_class` 🔢: ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial006c.py!} +{!../../docs_src/custom_response/tutorial006c.py!} ``` ### `StreamingResponse` @@ -226,7 +226,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 ✊ 🔁 🚂 ⚖️ 😐 🚂/🎻 & 🎏 📨 💪. ```Python hl_lines="2 14" -{!../../../docs_src/custom_response/tutorial007.py!} +{!../../docs_src/custom_response/tutorial007.py!} ``` #### ⚙️ `StreamingResponse` ⏮️ 📁-💖 🎚 @@ -238,7 +238,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👉 🔌 📚 🗃 🔗 ⏮️ ☁ 💾, 📹 🏭, & 🎏. ```{ .python .annotate hl_lines="2 10-12 14" } -{!../../../docs_src/custom_response/tutorial008.py!} +{!../../docs_src/custom_response/tutorial008.py!} ``` 1️⃣. 👉 🚂 🔢. ⚫️ "🚂 🔢" ↩️ ⚫️ 🔌 `yield` 📄 🔘. @@ -269,13 +269,13 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 📁 📨 🔜 🔌 ☑ `Content-Length`, `Last-Modified` & `ETag` 🎚. ```Python hl_lines="2 10" -{!../../../docs_src/custom_response/tutorial009.py!} +{!../../docs_src/custom_response/tutorial009.py!} ``` 👆 💪 ⚙️ `response_class` 🔢: ```Python hl_lines="2 8 10" -{!../../../docs_src/custom_response/tutorial009b.py!} +{!../../docs_src/custom_response/tutorial009b.py!} ``` 👉 💼, 👆 💪 📨 📁 ➡ 🔗 ⚪️➡️ 👆 *➡ 🛠️* 🔢. @@ -291,7 +291,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👆 💪 ✍ `CustomORJSONResponse`. 👑 👜 👆 ✔️ ✍ `Response.render(content)` 👩‍🔬 👈 📨 🎚 `bytes`: ```Python hl_lines="9-14 17" -{!../../../docs_src/custom_response/tutorial009c.py!} +{!../../docs_src/custom_response/tutorial009c.py!} ``` 🔜 ↩️ 🛬: @@ -319,7 +319,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🖼 🔛, **FastAPI** 🔜 ⚙️ `ORJSONResponse` 🔢, 🌐 *➡ 🛠️*, ↩️ `JSONResponse`. ```Python hl_lines="2 4" -{!../../../docs_src/custom_response/tutorial010.py!} +{!../../docs_src/custom_response/tutorial010.py!} ``` /// tip diff --git a/docs/em/docs/advanced/dataclasses.md b/docs/em/docs/advanced/dataclasses.md index 3f49ef07c..ab76e5083 100644 --- a/docs/em/docs/advanced/dataclasses.md +++ b/docs/em/docs/advanced/dataclasses.md @@ -5,7 +5,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda ✋️ FastAPI 🐕‍🦺 ⚙️ `dataclasses` 🎏 🌌: ```Python hl_lines="1 7-12 19-20" -{!../../../docs_src/dataclasses/tutorial001.py!} +{!../../docs_src/dataclasses/tutorial001.py!} ``` 👉 🐕‍🦺 👏 **Pydantic**, ⚫️ ✔️ 🔗 🐕‍🦺 `dataclasses`. @@ -35,7 +35,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda 👆 💪 ⚙️ `dataclasses` `response_model` 🔢: ```Python hl_lines="1 7-13 19" -{!../../../docs_src/dataclasses/tutorial002.py!} +{!../../docs_src/dataclasses/tutorial002.py!} ``` 🎻 🔜 🔁 🗜 Pydantic 🎻. @@ -53,7 +53,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda 👈 💼, 👆 💪 🎯 💱 🐩 `dataclasses` ⏮️ `pydantic.dataclasses`, ❔ 💧-♻: ```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } -{!../../../docs_src/dataclasses/tutorial003.py!} +{!../../docs_src/dataclasses/tutorial003.py!} ``` 1️⃣. 👥 🗄 `field` ⚪️➡️ 🐩 `dataclasses`. diff --git a/docs/em/docs/advanced/events.md b/docs/em/docs/advanced/events.md index 12c902c18..2eae2b366 100644 --- a/docs/em/docs/advanced/events.md +++ b/docs/em/docs/advanced/events.md @@ -31,7 +31,7 @@ 👥 ✍ 🔁 🔢 `lifespan()` ⏮️ `yield` 💖 👉: ```Python hl_lines="16 19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` 📥 👥 ⚖ 😥 *🕴* 🛠️ 🚚 🏷 🚮 (❌) 🏷 🔢 📖 ⏮️ 🎰 🏫 🏷 ⏭ `yield`. 👉 📟 🔜 🛠️ **⏭** 🈸 **▶️ ✊ 📨**, ⏮️ *🕴*. @@ -51,7 +51,7 @@ 🥇 👜 👀, 👈 👥 ⚖ 🔁 🔢 ⏮️ `yield`. 👉 📶 🎏 🔗 ⏮️ `yield`. ```Python hl_lines="14-19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` 🥇 🍕 🔢, ⏭ `yield`, 🔜 🛠️ **⏭** 🈸 ▶️. @@ -65,7 +65,7 @@ 👈 🗜 🔢 🔘 🕳 🤙 "**🔁 🔑 👨‍💼**". ```Python hl_lines="1 13" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` **🔑 👨‍💼** 🐍 🕳 👈 👆 💪 ⚙️ `with` 📄, 🖼, `open()` 💪 ⚙️ 🔑 👨‍💼: @@ -89,7 +89,7 @@ async with lifespan(app): `lifespan` 🔢 `FastAPI` 📱 ✊ **🔁 🔑 👨‍💼**, 👥 💪 🚶‍♀️ 👆 🆕 `lifespan` 🔁 🔑 👨‍💼 ⚫️. ```Python hl_lines="22" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` ## 🎛 🎉 (😢) @@ -113,7 +113,7 @@ async with lifespan(app): 🚮 🔢 👈 🔜 🏃 ⏭ 🈸 ▶️, 📣 ⚫️ ⏮️ 🎉 `"startup"`: ```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} +{!../../docs_src/events/tutorial001.py!} ``` 👉 💼, `startup` 🎉 🐕‍🦺 🔢 🔜 🔢 🏬 "💽" ( `dict`) ⏮️ 💲. @@ -127,7 +127,7 @@ async with lifespan(app): 🚮 🔢 👈 🔜 🏃 🕐❔ 🈸 🤫 🔽, 📣 ⚫️ ⏮️ 🎉 `"shutdown"`: ```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} +{!../../docs_src/events/tutorial002.py!} ``` 📥, `shutdown` 🎉 🐕‍🦺 🔢 🔜 ✍ ✍ ⏸ `"Application shutdown"` 📁 `log.txt`. diff --git a/docs/em/docs/advanced/generate-clients.md b/docs/em/docs/advanced/generate-clients.md index c8e044340..f09d75623 100644 --- a/docs/em/docs/advanced/generate-clients.md +++ b/docs/em/docs/advanced/generate-clients.md @@ -19,7 +19,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../../docs_src/generate_clients/tutorial001.py!} +{!> ../../docs_src/generate_clients/tutorial001.py!} ``` //// @@ -27,7 +27,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="7-9 12-13 16-17 21" -{!> ../../../docs_src/generate_clients/tutorial001_py39.py!} +{!> ../../docs_src/generate_clients/tutorial001_py39.py!} ``` //// @@ -139,7 +139,7 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="23 28 36" -{!> ../../../docs_src/generate_clients/tutorial002.py!} +{!> ../../docs_src/generate_clients/tutorial002.py!} ``` //// @@ -147,7 +147,7 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="21 26 34" -{!> ../../../docs_src/generate_clients/tutorial002_py39.py!} +{!> ../../docs_src/generate_clients/tutorial002_py39.py!} ``` //// @@ -200,7 +200,7 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="8-9 12" -{!> ../../../docs_src/generate_clients/tutorial003.py!} +{!> ../../docs_src/generate_clients/tutorial003.py!} ``` //// @@ -208,7 +208,7 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="6-7 10" -{!> ../../../docs_src/generate_clients/tutorial003_py39.py!} +{!> ../../docs_src/generate_clients/tutorial003_py39.py!} ``` //// @@ -234,7 +234,7 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** 👥 💪 ⏬ 🗄 🎻 📁 `openapi.json` & ⤴️ 👥 💪 **❎ 👈 🔡 🔖** ⏮️ ✍ 💖 👉: ```Python -{!../../../docs_src/generate_clients/tutorial004.py!} +{!../../docs_src/generate_clients/tutorial004.py!} ``` ⏮️ 👈, 🛠️ 🆔 🔜 📁 ⚪️➡️ 👜 💖 `items-get_items` `get_items`, 👈 🌌 👩‍💻 🚂 💪 🏗 🙅 👩‍🔬 📛. diff --git a/docs/em/docs/advanced/middleware.md b/docs/em/docs/advanced/middleware.md index e3cc389c6..23d2918d7 100644 --- a/docs/em/docs/advanced/middleware.md +++ b/docs/em/docs/advanced/middleware.md @@ -58,7 +58,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 🙆 📨 📨 `http` ⚖️ `ws` 🔜 ❎ 🔐 ⚖ ↩️. ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial001.py!} +{!../../docs_src/advanced_middleware/tutorial001.py!} ``` ## `TrustedHostMiddleware` @@ -66,7 +66,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 🛠️ 👈 🌐 📨 📨 ✔️ ☑ ⚒ `Host` 🎚, ✔ 💂‍♂ 🛡 🇺🇸🔍 🦠 🎚 👊. ```Python hl_lines="2 6-8" -{!../../../docs_src/advanced_middleware/tutorial002.py!} +{!../../docs_src/advanced_middleware/tutorial002.py!} ``` 📄 ❌ 🐕‍🦺: @@ -82,7 +82,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 🛠️ 🔜 🍵 👯‍♂️ 🐩 & 🎥 📨. ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial003.py!} +{!../../docs_src/advanced_middleware/tutorial003.py!} ``` 📄 ❌ 🐕‍🦺: diff --git a/docs/em/docs/advanced/openapi-callbacks.md b/docs/em/docs/advanced/openapi-callbacks.md index 00d54ebec..f7b5e7ed9 100644 --- a/docs/em/docs/advanced/openapi-callbacks.md +++ b/docs/em/docs/advanced/openapi-callbacks.md @@ -32,7 +32,7 @@ 👉 🍕 📶 😐, 🌅 📟 🎲 ⏪ 😰 👆: ```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` /// tip @@ -93,7 +93,7 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) 🥇 ✍ 🆕 `APIRouter` 👈 🔜 🔌 1️⃣ ⚖️ 🌅 ⏲. ```Python hl_lines="3 25" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` ### ✍ ⏲ *➡ 🛠️* @@ -106,7 +106,7 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) * & ⚫️ 💪 ✔️ 📄 📨 ⚫️ 🔜 📨, ✅ `response_model=InvoiceEventReceived`. ```Python hl_lines="16-18 21-22 28-32" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` 📤 2️⃣ 👑 🔺 ⚪️➡️ 😐 *➡ 🛠️*: @@ -176,7 +176,7 @@ https://www.external.org/events/invoices/2expen51ve 🔜 ⚙️ 🔢 `callbacks` *👆 🛠️ ➡ 🛠️ 👨‍🎨* 🚶‍♀️ 🔢 `.routes` (👈 🤙 `list` 🛣/*➡ 🛠️*) ⚪️➡️ 👈 ⏲ 📻: ```Python hl_lines="35" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` /// tip diff --git a/docs/em/docs/advanced/path-operation-advanced-configuration.md b/docs/em/docs/advanced/path-operation-advanced-configuration.md index b684df26f..805bfdf30 100644 --- a/docs/em/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/em/docs/advanced/path-operation-advanced-configuration.md @@ -13,7 +13,7 @@ 👆 🔜 ✔️ ⚒ 💭 👈 ⚫️ 😍 🔠 🛠️. ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} ``` ### ⚙️ *➡ 🛠️ 🔢* 📛 { @@ -23,7 +23,7 @@ 👆 🔜 ⚫️ ⏮️ ❎ 🌐 👆 *➡ 🛠️*. ```Python hl_lines="2 12-21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` /// tip @@ -45,7 +45,7 @@ 🚫 *➡ 🛠️* ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚙️ 🔢 `include_in_schema` & ⚒ ⚫️ `False`: ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} ``` ## 🏧 📛 ⚪️➡️ #️⃣ @@ -57,7 +57,7 @@ ⚫️ 🏆 🚫 🎦 🆙 🧾, ✋️ 🎏 🧰 (✅ 🐉) 🔜 💪 ⚙️ 🎂. ```Python hl_lines="19-29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} ``` ## 🌖 📨 @@ -101,7 +101,7 @@ 👉 `openapi_extra` 💪 👍, 🖼, 📣 [🗄 ↔](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions): ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial005.py!} ``` 🚥 👆 📂 🏧 🛠️ 🩺, 👆 ↔ 🔜 🎦 🆙 🔝 🎯 *➡ 🛠️*. @@ -150,7 +150,7 @@ 👆 💪 👈 ⏮️ `openapi_extra`: ```Python hl_lines="20-37 39-40" -{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial006.py!} ``` 👉 🖼, 👥 🚫 📣 🙆 Pydantic 🏷. 👐, 📨 💪 🚫 🎻 🎻, ⚫️ ✍ 🔗 `bytes`, & 🔢 `magic_data_reader()` 🔜 🈚 🎻 ⚫️ 🌌. @@ -166,7 +166,7 @@ 🖼, 👉 🈸 👥 🚫 ⚙️ FastAPI 🛠️ 🛠️ ⚗ 🎻 🔗 ⚪️➡️ Pydantic 🏷 🚫 🏧 🔬 🎻. 👐, 👥 📣 📨 🎚 🆎 📁, 🚫 🎻: ```Python hl_lines="17-22 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` 👐, 👐 👥 🚫 ⚙️ 🔢 🛠️ 🛠️, 👥 ⚙️ Pydantic 🏷 ❎ 🏗 🎻 🔗 💽 👈 👥 💚 📨 📁. @@ -176,7 +176,7 @@ & ⤴️ 👆 📟, 👥 🎻 👈 📁 🎚 🔗, & ⤴️ 👥 🔄 ⚙️ 🎏 Pydantic 🏷 ✔ 📁 🎚: ```Python hl_lines="26-33" -{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` /// tip diff --git a/docs/em/docs/advanced/response-change-status-code.md b/docs/em/docs/advanced/response-change-status-code.md index 156efcc16..7f2e8c157 100644 --- a/docs/em/docs/advanced/response-change-status-code.md +++ b/docs/em/docs/advanced/response-change-status-code.md @@ -21,7 +21,7 @@ & ⤴️ 👆 💪 ⚒ `status_code` 👈 *🔀* 📨 🎚. ```Python hl_lines="1 9 12" -{!../../../docs_src/response_change_status_code/tutorial001.py!} +{!../../docs_src/response_change_status_code/tutorial001.py!} ``` & ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️). diff --git a/docs/em/docs/advanced/response-cookies.md b/docs/em/docs/advanced/response-cookies.md index 717fb87ce..6b9e9a4d9 100644 --- a/docs/em/docs/advanced/response-cookies.md +++ b/docs/em/docs/advanced/response-cookies.md @@ -7,7 +7,7 @@ & ⤴️ 👆 💪 ⚒ 🍪 👈 *🔀* 📨 🎚. ```Python hl_lines="1 8-9" -{!../../../docs_src/response_cookies/tutorial002.py!} +{!../../docs_src/response_cookies/tutorial002.py!} ``` & ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️). @@ -27,7 +27,7 @@ ⤴️ ⚒ 🍪 ⚫️, & ⤴️ 📨 ⚫️: ```Python hl_lines="10-12" -{!../../../docs_src/response_cookies/tutorial001.py!} +{!../../docs_src/response_cookies/tutorial001.py!} ``` /// tip diff --git a/docs/em/docs/advanced/response-directly.md b/docs/em/docs/advanced/response-directly.md index 13ee081c2..dcffc56c6 100644 --- a/docs/em/docs/advanced/response-directly.md +++ b/docs/em/docs/advanced/response-directly.md @@ -35,7 +35,7 @@ 📚 💼, 👆 💪 ⚙️ `jsonable_encoder` 🗜 👆 📊 ⏭ 🚶‍♀️ ⚫️ 📨: ```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` /// note | "📡 ℹ" @@ -57,7 +57,7 @@ 👆 💪 🚮 👆 📂 🎚 🎻, 🚮 ⚫️ `Response`, & 📨 ⚫️: ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ## 🗒 diff --git a/docs/em/docs/advanced/response-headers.md b/docs/em/docs/advanced/response-headers.md index 27e1cdbd5..cbbbae237 100644 --- a/docs/em/docs/advanced/response-headers.md +++ b/docs/em/docs/advanced/response-headers.md @@ -7,7 +7,7 @@ & ⤴️ 👆 💪 ⚒ 🎚 👈 *🔀* 📨 🎚. ```Python hl_lines="1 7-8" -{!../../../docs_src/response_headers/tutorial002.py!} +{!../../docs_src/response_headers/tutorial002.py!} ``` & ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️). @@ -25,7 +25,7 @@ ✍ 📨 🔬 [📨 📨 🔗](response-directly.md){.internal-link target=_blank} & 🚶‍♀️ 🎚 🌖 🔢: ```Python hl_lines="10-12" -{!../../../docs_src/response_headers/tutorial001.py!} +{!../../docs_src/response_headers/tutorial001.py!} ``` /// note | "📡 ℹ" diff --git a/docs/em/docs/advanced/security/http-basic-auth.md b/docs/em/docs/advanced/security/http-basic-auth.md index 33470a726..e6fe3e32c 100644 --- a/docs/em/docs/advanced/security/http-basic-auth.md +++ b/docs/em/docs/advanced/security/http-basic-auth.md @@ -21,7 +21,7 @@ * ⚫️ 🔌 `username` & `password` 📨. ```Python hl_lines="2 6 10" -{!../../../docs_src/security/tutorial006.py!} +{!../../docs_src/security/tutorial006.py!} ``` 🕐❔ 👆 🔄 📂 📛 🥇 🕰 (⚖️ 🖊 "🛠️" 🔼 🩺) 🖥 🔜 💭 👆 👆 🆔 & 🔐: @@ -43,7 +43,7 @@ ⤴️ 👥 💪 ⚙️ `secrets.compare_digest()` 🚚 👈 `credentials.username` `"stanleyjobson"`, & 👈 `credentials.password` `"swordfish"`. ```Python hl_lines="1 11-21" -{!../../../docs_src/security/tutorial007.py!} +{!../../docs_src/security/tutorial007.py!} ``` 👉 🔜 🎏: @@ -109,5 +109,5 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": ⏮️ 🔍 👈 🎓 ❌, 📨 `HTTPException` ⏮️ 👔 📟 4️⃣0️⃣1️⃣ (🎏 📨 🕐❔ 🙅‍♂ 🎓 🚚) & 🚮 🎚 `WWW-Authenticate` ⚒ 🖥 🎦 💳 📋 🔄: ```Python hl_lines="23-27" -{!../../../docs_src/security/tutorial007.py!} +{!../../docs_src/security/tutorial007.py!} ``` diff --git a/docs/em/docs/advanced/security/oauth2-scopes.md b/docs/em/docs/advanced/security/oauth2-scopes.md index 73b2ec540..661be034e 100644 --- a/docs/em/docs/advanced/security/oauth2-scopes.md +++ b/docs/em/docs/advanced/security/oauth2-scopes.md @@ -63,7 +63,7 @@ Oauth2️⃣ 👫 🎻. 🥇, ➡️ 🔜 👀 🍕 👈 🔀 ⚪️➡️ 🖼 👑 **🔰 - 👩‍💻 🦮** [Oauth2️⃣ ⏮️ 🔐 (& 🔁), 📨 ⏮️ 🥙 🤝](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. 🔜 ⚙️ Oauth2️⃣ ↔: ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` 🔜 ➡️ 📄 👈 🔀 🔁 🔁. @@ -75,7 +75,7 @@ Oauth2️⃣ 👫 🎻. `scopes` 🔢 📨 `dict` ⏮️ 🔠 ↔ 🔑 & 📛 💲: ```Python hl_lines="62-65" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ↩️ 👥 🔜 📣 📚 ↔, 👫 🔜 🎦 🆙 🛠️ 🩺 🕐❔ 👆 🕹-/✔. @@ -103,7 +103,7 @@ Oauth2️⃣ 👫 🎻. /// ```Python hl_lines="155" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 📣 ↔ *➡ 🛠️* & 🔗 @@ -131,7 +131,7 @@ Oauth2️⃣ 👫 🎻. /// ```Python hl_lines="4 139 168" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` /// info | "📡 ℹ" @@ -159,7 +159,7 @@ Oauth2️⃣ 👫 🎻. 👉 `SecurityScopes` 🎓 🎏 `Request` (`Request` ⚙️ 🤚 📨 🎚 🔗). ```Python hl_lines="8 105" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## ⚙️ `scopes` @@ -175,7 +175,7 @@ Oauth2️⃣ 👫 🎻. 👉 ⚠, 👥 🔌 ↔ 🚚 (🚥 🙆) 🎻 👽 🚀 (⚙️ `scope_str`). 👥 🚮 👈 🎻 ⚗ ↔ `WWW-Authenticate` 🎚 (👉 🍕 🔌). ```Python hl_lines="105 107-115" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## ✔ `username` & 💽 💠 @@ -193,7 +193,7 @@ Oauth2️⃣ 👫 🎻. 👥 ✔ 👈 👥 ✔️ 👩‍💻 ⏮️ 👈 🆔, & 🚥 🚫, 👥 🤚 👈 🎏 ⚠ 👥 ✍ ⏭. ```Python hl_lines="46 116-127" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## ✔ `scopes` @@ -203,7 +203,7 @@ Oauth2️⃣ 👫 🎻. 👉, 👥 ⚙️ `security_scopes.scopes`, 👈 🔌 `list` ⏮️ 🌐 👫 ↔ `str`. ```Python hl_lines="128-134" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 🔗 🌲 & ↔ diff --git a/docs/em/docs/advanced/settings.md b/docs/em/docs/advanced/settings.md index e84941b57..59fb71d73 100644 --- a/docs/em/docs/advanced/settings.md +++ b/docs/em/docs/advanced/settings.md @@ -149,7 +149,7 @@ Hello World from Python 👆 💪 ⚙️ 🌐 🎏 🔬 ⚒ & 🧰 👆 ⚙️ Pydantic 🏷, 💖 🎏 📊 🆎 & 🌖 🔬 ⏮️ `Field()`. ```Python hl_lines="2 5-8 11" -{!../../../docs_src/settings/tutorial001.py!} +{!../../docs_src/settings/tutorial001.py!} ``` /// tip @@ -167,7 +167,7 @@ Hello World from Python ⤴️ 👆 💪 ⚙️ 🆕 `settings` 🎚 👆 🈸: ```Python hl_lines="18-20" -{!../../../docs_src/settings/tutorial001.py!} +{!../../docs_src/settings/tutorial001.py!} ``` ### 🏃 💽 @@ -203,13 +203,13 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 🖼, 👆 💪 ✔️ 📁 `config.py` ⏮️: ```Python -{!../../../docs_src/settings/app01/config.py!} +{!../../docs_src/settings/app01/config.py!} ``` & ⤴️ ⚙️ ⚫️ 📁 `main.py`: ```Python hl_lines="3 11-13" -{!../../../docs_src/settings/app01/main.py!} +{!../../docs_src/settings/app01/main.py!} ``` /// tip @@ -229,7 +229,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 👟 ⚪️➡️ ⏮️ 🖼, 👆 `config.py` 📁 💪 👀 💖: ```Python hl_lines="10" -{!../../../docs_src/settings/app02/config.py!} +{!../../docs_src/settings/app02/config.py!} ``` 👀 👈 🔜 👥 🚫 ✍ 🔢 👐 `settings = Settings()`. @@ -239,7 +239,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 🔜 👥 ✍ 🔗 👈 📨 🆕 `config.Settings()`. ```Python hl_lines="5 11-12" -{!../../../docs_src/settings/app02/main.py!} +{!../../docs_src/settings/app02/main.py!} ``` /// tip @@ -253,7 +253,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app & ⤴️ 👥 💪 🚚 ⚫️ ⚪️➡️ *➡ 🛠️ 🔢* 🔗 & ⚙️ ⚫️ 🙆 👥 💪 ⚫️. ```Python hl_lines="16 18-20" -{!../../../docs_src/settings/app02/main.py!} +{!../../docs_src/settings/app02/main.py!} ``` ### ⚒ & 🔬 @@ -261,7 +261,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app ⤴️ ⚫️ 🔜 📶 ⏩ 🚚 🎏 ⚒ 🎚 ⏮️ 🔬 🏗 🔗 🔐 `get_settings`: ```Python hl_lines="9-10 13 21" -{!../../../docs_src/settings/app02/test_main.py!} +{!../../docs_src/settings/app02/test_main.py!} ``` 🔗 🔐 👥 ⚒ 🆕 💲 `admin_email` 🕐❔ 🏗 🆕 `Settings` 🎚, & ⤴️ 👥 📨 👈 🆕 🎚. @@ -304,7 +304,7 @@ APP_NAME="ChimichangApp" & ⤴️ ℹ 👆 `config.py` ⏮️: ```Python hl_lines="9-10" -{!../../../docs_src/settings/app03/config.py!} +{!../../docs_src/settings/app03/config.py!} ``` 📥 👥 ✍ 🎓 `Config` 🔘 👆 Pydantic `Settings` 🎓, & ⚒ `env_file` 📁 ⏮️ 🇨🇻 📁 👥 💚 ⚙️. @@ -339,7 +339,7 @@ def get_settings(): ✋️ 👥 ⚙️ `@lru_cache` 👨‍🎨 🔛 🔝, `Settings` 🎚 🔜 ✍ 🕴 🕐, 🥇 🕰 ⚫️ 🤙. 👶 👶 ```Python hl_lines="1 10" -{!../../../docs_src/settings/app03/main.py!} +{!../../docs_src/settings/app03/main.py!} ``` ⤴️ 🙆 🏁 🤙 `get_settings()` 🔗 ⏭ 📨, ↩️ 🛠️ 🔗 📟 `get_settings()` & 🏗 🆕 `Settings` 🎚, ⚫️ 🔜 📨 🎏 🎚 👈 📨 🔛 🥇 🤙, 🔄 & 🔄. diff --git a/docs/em/docs/advanced/sub-applications.md b/docs/em/docs/advanced/sub-applications.md index 1e0931f95..e19f3f234 100644 --- a/docs/em/docs/advanced/sub-applications.md +++ b/docs/em/docs/advanced/sub-applications.md @@ -11,7 +11,7 @@ 🥇, ✍ 👑, 🔝-🎚, **FastAPI** 🈸, & 🚮 *➡ 🛠️*: ```Python hl_lines="3 6-8" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### 🎧-🈸 @@ -21,7 +21,7 @@ 👉 🎧-🈸 ➕1️⃣ 🐩 FastAPI 🈸, ✋️ 👉 1️⃣ 👈 🔜 "🗻": ```Python hl_lines="11 14-16" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### 🗻 🎧-🈸 @@ -31,7 +31,7 @@ 👉 💼, ⚫️ 🔜 📌 ➡ `/subapi`: ```Python hl_lines="11 19" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### ✅ 🏧 🛠️ 🩺 diff --git a/docs/em/docs/advanced/templates.md b/docs/em/docs/advanced/templates.md index c45ff47a1..66c7484a6 100644 --- a/docs/em/docs/advanced/templates.md +++ b/docs/em/docs/advanced/templates.md @@ -28,7 +28,7 @@ $ pip install jinja2 * ⚙️ `templates` 👆 ✍ ✍ & 📨 `TemplateResponse`, 🚶‍♀️ `request` 1️⃣ 🔑-💲 👫 Jinja2️⃣ "🔑". ```Python hl_lines="4 11 15-18" -{!../../../docs_src/templates/tutorial001.py!} +{!../../docs_src/templates/tutorial001.py!} ``` /// note @@ -56,7 +56,7 @@ $ pip install jinja2 ⤴️ 👆 💪 ✍ 📄 `templates/item.html` ⏮️: ```jinja hl_lines="7" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` ⚫️ 🔜 🎦 `id` ✊ ⚪️➡️ "🔑" `dict` 👆 🚶‍♀️: @@ -70,13 +70,13 @@ $ pip install jinja2 & 👆 💪 ⚙️ `url_for()` 🔘 📄, & ⚙️ ⚫️, 🖼, ⏮️ `StaticFiles` 👆 📌. ```jinja hl_lines="4" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` 👉 🖼, ⚫️ 🔜 🔗 🎚 📁 `static/styles.css` ⏮️: ```CSS hl_lines="4" -{!../../../docs_src/templates/static/styles.css!} +{!../../docs_src/templates/static/styles.css!} ``` & ↩️ 👆 ⚙️ `StaticFiles`, 👈 🎚 📁 🔜 🍦 🔁 👆 **FastAPI** 🈸 📛 `/static/styles.css`. diff --git a/docs/em/docs/advanced/testing-database.md b/docs/em/docs/advanced/testing-database.md index 825d545a9..71b29f9b7 100644 --- a/docs/em/docs/advanced/testing-database.md +++ b/docs/em/docs/advanced/testing-database.md @@ -49,7 +49,7 @@ ✋️ 🎂 🎉 📟 🌅 ⚖️ 🌘 🎏, 👥 📁 ⚫️. ```Python hl_lines="8-13" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` /// tip @@ -73,7 +73,7 @@ Base.metadata.create_all(bind=engine) 👥 🚮 👈 ⏸ 📥, ⏮️ 🆕 📁. ```Python hl_lines="16" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` ## 🔗 🔐 @@ -81,7 +81,7 @@ Base.metadata.create_all(bind=engine) 🔜 👥 ✍ 🔗 🔐 & 🚮 ⚫️ 🔐 👆 📱. ```Python hl_lines="19-24 27" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` /// tip @@ -95,7 +95,7 @@ Base.metadata.create_all(bind=engine) ⤴️ 👥 💪 💯 📱 🛎. ```Python hl_lines="32-47" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` & 🌐 🛠️ 👥 ⚒ 💽 ⏮️ 💯 🔜 `test.db` 💽 ↩️ 👑 `sql_app.db`. diff --git a/docs/em/docs/advanced/testing-dependencies.md b/docs/em/docs/advanced/testing-dependencies.md index 8bcffcc29..027767df1 100644 --- a/docs/em/docs/advanced/testing-dependencies.md +++ b/docs/em/docs/advanced/testing-dependencies.md @@ -29,7 +29,7 @@ & ⤴️ **FastAPI** 🔜 🤙 👈 🔐 ↩️ ⏮️ 🔗. ```Python hl_lines="28-29 32" -{!../../../docs_src/dependency_testing/tutorial001.py!} +{!../../docs_src/dependency_testing/tutorial001.py!} ``` /// tip diff --git a/docs/em/docs/advanced/testing-events.md b/docs/em/docs/advanced/testing-events.md index d64436eb9..071d49c21 100644 --- a/docs/em/docs/advanced/testing-events.md +++ b/docs/em/docs/advanced/testing-events.md @@ -3,5 +3,5 @@ 🕐❔ 👆 💪 👆 🎉 🐕‍🦺 (`startup` & `shutdown`) 🏃 👆 💯, 👆 💪 ⚙️ `TestClient` ⏮️ `with` 📄: ```Python hl_lines="9-12 20-24" -{!../../../docs_src/app_testing/tutorial003.py!} +{!../../docs_src/app_testing/tutorial003.py!} ``` diff --git a/docs/em/docs/advanced/testing-websockets.md b/docs/em/docs/advanced/testing-websockets.md index 5fb1e9c34..62939c343 100644 --- a/docs/em/docs/advanced/testing-websockets.md +++ b/docs/em/docs/advanced/testing-websockets.md @@ -5,7 +5,7 @@ 👉, 👆 ⚙️ `TestClient` `with` 📄, 🔗*️⃣: ```Python hl_lines="27-31" -{!../../../docs_src/app_testing/tutorial002.py!} +{!../../docs_src/app_testing/tutorial002.py!} ``` /// note diff --git a/docs/em/docs/advanced/using-request-directly.md b/docs/em/docs/advanced/using-request-directly.md index edc951d96..ae212364f 100644 --- a/docs/em/docs/advanced/using-request-directly.md +++ b/docs/em/docs/advanced/using-request-directly.md @@ -30,7 +30,7 @@ 👈 👆 💪 🔐 📨 🔗. ```Python hl_lines="1 7-8" -{!../../../docs_src/using_request_directly/tutorial001.py!} +{!../../docs_src/using_request_directly/tutorial001.py!} ``` 📣 *➡ 🛠️ 🔢* 🔢 ⏮️ 🆎 ➖ `Request` **FastAPI** 🔜 💭 🚶‍♀️ `Request` 👈 🔢. diff --git a/docs/em/docs/advanced/websockets.md b/docs/em/docs/advanced/websockets.md index 30dc3043e..7957eba1f 100644 --- a/docs/em/docs/advanced/websockets.md +++ b/docs/em/docs/advanced/websockets.md @@ -39,7 +39,7 @@ $ pip install websockets ✋️ ⚫️ 🙅 🌌 🎯 🔛 💽-🚄 *️⃣ & ✔️ 👷 🖼: ```Python hl_lines="2 6-38 41-43" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` ## ✍ `websocket` @@ -47,7 +47,7 @@ $ pip install websockets 👆 **FastAPI** 🈸, ✍ `websocket`: ```Python hl_lines="1 46-47" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` /// note | "📡 ℹ" @@ -63,7 +63,7 @@ $ pip install websockets 👆 *️⃣ 🛣 👆 💪 `await` 📧 & 📨 📧. ```Python hl_lines="48-52" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` 👆 💪 📨 & 📨 💱, ✍, & 🎻 💽. @@ -116,7 +116,7 @@ $ uvicorn main:app --reload 👫 👷 🎏 🌌 🎏 FastAPI 🔗/*➡ 🛠️*: ```Python hl_lines="66-77 76-91" -{!../../../docs_src/websockets/tutorial002.py!} +{!../../docs_src/websockets/tutorial002.py!} ``` /// info @@ -163,7 +163,7 @@ $ uvicorn main:app --reload 🕐❔ *️⃣ 🔗 📪, `await websocket.receive_text()` 🔜 🤚 `WebSocketDisconnect` ⚠, ❔ 👆 💪 ⤴️ ✊ & 🍵 💖 👉 🖼. ```Python hl_lines="81-83" -{!../../../docs_src/websockets/tutorial003.py!} +{!../../docs_src/websockets/tutorial003.py!} ``` 🔄 ⚫️ 👅: diff --git a/docs/em/docs/advanced/wsgi.md b/docs/em/docs/advanced/wsgi.md index 6a4ed073c..8c0008c74 100644 --- a/docs/em/docs/advanced/wsgi.md +++ b/docs/em/docs/advanced/wsgi.md @@ -13,7 +13,7 @@ & ⤴️ 🗻 👈 🔽 ➡. ```Python hl_lines="2-3 22" -{!../../../docs_src/wsgi/tutorial001.py!} +{!../../docs_src/wsgi/tutorial001.py!} ``` ## ✅ ⚫️ diff --git a/docs/em/docs/how-to/conditional-openapi.md b/docs/em/docs/how-to/conditional-openapi.md index a17ba4eec..a5932933a 100644 --- a/docs/em/docs/how-to/conditional-openapi.md +++ b/docs/em/docs/how-to/conditional-openapi.md @@ -30,7 +30,7 @@ 🖼: ```Python hl_lines="6 11" -{!../../../docs_src/conditional_openapi/tutorial001.py!} +{!../../docs_src/conditional_openapi/tutorial001.py!} ``` 📥 👥 📣 ⚒ `openapi_url` ⏮️ 🎏 🔢 `"/openapi.json"`. diff --git a/docs/em/docs/how-to/custom-request-and-route.md b/docs/em/docs/how-to/custom-request-and-route.md index 1f66c6eda..0425e6267 100644 --- a/docs/em/docs/how-to/custom-request-and-route.md +++ b/docs/em/docs/how-to/custom-request-and-route.md @@ -43,7 +43,7 @@ 👈 🌌, 🎏 🛣 🎓 💪 🍵 🗜 🗜 ⚖️ 🗜 📨. ```Python hl_lines="8-15" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} +{!../../docs_src/custom_request_and_route/tutorial001.py!} ``` ### ✍ 🛃 `GzipRoute` 🎓 @@ -57,7 +57,7 @@ 📥 👥 ⚙️ ⚫️ ✍ `GzipRequest` ⚪️➡️ ⏮️ 📨. ```Python hl_lines="18-26" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} +{!../../docs_src/custom_request_and_route/tutorial001.py!} ``` /// note | "📡 ℹ" @@ -97,13 +97,13 @@ 🌐 👥 💪 🍵 📨 🔘 `try`/`except` 🍫: ```Python hl_lines="13 15" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} +{!../../docs_src/custom_request_and_route/tutorial002.py!} ``` 🚥 ⚠ 📉, `Request` 👐 🔜 ↔, 👥 💪 ✍ & ⚒ ⚙️ 📨 💪 🕐❔ 🚚 ❌: ```Python hl_lines="16-18" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} +{!../../docs_src/custom_request_and_route/tutorial002.py!} ``` ## 🛃 `APIRoute` 🎓 📻 @@ -111,11 +111,11 @@ 👆 💪 ⚒ `route_class` 🔢 `APIRouter`: ```Python hl_lines="26" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} +{!../../docs_src/custom_request_and_route/tutorial003.py!} ``` 👉 🖼, *➡ 🛠️* 🔽 `router` 🔜 ⚙️ 🛃 `TimedRoute` 🎓, & 🔜 ✔️ ➕ `X-Response-Time` 🎚 📨 ⏮️ 🕰 ⚫️ ✊ 🏗 📨: ```Python hl_lines="13-20" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} +{!../../docs_src/custom_request_and_route/tutorial003.py!} ``` diff --git a/docs/em/docs/how-to/extending-openapi.md b/docs/em/docs/how-to/extending-openapi.md index dc9adf80e..698c78ec1 100644 --- a/docs/em/docs/how-to/extending-openapi.md +++ b/docs/em/docs/how-to/extending-openapi.md @@ -47,7 +47,7 @@ 🥇, ✍ 🌐 👆 **FastAPI** 🈸 🛎: ```Python hl_lines="1 4 7-9" -{!../../../docs_src/extending_openapi/tutorial001.py!} +{!../../docs_src/extending_openapi/tutorial001.py!} ``` ### 🏗 🗄 🔗 @@ -55,7 +55,7 @@ ⤴️, ⚙️ 🎏 🚙 🔢 🏗 🗄 🔗, 🔘 `custom_openapi()` 🔢: ```Python hl_lines="2 15-20" -{!../../../docs_src/extending_openapi/tutorial001.py!} +{!../../docs_src/extending_openapi/tutorial001.py!} ``` ### 🔀 🗄 🔗 @@ -63,7 +63,7 @@ 🔜 👆 💪 🚮 📄 ↔, ❎ 🛃 `x-logo` `info` "🎚" 🗄 🔗: ```Python hl_lines="21-23" -{!../../../docs_src/extending_openapi/tutorial001.py!} +{!../../docs_src/extending_openapi/tutorial001.py!} ``` ### 💾 🗄 🔗 @@ -75,7 +75,7 @@ ⚫️ 🔜 🏗 🕴 🕐, & ⤴️ 🎏 💾 🔗 🔜 ⚙️ ⏭ 📨. ```Python hl_lines="13-14 24-25" -{!../../../docs_src/extending_openapi/tutorial001.py!} +{!../../docs_src/extending_openapi/tutorial001.py!} ``` ### 🔐 👩‍🔬 @@ -83,7 +83,7 @@ 🔜 👆 💪 ❎ `.openapi()` 👩‍🔬 ⏮️ 👆 🆕 🔢. ```Python hl_lines="28" -{!../../../docs_src/extending_openapi/tutorial001.py!} +{!../../docs_src/extending_openapi/tutorial001.py!} ``` ### ✅ ⚫️ diff --git a/docs/em/docs/how-to/graphql.md b/docs/em/docs/how-to/graphql.md index b8610b767..5d0d95567 100644 --- a/docs/em/docs/how-to/graphql.md +++ b/docs/em/docs/how-to/graphql.md @@ -36,7 +36,7 @@ 📥 🤪 🎮 ❔ 👆 💪 🛠️ 🍓 ⏮️ FastAPI: ```Python hl_lines="3 22 25-26" -{!../../../docs_src/graphql/tutorial001.py!} +{!../../docs_src/graphql/tutorial001.py!} ``` 👆 💪 💡 🌅 🔃 🍓 🍓 🧾. diff --git a/docs/em/docs/how-to/sql-databases-peewee.md b/docs/em/docs/how-to/sql-databases-peewee.md index 88b827c24..d25b77894 100644 --- a/docs/em/docs/how-to/sql-databases-peewee.md +++ b/docs/em/docs/how-to/sql-databases-peewee.md @@ -71,7 +71,7 @@ ➡️ 🥇 ✅ 🌐 😐 🏒 📟, ✍ 🏒 💽: ```Python hl_lines="3 5 22" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} +{!../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` /// tip @@ -131,7 +131,7 @@ connect_args={"check_same_thread": False} 👥 🔜 ✍ `PeeweeConnectionState`: ```Python hl_lines="10-19" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} +{!../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` 👉 🎓 😖 ⚪️➡️ 🎁 🔗 🎓 ⚙️ 🏒. @@ -155,7 +155,7 @@ connect_args={"check_same_thread": False} 🔜, 📁 `._state` 🔗 🔢 🏒 💽 `db` 🎚 ⚙️ 🆕 `PeeweeConnectionState`: ```Python hl_lines="24" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} +{!../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` /// tip @@ -191,7 +191,7 @@ connect_args={"check_same_thread": False} 🗄 `db` ⚪️➡️ `database` (📁 `database.py` ⚪️➡️ 🔛) & ⚙️ ⚫️ 📥. ```Python hl_lines="3 6-12 15-21" -{!../../../docs_src/sql_databases_peewee/sql_app/models.py!} +{!../../docs_src/sql_databases_peewee/sql_app/models.py!} ``` /// tip @@ -225,7 +225,7 @@ connect_args={"check_same_thread": False} ✍ 🌐 🎏 Pydantic 🏷 🇸🇲 🔰: ```Python hl_lines="16-18 21-22 25-30 34-35 38-39 42-48" -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} +{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} ``` /// tip @@ -253,7 +253,7 @@ connect_args={"check_same_thread": False} 👥 🔜 ✍ 🛃 `PeeweeGetterDict` 🎓 & ⚙️ ⚫️ 🌐 🎏 Pydantic *🏷* / 🔗 👈 ⚙️ `orm_mode`: ```Python hl_lines="3 8-13 31 49" -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} +{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} ``` 📥 👥 ✅ 🚥 🔢 👈 ➖ 🔐 (✅ `.items` `some_user.items`) 👐 `peewee.ModelSelect`. @@ -277,7 +277,7 @@ connect_args={"check_same_thread": False} ✍ 🌐 🎏 💩 🇨🇻 🇸🇲 🔰, 🌐 📟 📶 🎏: ```Python hl_lines="1 4-5 8-9 12-13 16-20 23-24 27-30" -{!../../../docs_src/sql_databases_peewee/sql_app/crud.py!} +{!../../docs_src/sql_databases_peewee/sql_app/crud.py!} ``` 📤 🔺 ⏮️ 📟 🇸🇲 🔰. @@ -301,7 +301,7 @@ list(models.User.select()) 📶 🙃 🌌 ✍ 💽 🏓: ```Python hl_lines="9-11" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ### ✍ 🔗 @@ -309,7 +309,7 @@ list(models.User.select()) ✍ 🔗 👈 🔜 🔗 💽 ▶️️ ▶️ 📨 & 🔌 ⚫️ 🔚: ```Python hl_lines="23-29" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` 📥 👥 ✔️ 🛁 `yield` ↩️ 👥 🤙 🚫 ⚙️ 💽 🎚 🔗. @@ -323,7 +323,7 @@ list(models.User.select()) ✋️ 👥 🚫 ⚙️ 💲 👐 👉 🔗 (⚫️ 🤙 🚫 🤝 🙆 💲, ⚫️ ✔️ 🛁 `yield`). , 👥 🚫 🚮 ⚫️ *➡ 🛠️ 🔢* ✋️ *➡ 🛠️ 👨‍🎨* `dependencies` 🔢: ```Python hl_lines="32 40 47 59 65 72" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ### 🔑 🔢 🎧-🔗 @@ -333,7 +333,7 @@ list(models.User.select()) 👈, 👥 💪 ✍ ➕1️⃣ `async` 🔗 `reset_db_state()` 👈 ⚙️ 🎧-🔗 `get_db()`. ⚫️ 🔜 ⚒ 💲 🔑 🔢 (⏮️ 🔢 `dict`) 👈 🔜 ⚙️ 💽 🇵🇸 🎂 📨. & ⤴️ 🔗 `get_db()` 🔜 🏪 ⚫️ 💽 🇵🇸 (🔗, 💵, ♒️). ```Python hl_lines="18-20" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` **⏭ 📨**, 👥 🔜 ⏲ 👈 🔑 🔢 🔄 `async` 🔗 `reset_db_state()` & ⤴️ ✍ 🆕 🔗 `get_db()` 🔗, 👈 🆕 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 (🔗, 💵, ♒️). @@ -365,7 +365,7 @@ async def reset_db_state(): 🔜, 😒, 📥 🐩 **FastAPI** *➡ 🛠️* 📟. ```Python hl_lines="32-37 40-43 46-53 56-62 65-68 71-79" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ### 🔃 `def` 🆚 `async def` @@ -482,31 +482,31 @@ async def reset_db_state(): * `sql_app/database.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} +{!../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` * `sql_app/models.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/models.py!} +{!../../docs_src/sql_databases_peewee/sql_app/models.py!} ``` * `sql_app/schemas.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} +{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} ``` * `sql_app/crud.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/crud.py!} +{!../../docs_src/sql_databases_peewee/sql_app/crud.py!} ``` * `sql_app/main.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ## 📡 ℹ diff --git a/docs/em/docs/python-types.md b/docs/em/docs/python-types.md index 202c90f94..d2af23bb9 100644 --- a/docs/em/docs/python-types.md +++ b/docs/em/docs/python-types.md @@ -23,7 +23,7 @@ ➡️ ▶️ ⏮️ 🙅 🖼: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` 🤙 👉 📋 🔢: @@ -39,7 +39,7 @@ John Doe * 🔢 👫 ⏮️ 🚀 🖕. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### ✍ ⚫️ @@ -83,7 +83,7 @@ John Doe 👈 "🆎 🔑": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` 👈 🚫 🎏 📣 🔢 💲 💖 🔜 ⏮️: @@ -113,7 +113,7 @@ John Doe ✅ 👉 🔢, ⚫️ ⏪ ✔️ 🆎 🔑: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` ↩️ 👨‍🎨 💭 🆎 🔢, 👆 🚫 🕴 🤚 🛠️, 👆 🤚 ❌ ✅: @@ -123,7 +123,7 @@ John Doe 🔜 👆 💭 👈 👆 ✔️ 🔧 ⚫️, 🗜 `age` 🎻 ⏮️ `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## 📣 🆎 @@ -144,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### 💊 🆎 ⏮️ 🆎 🔢 @@ -172,7 +172,7 @@ John Doe ⚪️➡️ `typing`, 🗄 `List` (⏮️ 🔠 `L`): ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` 📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕. @@ -182,7 +182,7 @@ John Doe 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: ```Python hl_lines="4" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` //// @@ -196,7 +196,7 @@ John Doe 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006_py39.py!} +{!> ../../docs_src/python_types/tutorial006_py39.py!} ``` //// @@ -234,7 +234,7 @@ John Doe //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial007.py!} +{!> ../../docs_src/python_types/tutorial007.py!} ``` //// @@ -242,7 +242,7 @@ John Doe //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial007_py39.py!} +{!> ../../docs_src/python_types/tutorial007_py39.py!} ``` //// @@ -263,7 +263,7 @@ John Doe //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008.py!} +{!> ../../docs_src/python_types/tutorial008.py!} ``` //// @@ -271,7 +271,7 @@ John Doe //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008_py39.py!} +{!> ../../docs_src/python_types/tutorial008_py39.py!} ``` //// @@ -293,7 +293,7 @@ John Doe //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008b.py!} +{!> ../../docs_src/python_types/tutorial008b.py!} ``` //// @@ -301,7 +301,7 @@ John Doe //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +{!> ../../docs_src/python_types/tutorial008b_py310.py!} ``` //// @@ -315,7 +315,7 @@ John Doe 🐍 3️⃣.6️⃣ & 🔛 (✅ 🐍 3️⃣.1️⃣0️⃣) 👆 💪 📣 ⚫️ 🏭 & ⚙️ `Optional` ⚪️➡️ `typing` 🕹. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` ⚙️ `Optional[str]` ↩️ `str` 🔜 ➡️ 👨‍🎨 ℹ 👆 🔍 ❌ 🌐❔ 👆 💪 🤔 👈 💲 🕧 `str`, 🕐❔ ⚫️ 💪 🤙 `None` 💁‍♂️. @@ -327,7 +327,7 @@ John Doe //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009.py!} +{!> ../../docs_src/python_types/tutorial009.py!} ``` //// @@ -335,7 +335,7 @@ John Doe //// tab | 🐍 3️⃣.6️⃣ & 🔛 - 🎛 ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009b.py!} +{!> ../../docs_src/python_types/tutorial009b.py!} ``` //// @@ -343,7 +343,7 @@ John Doe //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial009_py310.py!} +{!> ../../docs_src/python_types/tutorial009_py310.py!} ``` //// @@ -364,7 +364,7 @@ John Doe 🖼, ➡️ ✊ 👉 🔢: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c.py!} +{!../../docs_src/python_types/tutorial009c.py!} ``` 🔢 `name` 🔬 `Optional[str]`, ✋️ ⚫️ **🚫 📦**, 👆 🚫🔜 🤙 🔢 🍵 🔢: @@ -382,7 +382,7 @@ say_hi(name=None) # This works, None is valid 🎉 👍 📰, 🕐 👆 🔛 🐍 3️⃣.1️⃣0️⃣ 👆 🏆 🚫 ✔️ 😟 🔃 👈, 👆 🔜 💪 🎯 ⚙️ `|` 🔬 🇪🇺 🆎: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c_py310.py!} +{!../../docs_src/python_types/tutorial009c_py310.py!} ``` & ⤴️ 👆 🏆 🚫 ✔️ 😟 🔃 📛 💖 `Optional` & `Union`. 👶 @@ -446,13 +446,13 @@ say_hi(name=None) # This works, None is valid 🎉 ➡️ 💬 👆 ✔️ 🎓 `Person`, ⏮️ 📛: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` ⤴️ 👆 💪 📣 🔢 🆎 `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` & ⤴️, 🔄, 👆 🤚 🌐 👨‍🎨 🐕‍🦺: @@ -476,7 +476,7 @@ say_hi(name=None) # This works, None is valid 🎉 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python -{!> ../../../docs_src/python_types/tutorial011.py!} +{!> ../../docs_src/python_types/tutorial011.py!} ``` //// @@ -484,7 +484,7 @@ say_hi(name=None) # This works, None is valid 🎉 //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python -{!> ../../../docs_src/python_types/tutorial011_py39.py!} +{!> ../../docs_src/python_types/tutorial011_py39.py!} ``` //// @@ -492,7 +492,7 @@ say_hi(name=None) # This works, None is valid 🎉 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python -{!> ../../../docs_src/python_types/tutorial011_py310.py!} +{!> ../../docs_src/python_types/tutorial011_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/background-tasks.md b/docs/em/docs/tutorial/background-tasks.md index 1d17a0e4e..0f4585ebe 100644 --- a/docs/em/docs/tutorial/background-tasks.md +++ b/docs/em/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ 🥇, 🗄 `BackgroundTasks` & 🔬 🔢 👆 *➡ 🛠️ 🔢* ⏮️ 🆎 📄 `BackgroundTasks`: ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** 🔜 ✍ 🎚 🆎 `BackgroundTasks` 👆 & 🚶‍♀️ ⚫️ 👈 🔢. @@ -34,7 +34,7 @@ & ✍ 🛠️ 🚫 ⚙️ `async` & `await`, 👥 🔬 🔢 ⏮️ 😐 `def`: ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## 🚮 🖥 📋 @@ -42,7 +42,7 @@ 🔘 👆 *➡ 🛠️ 🔢*, 🚶‍♀️ 👆 📋 🔢 *🖥 📋* 🎚 ⏮️ 👩‍🔬 `.add_task()`: ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` 📨 ❌: @@ -60,7 +60,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002.py!} +{!> ../../docs_src/background_tasks/tutorial002.py!} ``` //// @@ -68,7 +68,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="11 13 20 23" -{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +{!> ../../docs_src/background_tasks/tutorial002_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/bigger-applications.md b/docs/em/docs/tutorial/bigger-applications.md index 693a75d28..074ab302c 100644 --- a/docs/em/docs/tutorial/bigger-applications.md +++ b/docs/em/docs/tutorial/bigger-applications.md @@ -86,7 +86,7 @@ from app.routers import items 👆 🗄 ⚫️ & ✍ "👐" 🎏 🌌 👆 🔜 ⏮️ 🎓 `FastAPI`: ```Python hl_lines="1 3" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` ### *➡ 🛠️* ⏮️ `APIRouter` @@ -96,7 +96,7 @@ from app.routers import items ⚙️ ⚫️ 🎏 🌌 👆 🔜 ⚙️ `FastAPI` 🎓: ```Python hl_lines="6 11 16" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` 👆 💪 💭 `APIRouter` "🐩 `FastAPI`" 🎓. @@ -122,7 +122,7 @@ from app.routers import items 👥 🔜 🔜 ⚙️ 🙅 🔗 ✍ 🛃 `X-Token` 🎚: ```Python hl_lines="1 4-6" title="app/dependencies.py" -{!../../../docs_src/bigger_applications/app/dependencies.py!} +{!../../docs_src/bigger_applications/app/dependencies.py!} ``` /// tip @@ -156,7 +156,7 @@ from app.routers import items , ↩️ ❎ 🌐 👈 🔠 *➡ 🛠️*, 👥 💪 🚮 ⚫️ `APIRouter`. ```Python hl_lines="5-10 16 21" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` ➡ 🔠 *➡ 🛠️* ✔️ ▶️ ⏮️ `/`, 💖: @@ -217,7 +217,7 @@ async def read_item(item_id: str): 👥 ⚙️ ⚖ 🗄 ⏮️ `..` 🔗: ```Python hl_lines="3" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` #### ❔ ⚖ 🗄 👷 @@ -290,7 +290,7 @@ that 🔜 ⛓: ✋️ 👥 💪 🚮 _🌅_ `tags` 👈 🔜 ✔ 🎯 *➡ 🛠️*, & ➕ `responses` 🎯 👈 *➡ 🛠️*: ```Python hl_lines="30-31" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` /// tip @@ -318,7 +318,7 @@ that 🔜 ⛓: & 👥 💪 📣 [🌐 🔗](dependencies/global-dependencies.md){.internal-link target=_blank} 👈 🔜 🌀 ⏮️ 🔗 🔠 `APIRouter`: ```Python hl_lines="1 3 7" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### 🗄 `APIRouter` @@ -326,7 +326,7 @@ that 🔜 ⛓: 🔜 👥 🗄 🎏 🔁 👈 ✔️ `APIRouter`Ⓜ: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 📁 `app/routers/users.py` & `app/routers/items.py` 🔁 👈 🍕 🎏 🐍 📦 `app`, 👥 💪 ⚙️ 👁 ❣ `.` 🗄 👫 ⚙️ "⚖ 🗄". @@ -391,7 +391,7 @@ from .routers.users import router , 💪 ⚙️ 👯‍♂️ 👫 🎏 📁, 👥 🗄 🔁 🔗: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### 🔌 `APIRouter`Ⓜ `users` & `items` @@ -399,7 +399,7 @@ from .routers.users import router 🔜, ➡️ 🔌 `router`Ⓜ ⚪️➡️ 🔁 `users` & `items`: ```Python hl_lines="10-11" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` /// info @@ -441,7 +441,7 @@ from .routers.users import router 👉 🖼 ⚫️ 🔜 💎 🙅. ✋️ ➡️ 💬 👈 ↩️ ⚫️ 💰 ⏮️ 🎏 🏗 🏢, 👥 🚫🔜 🔀 ⚫️ & 🚮 `prefix`, `dependencies`, `tags`, ♒️. 🔗 `APIRouter`: ```Python hl_lines="3" title="app/internal/admin.py" -{!../../../docs_src/bigger_applications/app/internal/admin.py!} +{!../../docs_src/bigger_applications/app/internal/admin.py!} ``` ✋️ 👥 💚 ⚒ 🛃 `prefix` 🕐❔ ✅ `APIRouter` 👈 🌐 🚮 *➡ 🛠️* ▶️ ⏮️ `/admin`, 👥 💚 🔐 ⚫️ ⏮️ `dependencies` 👥 ⏪ ✔️ 👉 🏗, & 👥 💚 🔌 `tags` & `responses`. @@ -449,7 +449,7 @@ from .routers.users import router 👥 💪 📣 🌐 👈 🍵 ✔️ 🔀 ⏮️ `APIRouter` 🚶‍♀️ 👈 🔢 `app.include_router()`: ```Python hl_lines="14-17" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 👈 🌌, ⏮️ `APIRouter` 🔜 🚧 ⚗, 👥 💪 💰 👈 🎏 `app/internal/admin.py` 📁 ⏮️ 🎏 🏗 🏢. @@ -472,7 +472,7 @@ from .routers.users import router 📥 👥 ⚫️... 🎦 👈 👥 💪 🤷: ```Python hl_lines="21-23" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` & ⚫️ 🔜 👷 ☑, 👯‍♂️ ⏮️ 🌐 🎏 *➡ 🛠️* 🚮 ⏮️ `app.include_router()`. diff --git a/docs/em/docs/tutorial/body-fields.md b/docs/em/docs/tutorial/body-fields.md index c5a04daeb..eb3093de2 100644 --- a/docs/em/docs/tutorial/body-fields.md +++ b/docs/em/docs/tutorial/body-fields.md @@ -9,7 +9,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="2" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -35,7 +35,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// @@ -43,7 +43,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="9-12" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/body-multiple-params.md b/docs/em/docs/tutorial/body-multiple-params.md index c2a9a224d..2e20c83f9 100644 --- a/docs/em/docs/tutorial/body-multiple-params.md +++ b/docs/em/docs/tutorial/body-multiple-params.md @@ -11,7 +11,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +{!> ../../docs_src/body_multiple_params/tutorial001.py!} ``` //// @@ -19,7 +19,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="17-19" -{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} ``` //// @@ -48,7 +48,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +{!> ../../docs_src/body_multiple_params/tutorial002.py!} ``` //// @@ -56,7 +56,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} ``` //// @@ -103,7 +103,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +{!> ../../docs_src/body_multiple_params/tutorial003.py!} ``` //// @@ -111,7 +111,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} ``` //// @@ -157,7 +157,7 @@ q: str | None = None //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +{!> ../../docs_src/body_multiple_params/tutorial004.py!} ``` //// @@ -165,7 +165,7 @@ q: str | None = None //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="26" -{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` //// @@ -193,7 +193,7 @@ item: Item = Body(embed=True) //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +{!> ../../docs_src/body_multiple_params/tutorial005.py!} ``` //// @@ -201,7 +201,7 @@ item: Item = Body(embed=True) //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="15" -{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/body-nested-models.md b/docs/em/docs/tutorial/body-nested-models.md index 23114540a..3b56b7a07 100644 --- a/docs/em/docs/tutorial/body-nested-models.md +++ b/docs/em/docs/tutorial/body-nested-models.md @@ -9,7 +9,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial001.py!} +{!> ../../docs_src/body_nested_models/tutorial001.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} ``` //// @@ -35,7 +35,7 @@ ✋️ 🐍 ⏬ ⏭ 3️⃣.9️⃣ (3️⃣.6️⃣ & 🔛), 👆 🥇 💪 🗄 `List` ⚪️➡️ 🐩 🐍 `typing` 🕹: ```Python hl_lines="1" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` ### 📣 `list` ⏮️ 🆎 🔢 @@ -68,7 +68,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` //// @@ -76,7 +76,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} ``` //// @@ -84,7 +84,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} ``` //// @@ -100,7 +100,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="1 14" -{!> ../../../docs_src/body_nested_models/tutorial003.py!} +{!> ../../docs_src/body_nested_models/tutorial003.py!} ``` //// @@ -108,7 +108,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} ``` //// @@ -116,7 +116,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} ``` //// @@ -144,7 +144,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -152,7 +152,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -160,7 +160,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7-9" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -172,7 +172,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -180,7 +180,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -188,7 +188,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -227,7 +227,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005.py!} +{!> ../../docs_src/body_nested_models/tutorial005.py!} ``` //// @@ -235,7 +235,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} ``` //// @@ -243,7 +243,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="2 8" -{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} ``` //// @@ -257,7 +257,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006.py!} +{!> ../../docs_src/body_nested_models/tutorial006.py!} ``` //// @@ -265,7 +265,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} ``` //// @@ -273,7 +273,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} ``` //// @@ -317,7 +317,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007.py!} +{!> ../../docs_src/body_nested_models/tutorial007.py!} ``` //// @@ -325,7 +325,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} ``` //// @@ -333,7 +333,7 @@ my_list: List[str] //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7 12 18 21 25" -{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} ``` //// @@ -363,7 +363,7 @@ images: list[Image] //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="15" -{!> ../../../docs_src/body_nested_models/tutorial008.py!} +{!> ../../docs_src/body_nested_models/tutorial008.py!} ``` //// @@ -371,7 +371,7 @@ images: list[Image] //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="13" -{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} ``` //// @@ -407,7 +407,7 @@ images: list[Image] //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/body_nested_models/tutorial009.py!} +{!> ../../docs_src/body_nested_models/tutorial009.py!} ``` //// @@ -415,7 +415,7 @@ images: list[Image] //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} ``` //// diff --git a/docs/em/docs/tutorial/body-updates.md b/docs/em/docs/tutorial/body-updates.md index 97501eb6d..4a4b3b6b8 100644 --- a/docs/em/docs/tutorial/body-updates.md +++ b/docs/em/docs/tutorial/body-updates.md @@ -9,7 +9,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001.py!} +{!> ../../docs_src/body_updates/tutorial001.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001_py39.py!} +{!> ../../docs_src/body_updates/tutorial001_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="28-33" -{!> ../../../docs_src/body_updates/tutorial001_py310.py!} +{!> ../../docs_src/body_updates/tutorial001_py310.py!} ``` //// @@ -79,7 +79,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// @@ -87,7 +87,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -95,7 +95,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="32" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -109,7 +109,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// @@ -117,7 +117,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -125,7 +125,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="33" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -148,7 +148,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// @@ -156,7 +156,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -164,7 +164,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="28-35" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/body.md b/docs/em/docs/tutorial/body.md index 79d8e716f..3468fc512 100644 --- a/docs/em/docs/tutorial/body.md +++ b/docs/em/docs/tutorial/body.md @@ -25,7 +25,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="4" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -33,7 +33,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="2" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -47,7 +47,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="7-11" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -55,7 +55,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="5-9" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -89,7 +89,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -97,7 +97,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -170,7 +170,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="21" -{!> ../../../docs_src/body/tutorial002.py!} +{!> ../../docs_src/body/tutorial002.py!} ``` //// @@ -178,7 +178,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="19" -{!> ../../../docs_src/body/tutorial002_py310.py!} +{!> ../../docs_src/body/tutorial002_py310.py!} ``` //// @@ -192,7 +192,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="17-18" -{!> ../../../docs_src/body/tutorial003.py!} +{!> ../../docs_src/body/tutorial003.py!} ``` //// @@ -200,7 +200,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="15-16" -{!> ../../../docs_src/body/tutorial003_py310.py!} +{!> ../../docs_src/body/tutorial003_py310.py!} ``` //// @@ -214,7 +214,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial004.py!} +{!> ../../docs_src/body/tutorial004.py!} ``` //// @@ -222,7 +222,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial004_py310.py!} +{!> ../../docs_src/body/tutorial004_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/cookie-params.md b/docs/em/docs/tutorial/cookie-params.md index 891999028..f4956e76f 100644 --- a/docs/em/docs/tutorial/cookie-params.md +++ b/docs/em/docs/tutorial/cookie-params.md @@ -9,7 +9,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -39,7 +39,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/cors.md b/docs/em/docs/tutorial/cors.md index 690b8973a..5829319cb 100644 --- a/docs/em/docs/tutorial/cors.md +++ b/docs/em/docs/tutorial/cors.md @@ -47,7 +47,7 @@ * 🎯 🇺🇸🔍 🎚 ⚖️ 🌐 👫 ⏮️ 🃏 `"*"`. ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` 🔢 🔢 ⚙️ `CORSMiddleware` 🛠️ 🚫 🔢, 👆 🔜 💪 🎯 🛠️ 🎯 🇨🇳, 👩‍🔬, ⚖️ 🎚, ✔ 🖥 ✔ ⚙️ 👫 ✖️-🆔 🔑. diff --git a/docs/em/docs/tutorial/debugging.md b/docs/em/docs/tutorial/debugging.md index abef2a50c..9320370d6 100644 --- a/docs/em/docs/tutorial/debugging.md +++ b/docs/em/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ 👆 FastAPI 🈸, 🗄 & 🏃 `uvicorn` 🔗: ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### 🔃 `__name__ == "__main__"` diff --git a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md index f14239b0f..3e58d506c 100644 --- a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md @@ -9,7 +9,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -86,7 +86,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -94,7 +94,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="9-13" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -104,7 +104,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -112,7 +112,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -122,7 +122,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -130,7 +130,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="6" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -152,7 +152,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -160,7 +160,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -206,7 +206,7 @@ commons = Depends(CommonQueryParams) //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003.py!} +{!> ../../docs_src/dependencies/tutorial003.py!} ``` //// @@ -214,7 +214,7 @@ commons = Depends(CommonQueryParams) //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_py310.py!} ``` //// @@ -254,7 +254,7 @@ commons: CommonQueryParams = Depends() //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004.py!} +{!> ../../docs_src/dependencies/tutorial004.py!} ``` //// @@ -262,7 +262,7 @@ commons: CommonQueryParams = Depends() //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index bf267e056..cd36ad100 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -15,7 +15,7 @@ ⚫️ 🔜 `list` `Depends()`: ```Python hl_lines="17" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` 👉 🔗 🔜 🛠️/❎ 🎏 🌌 😐 🔗. ✋️ 👫 💲 (🚥 👫 📨 🙆) 🏆 🚫 🚶‍♀️ 👆 *➡ 🛠️ 🔢*. @@ -47,7 +47,7 @@ 👫 💪 📣 📨 📄 (💖 🎚) ⚖️ 🎏 🎧-🔗: ```Python hl_lines="6 11" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ### 🤚 ⚠ @@ -55,7 +55,7 @@ 👫 🔗 💪 `raise` ⚠, 🎏 😐 🔗: ```Python hl_lines="8 13" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ### 📨 💲 @@ -65,7 +65,7 @@ , 👆 💪 🏤-⚙️ 😐 🔗 (👈 📨 💲) 👆 ⏪ ⚙️ 👱 🙆, & ✋️ 💲 🏆 🚫 ⚙️, 🔗 🔜 🛠️: ```Python hl_lines="9 14" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ## 🔗 👪 *➡ 🛠️* diff --git a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md index 5998d06df..e0d6dba24 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md @@ -30,19 +30,19 @@ FastAPI 🐕‍🦺 🔗 👈 ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -42,7 +42,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -70,7 +70,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -78,7 +78,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -90,7 +90,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -98,7 +98,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/dependencies/sub-dependencies.md b/docs/em/docs/tutorial/dependencies/sub-dependencies.md index 02b33ccd7..a1e7be134 100644 --- a/docs/em/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/sub-dependencies.md @@ -13,7 +13,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -21,7 +21,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -37,7 +37,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -45,7 +45,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -64,7 +64,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="22" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -72,7 +72,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/encoder.md b/docs/em/docs/tutorial/encoder.md index 314f5b324..21419ef21 100644 --- a/docs/em/docs/tutorial/encoder.md +++ b/docs/em/docs/tutorial/encoder.md @@ -23,7 +23,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="5 22" -{!> ../../../docs_src/encoder/tutorial001.py!} +{!> ../../docs_src/encoder/tutorial001.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="4 21" -{!> ../../../docs_src/encoder/tutorial001_py310.py!} +{!> ../../docs_src/encoder/tutorial001_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/extra-data-types.md b/docs/em/docs/tutorial/extra-data-types.md index cbe111079..1d473bd93 100644 --- a/docs/em/docs/tutorial/extra-data-types.md +++ b/docs/em/docs/tutorial/extra-data-types.md @@ -58,7 +58,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// @@ -66,7 +66,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1 2 11-15" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -76,7 +76,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// @@ -84,7 +84,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="17-18" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/extra-models.md b/docs/em/docs/tutorial/extra-models.md index 4703c7123..4fdf196e8 100644 --- a/docs/em/docs/tutorial/extra-models.md +++ b/docs/em/docs/tutorial/extra-models.md @@ -23,7 +23,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../../docs_src/extra_models/tutorial001.py!} +{!> ../../docs_src/extra_models/tutorial001.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +{!> ../../docs_src/extra_models/tutorial001_py310.py!} ``` //// @@ -171,7 +171,7 @@ UserInDB( //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../../docs_src/extra_models/tutorial002.py!} +{!> ../../docs_src/extra_models/tutorial002.py!} ``` //// @@ -179,7 +179,7 @@ UserInDB( //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +{!> ../../docs_src/extra_models/tutorial002_py310.py!} ``` //// @@ -201,7 +201,7 @@ UserInDB( //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="1 14-15 18-20 33" -{!> ../../../docs_src/extra_models/tutorial003.py!} +{!> ../../docs_src/extra_models/tutorial003.py!} ``` //// @@ -209,7 +209,7 @@ UserInDB( //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1 14-15 18-20 33" -{!> ../../../docs_src/extra_models/tutorial003_py310.py!} +{!> ../../docs_src/extra_models/tutorial003_py310.py!} ``` //// @@ -237,7 +237,7 @@ some_variable: PlaneItem | CarItem //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="1 20" -{!> ../../../docs_src/extra_models/tutorial004.py!} +{!> ../../docs_src/extra_models/tutorial004.py!} ``` //// @@ -245,7 +245,7 @@ some_variable: PlaneItem | CarItem //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="18" -{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +{!> ../../docs_src/extra_models/tutorial004_py39.py!} ``` //// @@ -261,7 +261,7 @@ some_variable: PlaneItem | CarItem //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="1 8" -{!> ../../../docs_src/extra_models/tutorial005.py!} +{!> ../../docs_src/extra_models/tutorial005.py!} ``` //// @@ -269,7 +269,7 @@ some_variable: PlaneItem | CarItem //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="6" -{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +{!> ../../docs_src/extra_models/tutorial005_py39.py!} ``` //// diff --git a/docs/em/docs/tutorial/first-steps.md b/docs/em/docs/tutorial/first-steps.md index 158189e6e..d8cc05c40 100644 --- a/docs/em/docs/tutorial/first-steps.md +++ b/docs/em/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ 🙅 FastAPI 📁 💪 👀 💖 👉: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 📁 👈 📁 `main.py`. @@ -134,7 +134,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ### 🔁 1️⃣: 🗄 `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` 🐍 🎓 👈 🚚 🌐 🛠️ 👆 🛠️. @@ -150,7 +150,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ### 🔁 2️⃣: ✍ `FastAPI` "👐" ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 📥 `app` 🔢 🔜 "👐" 🎓 `FastAPI`. @@ -172,7 +172,7 @@ $ uvicorn main:app --reload 🚥 👆 ✍ 👆 📱 💖: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` & 🚮 ⚫️ 📁 `main.py`, ⤴️ 👆 🔜 🤙 `uvicorn` 💖: @@ -251,7 +251,7 @@ https://example.com/items/foo #### 🔬 *➡ 🛠️ 👨‍🎨* ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `@app.get("/")` 💬 **FastAPI** 👈 🔢 ▶️️ 🔛 🈚 🚚 📨 👈 🚶: @@ -307,7 +307,7 @@ https://example.com/items/foo * **🔢**: 🔢 🔛 "👨‍🎨" (🔛 `@app.get("/")`). ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 👉 🐍 🔢. @@ -321,7 +321,7 @@ https://example.com/items/foo 👆 💪 🔬 ⚫️ 😐 🔢 ↩️ `async def`: ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` /// note @@ -333,7 +333,7 @@ https://example.com/items/foo ### 🔁 5️⃣: 📨 🎚 ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 👆 💪 📨 `dict`, `list`, ⭐ 💲 `str`, `int`, ♒️. diff --git a/docs/em/docs/tutorial/handling-errors.md b/docs/em/docs/tutorial/handling-errors.md index ed32ab53a..7f6a704eb 100644 --- a/docs/em/docs/tutorial/handling-errors.md +++ b/docs/em/docs/tutorial/handling-errors.md @@ -26,7 +26,7 @@ ### 🗄 `HTTPException` ```Python hl_lines="1" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### 🤚 `HTTPException` 👆 📟 @@ -42,7 +42,7 @@ 👉 🖼, 🕐❔ 👩‍💻 📨 🏬 🆔 👈 🚫 🔀, 🤚 ⚠ ⏮️ 👔 📟 `404`: ```Python hl_lines="11" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### 📉 📨 @@ -82,7 +82,7 @@ ✋️ 💼 👆 💪 ⚫️ 🏧 😐, 👆 💪 🚮 🛃 🎚: ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial002.py!} +{!../../docs_src/handling_errors/tutorial002.py!} ``` ## ❎ 🛃 ⚠ 🐕‍🦺 @@ -96,7 +96,7 @@ 👆 💪 🚮 🛃 ⚠ 🐕‍🦺 ⏮️ `@app.exception_handler()`: ```Python hl_lines="5-7 13-18 24" -{!../../../docs_src/handling_errors/tutorial003.py!} +{!../../docs_src/handling_errors/tutorial003.py!} ``` 📥, 🚥 👆 📨 `/unicorns/yolo`, *➡ 🛠️* 🔜 `raise` `UnicornException`. @@ -136,7 +136,7 @@ ⚠ 🐕‍🦺 🔜 📨 `Request` & ⚠. ```Python hl_lines="2 14-16" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` 🔜, 🚥 👆 🚶 `/items/foo`, ↩️ 💆‍♂ 🔢 🎻 ❌ ⏮️: @@ -189,7 +189,7 @@ path -> item_id 🖼, 👆 💪 💚 📨 ✅ ✍ 📨 ↩️ 🎻 👫 ❌: ```Python hl_lines="3-4 9-11 22" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` /// note | "📡 ℹ" @@ -207,7 +207,7 @@ path -> item_id 👆 💪 ⚙️ ⚫️ ⏪ 🛠️ 👆 📱 🕹 💪 & ℹ ⚫️, 📨 ⚫️ 👩‍💻, ♒️. ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial005.py!} +{!../../docs_src/handling_errors/tutorial005.py!} ``` 🔜 🔄 📨 ❌ 🏬 💖: @@ -267,7 +267,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException 🚥 👆 💚 ⚙️ ⚠ ⤴️ ⏮️ 🎏 🔢 ⚠ 🐕‍🦺 ⚪️➡️ **FastAPI**, 👆 💪 🗄 & 🏤-⚙️ 🔢 ⚠ 🐕‍🦺 ⚪️➡️ `fastapi.exception_handlers`: ```Python hl_lines="2-5 15 21" -{!../../../docs_src/handling_errors/tutorial006.py!} +{!../../docs_src/handling_errors/tutorial006.py!} ``` 👉 🖼 👆 `print`😅 ❌ ⏮️ 📶 🎨 📧, ✋️ 👆 🤚 💭. 👆 💪 ⚙️ ⚠ & ⤴️ 🏤-⚙️ 🔢 ⚠ 🐕‍🦺. diff --git a/docs/em/docs/tutorial/header-params.md b/docs/em/docs/tutorial/header-params.md index 82583c7c3..34abd3a4c 100644 --- a/docs/em/docs/tutorial/header-params.md +++ b/docs/em/docs/tutorial/header-params.md @@ -9,7 +9,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1" -{!> ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -39,7 +39,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -77,7 +77,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial002.py!} +{!> ../../docs_src/header_params/tutorial002.py!} ``` //// @@ -85,7 +85,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="8" -{!> ../../../docs_src/header_params/tutorial002_py310.py!} +{!> ../../docs_src/header_params/tutorial002_py310.py!} ``` //// @@ -109,7 +109,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003.py!} +{!> ../../docs_src/header_params/tutorial003.py!} ``` //// @@ -117,7 +117,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_py39.py!} +{!> ../../docs_src/header_params/tutorial003_py39.py!} ``` //// @@ -125,7 +125,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial003_py310.py!} +{!> ../../docs_src/header_params/tutorial003_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/metadata.md b/docs/em/docs/tutorial/metadata.md index 6caeed4cd..a30db113d 100644 --- a/docs/em/docs/tutorial/metadata.md +++ b/docs/em/docs/tutorial/metadata.md @@ -18,7 +18,7 @@ 👆 💪 ⚒ 👫 ⏩: ```Python hl_lines="3-16 19-31" -{!../../../docs_src/metadata/tutorial001.py!} +{!../../docs_src/metadata/tutorial001.py!} ``` /// tip @@ -52,7 +52,7 @@ ✍ 🗃 👆 🔖 & 🚶‍♀️ ⚫️ `openapi_tags` 🔢: ```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` 👀 👈 👆 💪 ⚙️ ✍ 🔘 📛, 🖼 "💳" 🔜 🎦 🦁 (**💳**) & "🎀" 🔜 🎦 ❕ (_🎀_). @@ -68,7 +68,7 @@ ⚙️ `tags` 🔢 ⏮️ 👆 *➡ 🛠️* (& `APIRouter`Ⓜ) 🛠️ 👫 🎏 🔖: ```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` /// info @@ -98,7 +98,7 @@ 🖼, ⚒ ⚫️ 🍦 `/api/v1/openapi.json`: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} +{!../../docs_src/metadata/tutorial002.py!} ``` 🚥 👆 💚 ❎ 🗄 🔗 🍕 👆 💪 ⚒ `openapi_url=None`, 👈 🔜 ❎ 🧾 👩‍💻 🔢 👈 ⚙️ ⚫️. @@ -117,5 +117,5 @@ 🖼, ⚒ 🦁 🎚 🍦 `/documentation` & ❎ 📄: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} +{!../../docs_src/metadata/tutorial003.py!} ``` diff --git a/docs/em/docs/tutorial/middleware.md b/docs/em/docs/tutorial/middleware.md index b9bb12e00..cd0777ebb 100644 --- a/docs/em/docs/tutorial/middleware.md +++ b/docs/em/docs/tutorial/middleware.md @@ -32,7 +32,7 @@ * 👆 💪 ⤴️ 🔀 🌅 `response` ⏭ 🛬 ⚫️. ```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` /// tip @@ -60,7 +60,7 @@ 🖼, 👆 💪 🚮 🛃 🎚 `X-Process-Time` ⚗ 🕰 🥈 👈 ⚫️ ✊ 🛠️ 📨 & 🏗 📨: ```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` ## 🎏 🛠️ diff --git a/docs/em/docs/tutorial/path-operation-configuration.md b/docs/em/docs/tutorial/path-operation-configuration.md index 1979bed2b..9529928fb 100644 --- a/docs/em/docs/tutorial/path-operation-configuration.md +++ b/docs/em/docs/tutorial/path-operation-configuration.md @@ -19,7 +19,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001.py!} ``` //// @@ -27,7 +27,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} ``` //// @@ -35,7 +35,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1 15" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} ``` //// @@ -57,7 +57,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002.py!} ``` //// @@ -65,7 +65,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} ``` //// @@ -73,7 +73,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="15 20 25" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} ``` //// @@ -91,7 +91,7 @@ **FastAPI** 🐕‍🦺 👈 🎏 🌌 ⏮️ ✅ 🎻: ```Python hl_lines="1 8-10 13 18" -{!../../../docs_src/path_operation_configuration/tutorial002b.py!} +{!../../docs_src/path_operation_configuration/tutorial002b.py!} ``` ## 📄 & 📛 @@ -101,7 +101,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003.py!} ``` //// @@ -109,7 +109,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} ``` //// @@ -117,7 +117,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="18-19" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} ``` //// @@ -131,7 +131,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="19-27" -{!> ../../../docs_src/path_operation_configuration/tutorial004.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004.py!} ``` //// @@ -139,7 +139,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="19-27" -{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} ``` //// @@ -147,7 +147,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="17-25" -{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} ``` //// @@ -163,7 +163,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005.py!} ``` //// @@ -171,7 +171,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} ``` //// @@ -179,7 +179,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="19" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} ``` //// @@ -205,7 +205,7 @@ 🚥 👆 💪 ™ *➡ 🛠️* 😢, ✋️ 🍵 ❎ ⚫️, 🚶‍♀️ 🔢 `deprecated`: ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` ⚫️ 🔜 🎯 ™ 😢 🎓 🩺: diff --git a/docs/em/docs/tutorial/path-params-numeric-validations.md b/docs/em/docs/tutorial/path-params-numeric-validations.md index a7952984c..c25f0323e 100644 --- a/docs/em/docs/tutorial/path-params-numeric-validations.md +++ b/docs/em/docs/tutorial/path-params-numeric-validations.md @@ -9,7 +9,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -39,7 +39,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -71,7 +71,7 @@ , 👆 💪 📣 👆 🔢: ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` ## ✔ 🔢 👆 💪, 🎱 @@ -83,7 +83,7 @@ 🐍 🏆 🚫 🕳 ⏮️ 👈 `*`, ✋️ ⚫️ 🔜 💭 👈 🌐 📄 🔢 🔜 🤙 🇨🇻 ❌ (🔑-💲 👫), 💭 kwargs. 🚥 👫 🚫 ✔️ 🔢 💲. ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ## 🔢 🔬: 👑 🌘 ⚖️ 🌓 @@ -93,7 +93,7 @@ 📥, ⏮️ `ge=1`, `item_id` 🔜 💪 🔢 🔢 "`g`🅾 🌘 ⚖️ `e`🅾" `1`. ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` ## 🔢 🔬: 🌘 🌘 & 🌘 🌘 ⚖️ 🌓 @@ -104,7 +104,7 @@ * `le`: `l`👭 🌘 ⚖️ `e`🅾 ```Python hl_lines="9" -{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` ## 🔢 🔬: 🎈, 🌘 🌘 & 🌘 🌘 @@ -118,7 +118,7 @@ & 🎏 lt. ```Python hl_lines="11" -{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` ## 🌃 diff --git a/docs/em/docs/tutorial/path-params.md b/docs/em/docs/tutorial/path-params.md index e0d51a1df..daf5417eb 100644 --- a/docs/em/docs/tutorial/path-params.md +++ b/docs/em/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ 👆 💪 📣 ➡ "🔢" ⚖️ "🔢" ⏮️ 🎏 ❕ ⚙️ 🐍 📁 🎻: ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` 💲 ➡ 🔢 `item_id` 🔜 🚶‍♀️ 👆 🔢 ❌ `item_id`. @@ -19,7 +19,7 @@ 👆 💪 📣 🆎 ➡ 🔢 🔢, ⚙️ 🐩 🐍 🆎 ✍: ```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} +{!../../docs_src/path_params/tutorial002.py!} ``` 👉 💼, `item_id` 📣 `int`. @@ -122,7 +122,7 @@ ↩️ *➡ 🛠️* 🔬 ✔, 👆 💪 ⚒ 💭 👈 ➡ `/users/me` 📣 ⏭ 1️⃣ `/users/{user_id}`: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} +{!../../docs_src/path_params/tutorial003.py!} ``` ⏪, ➡ `/users/{user_id}` 🔜 🏏 `/users/me`, "💭" 👈 ⚫️ 📨 🔢 `user_id` ⏮️ 💲 `"me"`. @@ -130,7 +130,7 @@ ➡, 👆 🚫🔜 ↔ ➡ 🛠️: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003b.py!} +{!../../docs_src/path_params/tutorial003b.py!} ``` 🥇 🕐 🔜 🕧 ⚙️ ↩️ ➡ 🏏 🥇. @@ -148,7 +148,7 @@ ⤴️ ✍ 🎓 🔢 ⏮️ 🔧 💲, ❔ 🔜 💪 ☑ 💲: ```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// info @@ -168,7 +168,7 @@ ⤴️ ✍ *➡ 🔢* ⏮️ 🆎 ✍ ⚙️ 🔢 🎓 👆 ✍ (`ModelName`): ```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` ### ✅ 🩺 @@ -186,7 +186,7 @@ 👆 💪 🔬 ⚫️ ⏮️ *🔢 👨‍🎓* 👆 ✍ 🔢 `ModelName`: ```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` #### 🤚 *🔢 💲* @@ -194,7 +194,7 @@ 👆 💪 🤚 ☑ 💲 ( `str` 👉 💼) ⚙️ `model_name.value`, ⚖️ 🏢, `your_enum_member.value`: ```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// tip @@ -210,7 +210,7 @@ 👫 🔜 🗜 👫 🔗 💲 (🎻 👉 💼) ⏭ 🛬 👫 👩‍💻: ```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` 👆 👩‍💻 👆 🔜 🤚 🎻 📨 💖: @@ -251,7 +251,7 @@ , 👆 💪 ⚙️ ⚫️ ⏮️: ```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} +{!../../docs_src/path_params/tutorial004.py!} ``` /// tip diff --git a/docs/em/docs/tutorial/query-params-str-validations.md b/docs/em/docs/tutorial/query-params-str-validations.md index 23873155e..f75c0a26f 100644 --- a/docs/em/docs/tutorial/query-params-str-validations.md +++ b/docs/em/docs/tutorial/query-params-str-validations.md @@ -7,7 +7,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial001.py!} +{!> ../../docs_src/query_params_str_validations/tutorial001.py!} ``` //// @@ -15,7 +15,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} ``` //// @@ -41,7 +41,7 @@ FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="3" -{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002.py!} ``` //// @@ -49,7 +49,7 @@ FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1" -{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} ``` //// @@ -61,7 +61,7 @@ FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002.py!} ``` //// @@ -69,7 +69,7 @@ FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} ``` //// @@ -137,7 +137,7 @@ q: Union[str, None] = Query(default=None, max_length=50) //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003.py!} ``` //// @@ -145,7 +145,7 @@ q: Union[str, None] = Query(default=None, max_length=50) //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} ``` //// @@ -157,7 +157,7 @@ q: Union[str, None] = Query(default=None, max_length=50) //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial004.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004.py!} ``` //// @@ -165,7 +165,7 @@ q: Union[str, None] = Query(default=None, max_length=50) //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} ``` //// @@ -187,7 +187,7 @@ q: Union[str, None] = Query(default=None, max_length=50) ➡️ 💬 👈 👆 💚 📣 `q` 🔢 🔢 ✔️ `min_length` `3`, & ✔️ 🔢 💲 `"fixedquery"`: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} +{!../../docs_src/query_params_str_validations/tutorial005.py!} ``` /// note @@ -219,7 +219,7 @@ q: Union[str, None] = Query(default=None, min_length=3) , 🕐❔ 👆 💪 📣 💲 ✔ ⏪ ⚙️ `Query`, 👆 💪 🎯 🚫 📣 🔢 💲: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} +{!../../docs_src/query_params_str_validations/tutorial006.py!} ``` ### ✔ ⏮️ ❕ (`...`) @@ -227,7 +227,7 @@ q: Union[str, None] = Query(default=None, min_length=3) 📤 🎛 🌌 🎯 📣 👈 💲 ✔. 👆 💪 ⚒ `default` 🔢 🔑 💲 `...`: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006b.py!} +{!../../docs_src/query_params_str_validations/tutorial006b.py!} ``` /// info @@ -249,7 +249,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} ``` //// @@ -257,7 +257,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} ``` //// @@ -273,7 +273,7 @@ Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🚥 👆 💭 😬 ⚙️ `...`, 👆 💪 🗄 & ⚙️ `Required` ⚪️➡️ Pydantic: ```Python hl_lines="2 8" -{!../../../docs_src/query_params_str_validations/tutorial006d.py!} +{!../../docs_src/query_params_str_validations/tutorial006d.py!} ``` /// tip @@ -291,7 +291,7 @@ Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011.py!} ``` //// @@ -299,7 +299,7 @@ Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} ``` //// @@ -307,7 +307,7 @@ Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} ``` //// @@ -348,7 +348,7 @@ http://localhost:8000/items/?q=foo&q=bar //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial012.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012.py!} ``` //// @@ -356,7 +356,7 @@ http://localhost:8000/items/?q=foo&q=bar //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} ``` //// @@ -383,7 +383,7 @@ http://localhost:8000/items/ 👆 💪 ⚙️ `list` 🔗 ↩️ `List[str]` (⚖️ `list[str]` 🐍 3️⃣.9️⃣ ➕): ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} +{!../../docs_src/query_params_str_validations/tutorial013.py!} ``` /// note @@ -413,7 +413,7 @@ http://localhost:8000/items/ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007.py!} ``` //// @@ -421,7 +421,7 @@ http://localhost:8000/items/ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} ``` //// @@ -431,7 +431,7 @@ http://localhost:8000/items/ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="13" -{!> ../../../docs_src/query_params_str_validations/tutorial008.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008.py!} ``` //// @@ -439,7 +439,7 @@ http://localhost:8000/items/ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} ``` //// @@ -465,7 +465,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009.py!} ``` //// @@ -473,7 +473,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} ``` //// @@ -489,7 +489,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="18" -{!> ../../../docs_src/query_params_str_validations/tutorial010.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010.py!} ``` //// @@ -497,7 +497,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="16" -{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} ``` //// @@ -513,7 +513,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014.py!} ``` //// @@ -521,7 +521,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/query-params.md b/docs/em/docs/tutorial/query-params.md index 9bdab9e3c..c8432f182 100644 --- a/docs/em/docs/tutorial/query-params.md +++ b/docs/em/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ 🕐❔ 👆 📣 🎏 🔢 🔢 👈 🚫 🍕 ➡ 🔢, 👫 🔁 🔬 "🔢" 🔢. ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` 🔢 ⚒ 🔑-💲 👫 👈 🚶 ⏮️ `?` 📛, 🎏 `&` 🦹. @@ -66,7 +66,7 @@ http://127.0.0.1:8000/items/?skip=20 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial002.py!} +{!> ../../docs_src/query_params/tutorial002.py!} ``` //// @@ -74,7 +74,7 @@ http://127.0.0.1:8000/items/?skip=20 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial002_py310.py!} +{!> ../../docs_src/query_params/tutorial002_py310.py!} ``` //// @@ -94,7 +94,7 @@ http://127.0.0.1:8000/items/?skip=20 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial003.py!} +{!> ../../docs_src/query_params/tutorial003.py!} ``` //// @@ -102,7 +102,7 @@ http://127.0.0.1:8000/items/?skip=20 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial003_py310.py!} +{!> ../../docs_src/query_params/tutorial003_py310.py!} ``` //// @@ -151,7 +151,7 @@ http://127.0.0.1:8000/items/foo?short=yes //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="8 10" -{!> ../../../docs_src/query_params/tutorial004.py!} +{!> ../../docs_src/query_params/tutorial004.py!} ``` //// @@ -159,7 +159,7 @@ http://127.0.0.1:8000/items/foo?short=yes //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="6 8" -{!> ../../../docs_src/query_params/tutorial004_py310.py!} +{!> ../../docs_src/query_params/tutorial004_py310.py!} ``` //// @@ -173,7 +173,7 @@ http://127.0.0.1:8000/items/foo?short=yes ✋️ 🕐❔ 👆 💚 ⚒ 🔢 🔢 ✔, 👆 💪 🚫 📣 🙆 🔢 💲: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` 📥 🔢 🔢 `needy` ✔ 🔢 🔢 🆎 `str`. @@ -221,7 +221,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="10" -{!> ../../../docs_src/query_params/tutorial006.py!} +{!> ../../docs_src/query_params/tutorial006.py!} ``` //// @@ -229,7 +229,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="8" -{!> ../../../docs_src/query_params/tutorial006_py310.py!} +{!> ../../docs_src/query_params/tutorial006_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/request-files.md b/docs/em/docs/tutorial/request-files.md index 010aa76bf..102690f4b 100644 --- a/docs/em/docs/tutorial/request-files.md +++ b/docs/em/docs/tutorial/request-files.md @@ -17,7 +17,7 @@ 🗄 `File` & `UploadFile` ⚪️➡️ `fastapi`: ```Python hl_lines="1" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` ## 🔬 `File` 🔢 @@ -25,7 +25,7 @@ ✍ 📁 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Form`: ```Python hl_lines="7" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` /// info @@ -55,7 +55,7 @@ 🔬 📁 🔢 ⏮️ 🆎 `UploadFile`: ```Python hl_lines="12" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` ⚙️ `UploadFile` ✔️ 📚 📈 🤭 `bytes`: @@ -142,7 +142,7 @@ contents = myfile.file.read() //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02.py!} +{!> ../../docs_src/request_files/tutorial001_02.py!} ``` //// @@ -150,7 +150,7 @@ contents = myfile.file.read() //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7 14" -{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +{!> ../../docs_src/request_files/tutorial001_02_py310.py!} ``` //// @@ -160,7 +160,7 @@ contents = myfile.file.read() 👆 💪 ⚙️ `File()` ⏮️ `UploadFile`, 🖼, ⚒ 🌖 🗃: ```Python hl_lines="13" -{!../../../docs_src/request_files/tutorial001_03.py!} +{!../../docs_src/request_files/tutorial001_03.py!} ``` ## 💗 📁 📂 @@ -174,7 +174,7 @@ contents = myfile.file.read() //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="10 15" -{!> ../../../docs_src/request_files/tutorial002.py!} +{!> ../../docs_src/request_files/tutorial002.py!} ``` //// @@ -182,7 +182,7 @@ contents = myfile.file.read() //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="8 13" -{!> ../../../docs_src/request_files/tutorial002_py39.py!} +{!> ../../docs_src/request_files/tutorial002_py39.py!} ``` //// @@ -204,7 +204,7 @@ contents = myfile.file.read() //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="18" -{!> ../../../docs_src/request_files/tutorial003.py!} +{!> ../../docs_src/request_files/tutorial003.py!} ``` //// @@ -212,7 +212,7 @@ contents = myfile.file.read() //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="16" -{!> ../../../docs_src/request_files/tutorial003_py39.py!} +{!> ../../docs_src/request_files/tutorial003_py39.py!} ``` //// diff --git a/docs/em/docs/tutorial/request-forms-and-files.md b/docs/em/docs/tutorial/request-forms-and-files.md index ab39d1b94..80793dae4 100644 --- a/docs/em/docs/tutorial/request-forms-and-files.md +++ b/docs/em/docs/tutorial/request-forms-and-files.md @@ -13,7 +13,7 @@ ## 🗄 `File` & `Form` ```Python hl_lines="1" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` ## 🔬 `File` & `Form` 🔢 @@ -21,7 +21,7 @@ ✍ 📁 & 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`: ```Python hl_lines="8" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` 📁 & 📨 🏑 🔜 📂 📨 📊 & 👆 🔜 📨 📁 & 📨 🏑. diff --git a/docs/em/docs/tutorial/request-forms.md b/docs/em/docs/tutorial/request-forms.md index 74117c47d..cbe4e2862 100644 --- a/docs/em/docs/tutorial/request-forms.md +++ b/docs/em/docs/tutorial/request-forms.md @@ -15,7 +15,7 @@ 🗄 `Form` ⚪️➡️ `fastapi`: ```Python hl_lines="1" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` ## 🔬 `Form` 🔢 @@ -23,7 +23,7 @@ ✍ 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`: ```Python hl_lines="7" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` 🖼, 1️⃣ 🌌 Oauth2️⃣ 🔧 💪 ⚙️ (🤙 "🔐 💧") ⚫️ ✔ 📨 `username` & `password` 📨 🏑. diff --git a/docs/em/docs/tutorial/response-model.md b/docs/em/docs/tutorial/response-model.md index 9483508aa..fb5c17dd6 100644 --- a/docs/em/docs/tutorial/response-model.md +++ b/docs/em/docs/tutorial/response-model.md @@ -7,7 +7,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="18 23" -{!> ../../../docs_src/response_model/tutorial001_01.py!} +{!> ../../docs_src/response_model/tutorial001_01.py!} ``` //// @@ -15,7 +15,7 @@ //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="18 23" -{!> ../../../docs_src/response_model/tutorial001_01_py39.py!} +{!> ../../docs_src/response_model/tutorial001_01_py39.py!} ``` //// @@ -23,7 +23,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="16 21" -{!> ../../../docs_src/response_model/tutorial001_01_py310.py!} +{!> ../../docs_src/response_model/tutorial001_01_py310.py!} ``` //// @@ -62,7 +62,7 @@ FastAPI 🔜 ⚙️ 👉 📨 🆎: //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001.py!} +{!> ../../docs_src/response_model/tutorial001.py!} ``` //// @@ -70,7 +70,7 @@ FastAPI 🔜 ⚙️ 👉 📨 🆎: //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001_py39.py!} +{!> ../../docs_src/response_model/tutorial001_py39.py!} ``` //// @@ -78,7 +78,7 @@ FastAPI 🔜 ⚙️ 👉 📨 🆎: //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001_py310.py!} +{!> ../../docs_src/response_model/tutorial001_py310.py!} ``` //// @@ -116,7 +116,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9 11" -{!> ../../../docs_src/response_model/tutorial002.py!} +{!> ../../docs_src/response_model/tutorial002.py!} ``` //// @@ -124,7 +124,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7 9" -{!> ../../../docs_src/response_model/tutorial002_py310.py!} +{!> ../../docs_src/response_model/tutorial002_py310.py!} ``` //// @@ -143,7 +143,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="18" -{!> ../../../docs_src/response_model/tutorial002.py!} +{!> ../../docs_src/response_model/tutorial002.py!} ``` //// @@ -151,7 +151,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="16" -{!> ../../../docs_src/response_model/tutorial002_py310.py!} +{!> ../../docs_src/response_model/tutorial002_py310.py!} ``` //// @@ -175,7 +175,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9 11 16" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -183,7 +183,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="9 11 16" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -193,7 +193,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -201,7 +201,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -211,7 +211,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -219,7 +219,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -249,7 +249,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9-13 15-16 20" -{!> ../../../docs_src/response_model/tutorial003_01.py!} +{!> ../../docs_src/response_model/tutorial003_01.py!} ``` //// @@ -257,7 +257,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7-10 13-14 18" -{!> ../../../docs_src/response_model/tutorial003_01_py310.py!} +{!> ../../docs_src/response_model/tutorial003_01_py310.py!} ``` //// @@ -303,7 +303,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 🏆 ⚠ 💼 🔜 [🛬 📨 🔗 🔬 ⏪ 🏧 🩺](../advanced/response-directly.md){.internal-link target=_blank}. ```Python hl_lines="8 10-11" -{!> ../../../docs_src/response_model/tutorial003_02.py!} +{!> ../../docs_src/response_model/tutorial003_02.py!} ``` 👉 🙅 💼 🍵 🔁 FastAPI ↩️ 📨 🆎 ✍ 🎓 (⚖️ 🏿) `Response`. @@ -315,7 +315,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 💪 ⚙️ 🏿 `Response` 🆎 ✍: ```Python hl_lines="8-9" -{!> ../../../docs_src/response_model/tutorial003_03.py!} +{!> ../../docs_src/response_model/tutorial003_03.py!} ``` 👉 🔜 👷 ↩️ `RedirectResponse` 🏿 `Response`, & FastAPI 🔜 🔁 🍵 👉 🙅 💼. @@ -329,7 +329,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="10" -{!> ../../../docs_src/response_model/tutorial003_04.py!} +{!> ../../docs_src/response_model/tutorial003_04.py!} ``` //// @@ -337,7 +337,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="8" -{!> ../../../docs_src/response_model/tutorial003_04_py310.py!} +{!> ../../docs_src/response_model/tutorial003_04_py310.py!} ``` //// @@ -355,7 +355,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/response_model/tutorial003_05.py!} +{!> ../../docs_src/response_model/tutorial003_05.py!} ``` //// @@ -363,7 +363,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/response_model/tutorial003_05_py310.py!} +{!> ../../docs_src/response_model/tutorial003_05_py310.py!} ``` //// @@ -377,7 +377,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="11 13-14" -{!> ../../../docs_src/response_model/tutorial004.py!} +{!> ../../docs_src/response_model/tutorial004.py!} ``` //// @@ -385,7 +385,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="11 13-14" -{!> ../../../docs_src/response_model/tutorial004_py39.py!} +{!> ../../docs_src/response_model/tutorial004_py39.py!} ``` //// @@ -393,7 +393,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="9 11-12" -{!> ../../../docs_src/response_model/tutorial004_py310.py!} +{!> ../../docs_src/response_model/tutorial004_py310.py!} ``` //// @@ -413,7 +413,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial004.py!} +{!> ../../docs_src/response_model/tutorial004.py!} ``` //// @@ -421,7 +421,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial004_py39.py!} +{!> ../../docs_src/response_model/tutorial004_py39.py!} ``` //// @@ -429,7 +429,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial004_py310.py!} +{!> ../../docs_src/response_model/tutorial004_py310.py!} ``` //// @@ -524,7 +524,7 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="31 37" -{!> ../../../docs_src/response_model/tutorial005.py!} +{!> ../../docs_src/response_model/tutorial005.py!} ``` //// @@ -532,7 +532,7 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="29 35" -{!> ../../../docs_src/response_model/tutorial005_py310.py!} +{!> ../../docs_src/response_model/tutorial005_py310.py!} ``` //// @@ -552,7 +552,7 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="31 37" -{!> ../../../docs_src/response_model/tutorial006.py!} +{!> ../../docs_src/response_model/tutorial006.py!} ``` //// @@ -560,7 +560,7 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="29 35" -{!> ../../../docs_src/response_model/tutorial006_py310.py!} +{!> ../../docs_src/response_model/tutorial006_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/response-status-code.md b/docs/em/docs/tutorial/response-status-code.md index 57c44777a..cefff708f 100644 --- a/docs/em/docs/tutorial/response-status-code.md +++ b/docs/em/docs/tutorial/response-status-code.md @@ -9,7 +9,7 @@ * ♒️. ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` /// note @@ -77,7 +77,7 @@ FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅‍♂ 📨 ➡️ 👀 ⏮️ 🖼 🔄: ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` `201` 👔 📟 "✍". @@ -87,7 +87,7 @@ FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅‍♂ 📨 👆 💪 ⚙️ 🏪 🔢 ⚪️➡️ `fastapi.status`. ```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} +{!../../docs_src/response_status_code/tutorial002.py!} ``` 👫 🏪, 👫 🧑‍🤝‍🧑 🎏 🔢, ✋️ 👈 🌌 👆 💪 ⚙️ 👨‍🎨 📋 🔎 👫: diff --git a/docs/em/docs/tutorial/schema-extra-example.md b/docs/em/docs/tutorial/schema-extra-example.md index 8562de09c..e4f877a8e 100644 --- a/docs/em/docs/tutorial/schema-extra-example.md +++ b/docs/em/docs/tutorial/schema-extra-example.md @@ -11,7 +11,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="15-23" -{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +{!> ../../docs_src/schema_extra_example/tutorial001.py!} ``` //// @@ -19,7 +19,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="13-21" -{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} ``` //// @@ -43,7 +43,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="4 10-13" -{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +{!> ../../docs_src/schema_extra_example/tutorial002.py!} ``` //// @@ -51,7 +51,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="2 8-11" -{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} ``` //// @@ -83,7 +83,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="20-25" -{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +{!> ../../docs_src/schema_extra_example/tutorial003.py!} ``` //// @@ -91,7 +91,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="18-23" -{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} ``` //// @@ -118,7 +118,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="21-47" -{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +{!> ../../docs_src/schema_extra_example/tutorial004.py!} ``` //// @@ -126,7 +126,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="19-45" -{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/security/first-steps.md b/docs/em/docs/tutorial/security/first-steps.md index 538ea7b0a..6245f52ab 100644 --- a/docs/em/docs/tutorial/security/first-steps.md +++ b/docs/em/docs/tutorial/security/first-steps.md @@ -21,7 +21,7 @@ 📁 🖼 📁 `main.py`: ```Python -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` ## 🏃 ⚫️ @@ -129,7 +129,7 @@ Oauth2️⃣ 🔧 👈 👩‍💻 ⚖️ 🛠️ 💪 🔬 💽 👈 🔓 👩 🕐❔ 👥 ✍ 👐 `OAuth2PasswordBearer` 🎓 👥 🚶‍♀️ `tokenUrl` 🔢. 👉 🔢 🔌 📛 👈 👩‍💻 (🕸 🏃 👩‍💻 🖥) 🔜 ⚙️ 📨 `username` & `password` ✔ 🤚 🤝. ```Python hl_lines="6" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` /// tip @@ -169,7 +169,7 @@ oauth2_scheme(some, parameters) 🔜 👆 💪 🚶‍♀️ 👈 `oauth2_scheme` 🔗 ⏮️ `Depends`. ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` 👉 🔗 🔜 🚚 `str` 👈 🛠️ 🔢 `token` *➡ 🛠️ 🔢*. diff --git a/docs/em/docs/tutorial/security/get-current-user.md b/docs/em/docs/tutorial/security/get-current-user.md index 15545f427..4e5b4ebfc 100644 --- a/docs/em/docs/tutorial/security/get-current-user.md +++ b/docs/em/docs/tutorial/security/get-current-user.md @@ -3,7 +3,7 @@ ⏮️ 📃 💂‍♂ ⚙️ (❔ 🧢 🔛 🔗 💉 ⚙️) 🤝 *➡ 🛠️ 🔢* `token` `str`: ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` ✋️ 👈 🚫 👈 ⚠. @@ -19,7 +19,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="5 12-16" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -27,7 +27,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="3 10-14" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -45,7 +45,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="25" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -53,7 +53,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="23" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -65,7 +65,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="19-22 26-27" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -73,7 +73,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="17-20 24-25" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -85,7 +85,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="31" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -93,7 +93,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="29" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -153,7 +153,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="30-32" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -161,7 +161,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="28-30" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/security/oauth2-jwt.md b/docs/em/docs/tutorial/security/oauth2-jwt.md index 3ab8cc986..95fa58f71 100644 --- a/docs/em/docs/tutorial/security/oauth2-jwt.md +++ b/docs/em/docs/tutorial/security/oauth2-jwt.md @@ -121,7 +121,7 @@ $ pip install "passlib[bcrypt]" //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -129,7 +129,7 @@ $ pip install "passlib[bcrypt]" //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="6 47 54-55 58-59 68-74" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -171,7 +171,7 @@ $ openssl rand -hex 32 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -179,7 +179,7 @@ $ openssl rand -hex 32 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="5 11-13 27-29 77-85" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -195,7 +195,7 @@ $ openssl rand -hex 32 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="89-106" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -203,7 +203,7 @@ $ openssl rand -hex 32 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="88-105" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -217,7 +217,7 @@ $ openssl rand -hex 32 //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="115-130" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -225,7 +225,7 @@ $ openssl rand -hex 32 //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="114-129" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/security/simple-oauth2.md b/docs/em/docs/tutorial/security/simple-oauth2.md index 937546be8..43d928ce7 100644 --- a/docs/em/docs/tutorial/security/simple-oauth2.md +++ b/docs/em/docs/tutorial/security/simple-oauth2.md @@ -55,7 +55,7 @@ Oauth2️⃣ 👫 🎻. //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="4 76" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -63,7 +63,7 @@ Oauth2️⃣ 👫 🎻. //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="2 74" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -117,7 +117,7 @@ Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="3 77-79" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -125,7 +125,7 @@ Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1 75-77" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -157,7 +157,7 @@ Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="80-83" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -165,7 +165,7 @@ Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="78-81" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -213,7 +213,7 @@ UserInDB( //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="85" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -221,7 +221,7 @@ UserInDB( //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="83" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -253,7 +253,7 @@ UserInDB( //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="58-66 69-72 90" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -261,7 +261,7 @@ UserInDB( //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="55-64 67-70 88" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md index 2492c8708..c59d8c131 100644 --- a/docs/em/docs/tutorial/sql-databases.md +++ b/docs/em/docs/tutorial/sql-databases.md @@ -110,13 +110,13 @@ $ pip install sqlalchemy ### 🗄 🇸🇲 🍕 ```Python hl_lines="1-3" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` ### ✍ 💽 📛 🇸🇲 ```Python hl_lines="5-6" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` 👉 🖼, 👥 "🔗" 🗄 💽 (📂 📁 ⏮️ 🗄 💽). @@ -146,7 +146,7 @@ SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" 👥 🔜 ⏪ ⚙️ 👉 `engine` 🎏 🥉. ```Python hl_lines="8-10" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` #### 🗒 @@ -184,7 +184,7 @@ connect_args={"check_same_thread": False} ✍ `SessionLocal` 🎓, ⚙️ 🔢 `sessionmaker`: ```Python hl_lines="11" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` ### ✍ `Base` 🎓 @@ -194,7 +194,7 @@ connect_args={"check_same_thread": False} ⏪ 👥 🔜 😖 ⚪️➡️ 👉 🎓 ✍ 🔠 💽 🏷 ⚖️ 🎓 (🐜 🏷): ```Python hl_lines="13" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` ## ✍ 💽 🏷 @@ -220,7 +220,7 @@ connect_args={"check_same_thread": False} 👫 🎓 🇸🇲 🏷. ```Python hl_lines="4 7-8 18-19" -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` `__tablename__` 🔢 💬 🇸🇲 📛 🏓 ⚙️ 💽 🔠 👫 🏷. @@ -236,7 +236,7 @@ connect_args={"check_same_thread": False} & 👥 🚶‍♀️ 🇸🇲 🎓 "🆎", `Integer`, `String`, & `Boolean`, 👈 🔬 🆎 💽, ❌. ```Python hl_lines="1 10-13 21-24" -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` ### ✍ 💛 @@ -248,7 +248,7 @@ connect_args={"check_same_thread": False} 👉 🔜 ▶️️, 🌅 ⚖️ 🌘, "🎱" 🔢 👈 🔜 🔌 💲 ⚪️➡️ 🎏 🏓 🔗 👉 1️⃣. ```Python hl_lines="2 15 26" -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` 🕐❔ 🔐 🔢 `items` `User`, `my_user.items`, ⚫️ 🔜 ✔️ 📇 `Item` 🇸🇲 🏷 (⚪️➡️ `items` 🏓) 👈 ✔️ 💱 🔑 ☝ 👉 ⏺ `users` 🏓. @@ -284,7 +284,7 @@ connect_args={"check_same_thread": False} //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} ``` //// @@ -292,7 +292,7 @@ connect_args={"check_same_thread": False} //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` //// @@ -300,7 +300,7 @@ connect_args={"check_same_thread": False} //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="1 4-6 9-10 21-22 25-26" -{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} ``` //// @@ -334,7 +334,7 @@ name: str //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="15-17 31-34" -{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} ``` //// @@ -342,7 +342,7 @@ name: str //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="15-17 31-34" -{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` //// @@ -350,7 +350,7 @@ name: str //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="13-15 29-32" -{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} ``` //// @@ -372,7 +372,7 @@ name: str //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="15 19-20 31 36-37" -{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} ``` //// @@ -380,7 +380,7 @@ name: str //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="15 19-20 31 36-37" -{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` //// @@ -388,7 +388,7 @@ name: str //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python hl_lines="13 17-18 29 34-35" -{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} ``` //// @@ -466,7 +466,7 @@ current_user.items * ✍ 💗 🏬. ```Python hl_lines="1 3 6-7 10-11 14-15 27-28" -{!../../../docs_src/sql_databases/sql_app/crud.py!} +{!../../docs_src/sql_databases/sql_app/crud.py!} ``` /// tip @@ -487,7 +487,7 @@ current_user.items * `refresh` 👆 👐 (👈 ⚫️ 🔌 🙆 🆕 📊 ⚪️➡️ 💽, 💖 🏗 🆔). ```Python hl_lines="18-24 31-36" -{!../../../docs_src/sql_databases/sql_app/crud.py!} +{!../../docs_src/sql_databases/sql_app/crud.py!} ``` /// tip @@ -539,7 +539,7 @@ current_user.items //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="9" -{!> ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -547,7 +547,7 @@ current_user.items //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="7" -{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -577,7 +577,7 @@ current_user.items //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="15-20" -{!> ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -585,7 +585,7 @@ current_user.items //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="13-18" -{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -609,7 +609,7 @@ current_user.items //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="24 32 38 47 53" -{!> ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -617,7 +617,7 @@ current_user.items //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="22 30 36 45 51" -{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -637,7 +637,7 @@ current_user.items //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="23-28 31-34 37-42 45-49 52-55" -{!> ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -645,7 +645,7 @@ current_user.items //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="21-26 29-32 35-40 43-47 50-53" -{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -732,13 +732,13 @@ def read_user(user_id: int, db: Session = Depends(get_db)): * `sql_app/database.py`: ```Python -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` * `sql_app/models.py`: ```Python -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` * `sql_app/schemas.py`: @@ -746,7 +746,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python -{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} ``` //// @@ -754,7 +754,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python -{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` //// @@ -762,7 +762,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python -{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} ``` //// @@ -770,7 +770,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): * `sql_app/crud.py`: ```Python -{!../../../docs_src/sql_databases/sql_app/crud.py!} +{!../../docs_src/sql_databases/sql_app/crud.py!} ``` * `sql_app/main.py`: @@ -778,7 +778,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python -{!> ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -786,7 +786,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python -{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -843,7 +843,7 @@ $ uvicorn sql_app.main:app --reload //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python hl_lines="14-22" -{!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} +{!> ../../docs_src/sql_databases/sql_app/alt_main.py!} ``` //// @@ -851,7 +851,7 @@ $ uvicorn sql_app.main:app --reload //// tab | 🐍 3️⃣.9️⃣ & 🔛 ```Python hl_lines="12-20" -{!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/alt_main.py!} ``` //// diff --git a/docs/em/docs/tutorial/static-files.md b/docs/em/docs/tutorial/static-files.md index 3305746c2..0627031b3 100644 --- a/docs/em/docs/tutorial/static-files.md +++ b/docs/em/docs/tutorial/static-files.md @@ -8,7 +8,7 @@ * "🗻" `StaticFiles()` 👐 🎯 ➡. ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` /// note | "📡 ℹ" diff --git a/docs/em/docs/tutorial/testing.md b/docs/em/docs/tutorial/testing.md index 75dd2d295..5f3d5e736 100644 --- a/docs/em/docs/tutorial/testing.md +++ b/docs/em/docs/tutorial/testing.md @@ -27,7 +27,7 @@ ✍ 🙅 `assert` 📄 ⏮️ 🐩 🐍 🧬 👈 👆 💪 ✅ (🔄, 🐩 `pytest`). ```Python hl_lines="2 12 15-18" -{!../../../docs_src/app_testing/tutorial001.py!} +{!../../docs_src/app_testing/tutorial001.py!} ``` /// tip @@ -75,7 +75,7 @@ ```Python -{!../../../docs_src/app_testing/main.py!} +{!../../docs_src/app_testing/main.py!} ``` ### 🔬 📁 @@ -93,7 +93,7 @@ ↩️ 👉 📁 🎏 📦, 👆 💪 ⚙️ ⚖ 🗄 🗄 🎚 `app` ⚪️➡️ `main` 🕹 (`main.py`): ```Python hl_lines="3" -{!../../../docs_src/app_testing/test_main.py!} +{!../../docs_src/app_testing/test_main.py!} ``` ...& ✔️ 📟 💯 💖 ⏭. @@ -125,7 +125,7 @@ //// tab | 🐍 3️⃣.6️⃣ & 🔛 ```Python -{!> ../../../docs_src/app_testing/app_b/main.py!} +{!> ../../docs_src/app_testing/app_b/main.py!} ``` //// @@ -133,7 +133,7 @@ //// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 ```Python -{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_py310/main.py!} ``` //// @@ -143,7 +143,7 @@ 👆 💪 ⤴️ ℹ `test_main.py` ⏮️ ↔ 💯: ```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} +{!> ../../docs_src/app_testing/app_b/test_main.py!} ``` 🕐❔ 👆 💪 👩‍💻 🚶‍♀️ ℹ 📨 & 👆 🚫 💭 ❔, 👆 💪 🔎 (🇺🇸🔍) ❔ ⚫️ `httpx`, ⚖️ ❔ ⚫️ ⏮️ `requests`, 🇸🇲 🔧 ⚓️ 🔛 📨' 🔧. diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index 4fec41213..c038096f9 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -27,7 +27,7 @@ Each of those response `dict`s can have a key `model`, containing a Pydantic mod For example, to declare another response with a status code `404` and a Pydantic model `Message`, you can write: ```Python hl_lines="18 22" -{!../../../docs_src/additional_responses/tutorial001.py!} +{!../../docs_src/additional_responses/tutorial001.py!} ``` /// note @@ -178,7 +178,7 @@ You can use this same `responses` parameter to add different media types for the For example, you can add an additional media type of `image/png`, declaring that your *path operation* can return a JSON object (with media type `application/json`) or a PNG image: ```Python hl_lines="19-24 28" -{!../../../docs_src/additional_responses/tutorial002.py!} +{!../../docs_src/additional_responses/tutorial002.py!} ``` /// note @@ -208,7 +208,7 @@ For example, you can declare a response with a status code `404` that uses a Pyd And a response with a status code `200` that uses your `response_model`, but includes a custom `example`: ```Python hl_lines="20-31" -{!../../../docs_src/additional_responses/tutorial003.py!} +{!../../docs_src/additional_responses/tutorial003.py!} ``` It will all be combined and included in your OpenAPI, and shown in the API docs: @@ -244,7 +244,7 @@ You can use that technique to reuse some predefined responses in your *path oper For example: ```Python hl_lines="13-17 26" -{!../../../docs_src/additional_responses/tutorial004.py!} +{!../../docs_src/additional_responses/tutorial004.py!} ``` ## More information about OpenAPI responses diff --git a/docs/en/docs/advanced/additional-status-codes.md b/docs/en/docs/advanced/additional-status-codes.md index 99ad72b53..6105a301c 100644 --- a/docs/en/docs/advanced/additional-status-codes.md +++ b/docs/en/docs/advanced/additional-status-codes.md @@ -17,7 +17,7 @@ To achieve that, import `JSONResponse`, and return your content there directly, //// tab | Python 3.10+ ```Python hl_lines="4 25" -{!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_an_py310.py!} ``` //// @@ -25,7 +25,7 @@ To achieve that, import `JSONResponse`, and return your content there directly, //// tab | Python 3.9+ ```Python hl_lines="4 25" -{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_an_py39.py!} ``` //// @@ -33,7 +33,7 @@ To achieve that, import `JSONResponse`, and return your content there directly, //// tab | Python 3.8+ ```Python hl_lines="4 26" -{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_an.py!} ``` //// @@ -47,7 +47,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="2 23" -{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_py310.py!} ``` //// @@ -61,7 +61,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="4 25" -{!> ../../../docs_src/additional_status_codes/tutorial001.py!} +{!> ../../docs_src/additional_status_codes/tutorial001.py!} ``` //// diff --git a/docs/en/docs/advanced/advanced-dependencies.md b/docs/en/docs/advanced/advanced-dependencies.md index f65e1b180..b15a4fe3d 100644 --- a/docs/en/docs/advanced/advanced-dependencies.md +++ b/docs/en/docs/advanced/advanced-dependencies.md @@ -21,7 +21,7 @@ To do that, we declare a method `__call__`: //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -29,7 +29,7 @@ To do that, we declare a method `__call__`: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -43,7 +43,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// @@ -57,7 +57,7 @@ And now, we can use `__init__` to declare the parameters of the instance that we //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -65,7 +65,7 @@ And now, we can use `__init__` to declare the parameters of the instance that we //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -79,7 +79,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// @@ -93,7 +93,7 @@ We could create an instance of this class with: //// tab | Python 3.9+ ```Python hl_lines="18" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -101,7 +101,7 @@ We could create an instance of this class with: //// tab | Python 3.8+ ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -115,7 +115,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// @@ -137,7 +137,7 @@ checker(q="somequery") //// tab | Python 3.9+ ```Python hl_lines="22" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -145,7 +145,7 @@ checker(q="somequery") //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -159,7 +159,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md index a528c80fe..232cd6e57 100644 --- a/docs/en/docs/advanced/async-tests.md +++ b/docs/en/docs/advanced/async-tests.md @@ -33,13 +33,13 @@ For a simple example, let's consider a file structure similar to the one describ The file `main.py` would have: ```Python -{!../../../docs_src/async_tests/main.py!} +{!../../docs_src/async_tests/main.py!} ``` The file `test_main.py` would have the tests for `main.py`, it could look like this now: ```Python -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` ## Run it @@ -61,7 +61,7 @@ $ pytest The marker `@pytest.mark.anyio` tells pytest that this test function should be called asynchronously: ```Python hl_lines="7" -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` /// tip @@ -73,7 +73,7 @@ Note that the test function is now `async def` instead of just `def` as before w Then we can create an `AsyncClient` with the app, and send async requests to it, using `await`. ```Python hl_lines="9-12" -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` This is the equivalent to: diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index e642b1910..67718a27b 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -19,7 +19,7 @@ In this case, the original path `/app` would actually be served at `/api/v1/app` Even though all your code is written assuming there's just `/app`. ```Python hl_lines="6" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} +{!../../docs_src/behind_a_proxy/tutorial001.py!} ``` And the proxy would be **"stripping"** the **path prefix** on the fly before transmitting the request to the app server (probably Uvicorn via FastAPI CLI), keeping your application convinced that it is being served at `/app`, so that you don't have to update all your code to include the prefix `/api/v1`. @@ -99,7 +99,7 @@ You can get the current `root_path` used by your application for each request, i Here we are including it in the message just for demonstration purposes. ```Python hl_lines="8" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} +{!../../docs_src/behind_a_proxy/tutorial001.py!} ``` Then, if you start Uvicorn with: @@ -128,7 +128,7 @@ The response would be something like: Alternatively, if you don't have a way to provide a command line option like `--root-path` or equivalent, you can set the `root_path` parameter when creating your FastAPI app: ```Python hl_lines="3" -{!../../../docs_src/behind_a_proxy/tutorial002.py!} +{!../../docs_src/behind_a_proxy/tutorial002.py!} ``` Passing the `root_path` to `FastAPI` would be the equivalent of passing the `--root-path` command line option to Uvicorn or Hypercorn. @@ -310,7 +310,7 @@ If you pass a custom list of `servers` and there's a `root_path` (because your A For example: ```Python hl_lines="4-7" -{!../../../docs_src/behind_a_proxy/tutorial003.py!} +{!../../docs_src/behind_a_proxy/tutorial003.py!} ``` Will generate an OpenAPI schema like: @@ -359,7 +359,7 @@ The docs UI will interact with the server that you select. If you don't want **FastAPI** to include an automatic server using the `root_path`, you can use the parameter `root_path_in_servers=False`: ```Python hl_lines="9" -{!../../../docs_src/behind_a_proxy/tutorial004.py!} +{!../../docs_src/behind_a_proxy/tutorial004.py!} ``` and then it won't include it in the OpenAPI schema. diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index 1cefe979f..1d6dc3f6d 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -31,7 +31,7 @@ This is because by default, FastAPI will inspect every item inside and make sure But if you are certain that the content that you are returning is **serializable with JSON**, you can pass it directly to the response class and avoid the extra overhead that FastAPI would have by passing your return content through the `jsonable_encoder` before passing it to the response class. ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001b.py!} +{!../../docs_src/custom_response/tutorial001b.py!} ``` /// info @@ -58,7 +58,7 @@ To return a response with HTML directly from **FastAPI**, use `HTMLResponse`. * Pass `HTMLResponse` as the parameter `response_class` of your *path operation decorator*. ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial002.py!} +{!../../docs_src/custom_response/tutorial002.py!} ``` /// info @@ -78,7 +78,7 @@ As seen in [Return a Response directly](response-directly.md){.internal-link tar The same example from above, returning an `HTMLResponse`, could look like: ```Python hl_lines="2 7 19" -{!../../../docs_src/custom_response/tutorial003.py!} +{!../../docs_src/custom_response/tutorial003.py!} ``` /// warning @@ -104,7 +104,7 @@ The `response_class` will then be used only to document the OpenAPI *path operat For example, it could be something like: ```Python hl_lines="7 21 23" -{!../../../docs_src/custom_response/tutorial004.py!} +{!../../docs_src/custom_response/tutorial004.py!} ``` In this example, the function `generate_html_response()` already generates and returns a `Response` instead of returning the HTML in a `str`. @@ -145,7 +145,7 @@ It accepts the following parameters: FastAPI (actually Starlette) will automatically include a Content-Length header. It will also include a Content-Type header, based on the `media_type` and appending a charset for text types. ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ### `HTMLResponse` @@ -157,7 +157,7 @@ Takes some text or bytes and returns an HTML response, as you read above. Takes some text or bytes and returns a plain text response. ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial005.py!} +{!../../docs_src/custom_response/tutorial005.py!} ``` ### `JSONResponse` @@ -193,7 +193,7 @@ This requires installing `ujson` for example with `pip install ujson`. /// ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001.py!} +{!../../docs_src/custom_response/tutorial001.py!} ``` /// tip @@ -209,7 +209,7 @@ Returns an HTTP redirect. Uses a 307 status code (Temporary Redirect) by default You can return a `RedirectResponse` directly: ```Python hl_lines="2 9" -{!../../../docs_src/custom_response/tutorial006.py!} +{!../../docs_src/custom_response/tutorial006.py!} ``` --- @@ -218,7 +218,7 @@ Or you can use it in the `response_class` parameter: ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial006b.py!} +{!../../docs_src/custom_response/tutorial006b.py!} ``` If you do that, then you can return the URL directly from your *path operation* function. @@ -230,7 +230,7 @@ In this case, the `status_code` used will be the default one for the `RedirectRe You can also use the `status_code` parameter combined with the `response_class` parameter: ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial006c.py!} +{!../../docs_src/custom_response/tutorial006c.py!} ``` ### `StreamingResponse` @@ -238,7 +238,7 @@ You can also use the `status_code` parameter combined with the `response_class` Takes an async generator or a normal generator/iterator and streams the response body. ```Python hl_lines="2 14" -{!../../../docs_src/custom_response/tutorial007.py!} +{!../../docs_src/custom_response/tutorial007.py!} ``` #### Using `StreamingResponse` with file-like objects @@ -250,7 +250,7 @@ That way, you don't have to read it all first in memory, and you can pass that g This includes many libraries to interact with cloud storage, video processing, and others. ```{ .python .annotate hl_lines="2 10-12 14" } -{!../../../docs_src/custom_response/tutorial008.py!} +{!../../docs_src/custom_response/tutorial008.py!} ``` 1. This is the generator function. It's a "generator function" because it contains `yield` statements inside. @@ -281,13 +281,13 @@ Takes a different set of arguments to instantiate than the other response types: File responses will include appropriate `Content-Length`, `Last-Modified` and `ETag` headers. ```Python hl_lines="2 10" -{!../../../docs_src/custom_response/tutorial009.py!} +{!../../docs_src/custom_response/tutorial009.py!} ``` You can also use the `response_class` parameter: ```Python hl_lines="2 8 10" -{!../../../docs_src/custom_response/tutorial009b.py!} +{!../../docs_src/custom_response/tutorial009b.py!} ``` In this case, you can return the file path directly from your *path operation* function. @@ -303,7 +303,7 @@ Let's say you want it to return indented and formatted JSON, so you want to use You could create a `CustomORJSONResponse`. The main thing you have to do is create a `Response.render(content)` method that returns the content as `bytes`: ```Python hl_lines="9-14 17" -{!../../../docs_src/custom_response/tutorial009c.py!} +{!../../docs_src/custom_response/tutorial009c.py!} ``` Now instead of returning: @@ -331,7 +331,7 @@ The parameter that defines this is `default_response_class`. In the example below, **FastAPI** will use `ORJSONResponse` by default, in all *path operations*, instead of `JSONResponse`. ```Python hl_lines="2 4" -{!../../../docs_src/custom_response/tutorial010.py!} +{!../../docs_src/custom_response/tutorial010.py!} ``` /// tip diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md index 252ab6fa5..efc07eab2 100644 --- a/docs/en/docs/advanced/dataclasses.md +++ b/docs/en/docs/advanced/dataclasses.md @@ -5,7 +5,7 @@ FastAPI is built on top of **Pydantic**, and I have been showing you how to use But FastAPI also supports using `dataclasses` the same way: ```Python hl_lines="1 7-12 19-20" -{!../../../docs_src/dataclasses/tutorial001.py!} +{!../../docs_src/dataclasses/tutorial001.py!} ``` This is still supported thanks to **Pydantic**, as it has internal support for `dataclasses`. @@ -35,7 +35,7 @@ But if you have a bunch of dataclasses laying around, this is a nice trick to us You can also use `dataclasses` in the `response_model` parameter: ```Python hl_lines="1 7-13 19" -{!../../../docs_src/dataclasses/tutorial002.py!} +{!../../docs_src/dataclasses/tutorial002.py!} ``` The dataclass will be automatically converted to a Pydantic dataclass. @@ -53,7 +53,7 @@ In some cases, you might still have to use Pydantic's version of `dataclasses`. In that case, you can simply swap the standard `dataclasses` with `pydantic.dataclasses`, which is a drop-in replacement: ```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } -{!../../../docs_src/dataclasses/tutorial003.py!} +{!../../docs_src/dataclasses/tutorial003.py!} ``` 1. We still import `field` from standard `dataclasses`. diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md index 7fd934344..efce492f4 100644 --- a/docs/en/docs/advanced/events.md +++ b/docs/en/docs/advanced/events.md @@ -31,7 +31,7 @@ Let's start with an example and then see it in detail. We create an async function `lifespan()` with `yield` like this: ```Python hl_lines="16 19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` Here we are simulating the expensive *startup* operation of loading the model by putting the (fake) model function in the dictionary with machine learning models before the `yield`. This code will be executed **before** the application **starts taking requests**, during the *startup*. @@ -51,7 +51,7 @@ Maybe you need to start a new version, or you just got tired of running it. 🤷 The first thing to notice, is that we are defining an async function with `yield`. This is very similar to Dependencies with `yield`. ```Python hl_lines="14-19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` The first part of the function, before the `yield`, will be executed **before** the application starts. @@ -65,7 +65,7 @@ If you check, the function is decorated with an `@asynccontextmanager`. That converts the function into something called an "**async context manager**". ```Python hl_lines="1 13" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` A **context manager** in Python is something that you can use in a `with` statement, for example, `open()` can be used as a context manager: @@ -89,7 +89,7 @@ In our code example above, we don't use it directly, but we pass it to FastAPI f The `lifespan` parameter of the `FastAPI` app takes an **async context manager**, so we can pass our new `lifespan` async context manager to it. ```Python hl_lines="22" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` ## Alternative Events (deprecated) @@ -113,7 +113,7 @@ These functions can be declared with `async def` or normal `def`. To add a function that should be run before the application starts, declare it with the event `"startup"`: ```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} +{!../../docs_src/events/tutorial001.py!} ``` In this case, the `startup` event handler function will initialize the items "database" (just a `dict`) with some values. @@ -127,7 +127,7 @@ And your application won't start receiving requests until all the `startup` even To add a function that should be run when the application is shutting down, declare it with the event `"shutdown"`: ```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} +{!../../docs_src/events/tutorial002.py!} ``` Here, the `shutdown` event handler function will write a text line `"Application shutdown"` to a file `log.txt`. diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index faa7c323f..7872103c3 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -35,7 +35,7 @@ Let's start with a simple FastAPI application: //// tab | Python 3.9+ ```Python hl_lines="7-9 12-13 16-17 21" -{!> ../../../docs_src/generate_clients/tutorial001_py39.py!} +{!> ../../docs_src/generate_clients/tutorial001_py39.py!} ``` //// @@ -43,7 +43,7 @@ Let's start with a simple FastAPI application: //// tab | Python 3.8+ ```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../../docs_src/generate_clients/tutorial001.py!} +{!> ../../docs_src/generate_clients/tutorial001.py!} ``` //// @@ -154,7 +154,7 @@ For example, you could have a section for **items** and another section for **us //// tab | Python 3.9+ ```Python hl_lines="21 26 34" -{!> ../../../docs_src/generate_clients/tutorial002_py39.py!} +{!> ../../docs_src/generate_clients/tutorial002_py39.py!} ``` //// @@ -162,7 +162,7 @@ For example, you could have a section for **items** and another section for **us //// tab | Python 3.8+ ```Python hl_lines="23 28 36" -{!> ../../../docs_src/generate_clients/tutorial002.py!} +{!> ../../docs_src/generate_clients/tutorial002.py!} ``` //// @@ -215,7 +215,7 @@ You can then pass that custom function to **FastAPI** as the `generate_unique_id //// tab | Python 3.9+ ```Python hl_lines="6-7 10" -{!> ../../../docs_src/generate_clients/tutorial003_py39.py!} +{!> ../../docs_src/generate_clients/tutorial003_py39.py!} ``` //// @@ -223,7 +223,7 @@ You can then pass that custom function to **FastAPI** as the `generate_unique_id //// tab | Python 3.8+ ```Python hl_lines="8-9 12" -{!> ../../../docs_src/generate_clients/tutorial003.py!} +{!> ../../docs_src/generate_clients/tutorial003.py!} ``` //// @@ -251,7 +251,7 @@ We could download the OpenAPI JSON to a file `openapi.json` and then we could ** //// tab | Python ```Python -{!> ../../../docs_src/generate_clients/tutorial004.py!} +{!> ../../docs_src/generate_clients/tutorial004.py!} ``` //// @@ -259,7 +259,7 @@ We could download the OpenAPI JSON to a file `openapi.json` and then we could ** //// tab | Node.js ```Javascript -{!> ../../../docs_src/generate_clients/tutorial004.js!} +{!> ../../docs_src/generate_clients/tutorial004.js!} ``` //// diff --git a/docs/en/docs/advanced/middleware.md b/docs/en/docs/advanced/middleware.md index ab7778db0..07deac716 100644 --- a/docs/en/docs/advanced/middleware.md +++ b/docs/en/docs/advanced/middleware.md @@ -58,7 +58,7 @@ Enforces that all incoming requests must either be `https` or `wss`. Any incoming request to `http` or `ws` will be redirected to the secure scheme instead. ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial001.py!} +{!../../docs_src/advanced_middleware/tutorial001.py!} ``` ## `TrustedHostMiddleware` @@ -66,7 +66,7 @@ Any incoming request to `http` or `ws` will be redirected to the secure scheme i Enforces that all incoming requests have a correctly set `Host` header, in order to guard against HTTP Host Header attacks. ```Python hl_lines="2 6-8" -{!../../../docs_src/advanced_middleware/tutorial002.py!} +{!../../docs_src/advanced_middleware/tutorial002.py!} ``` The following arguments are supported: @@ -82,7 +82,7 @@ Handles GZip responses for any request that includes `"gzip"` in the `Accept-Enc The middleware will handle both standard and streaming responses. ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial003.py!} +{!../../docs_src/advanced_middleware/tutorial003.py!} ``` The following arguments are supported: diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md index 7fead2ed9..82069a950 100644 --- a/docs/en/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -32,7 +32,7 @@ It will have a *path operation* that will receive an `Invoice` body, and a query This part is pretty normal, most of the code is probably already familiar to you: ```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` /// tip @@ -93,7 +93,7 @@ Temporarily adopting this point of view (of the *external developer*) can help y First create a new `APIRouter` that will contain one or more callbacks. ```Python hl_lines="3 25" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` ### Create the callback *path operation* @@ -106,7 +106,7 @@ It should look just like a normal FastAPI *path operation*: * And it could also have a declaration of the response it should return, e.g. `response_model=InvoiceEventReceived`. ```Python hl_lines="16-18 21-22 28-32" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` There are 2 main differences from a normal *path operation*: @@ -176,7 +176,7 @@ At this point you have the *callback path operation(s)* needed (the one(s) that Now use the parameter `callbacks` in *your API's path operation decorator* to pass the attribute `.routes` (that's actually just a `list` of routes/*path operations*) from that callback router: ```Python hl_lines="35" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` /// tip diff --git a/docs/en/docs/advanced/openapi-webhooks.md b/docs/en/docs/advanced/openapi-webhooks.md index 5ee321e2a..eaaa48a37 100644 --- a/docs/en/docs/advanced/openapi-webhooks.md +++ b/docs/en/docs/advanced/openapi-webhooks.md @@ -33,7 +33,7 @@ Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` When you create a **FastAPI** application, there is a `webhooks` attribute that you can use to define *webhooks*, the same way you would define *path operations*, for example with `@app.webhooks.post()`. ```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_webhooks/tutorial001.py!} +{!../../docs_src/openapi_webhooks/tutorial001.py!} ``` The webhooks that you define will end up in the **OpenAPI** schema and the automatic **docs UI**. diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md index d599006d2..a61e3f19b 100644 --- a/docs/en/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md @@ -13,7 +13,7 @@ You can set the OpenAPI `operationId` to be used in your *path operation* with t You would have to make sure that it is unique for each operation. ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} ``` ### Using the *path operation function* name as the operationId @@ -23,7 +23,7 @@ If you want to use your APIs' function names as `operationId`s, you can iterate You should do it after adding all your *path operations*. ```Python hl_lines="2 12-21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` /// tip @@ -45,7 +45,7 @@ Even if they are in different modules (Python files). To exclude a *path operation* from the generated OpenAPI schema (and thus, from the automatic documentation systems), use the parameter `include_in_schema` and set it to `False`: ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} ``` ## Advanced description from docstring @@ -57,7 +57,7 @@ Adding an `\f` (an escaped "form feed" character) causes **FastAPI** to truncate It won't show up in the documentation, but other tools (such as Sphinx) will be able to use the rest. ```Python hl_lines="19-29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} ``` ## Additional Responses @@ -101,7 +101,7 @@ You can extend the OpenAPI schema for a *path operation* using the parameter `op This `openapi_extra` can be helpful, for example, to declare [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions): ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial005.py!} ``` If you open the automatic API docs, your extension will show up at the bottom of the specific *path operation*. @@ -150,7 +150,7 @@ For example, you could decide to read and validate the request with your own cod You could do that with `openapi_extra`: ```Python hl_lines="19-36 39-40" -{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial006.py!} ``` In this example, we didn't declare any Pydantic model. In fact, the request body is not even parsed as JSON, it is read directly as `bytes`, and the function `magic_data_reader()` would be in charge of parsing it in some way. @@ -168,7 +168,7 @@ For example, in this application we don't use FastAPI's integrated functionality //// tab | Pydantic v2 ```Python hl_lines="17-22 24" -{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` //// @@ -176,7 +176,7 @@ For example, in this application we don't use FastAPI's integrated functionality //// tab | Pydantic v1 ```Python hl_lines="17-22 24" -{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} ``` //// @@ -196,7 +196,7 @@ And then in our code, we parse that YAML content directly, and then we are again //// tab | Pydantic v2 ```Python hl_lines="26-33" -{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` //// @@ -204,7 +204,7 @@ And then in our code, we parse that YAML content directly, and then we are again //// tab | Pydantic v1 ```Python hl_lines="26-33" -{!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} ``` //// diff --git a/docs/en/docs/advanced/response-change-status-code.md b/docs/en/docs/advanced/response-change-status-code.md index b88d74a8a..fc041f7de 100644 --- a/docs/en/docs/advanced/response-change-status-code.md +++ b/docs/en/docs/advanced/response-change-status-code.md @@ -21,7 +21,7 @@ You can declare a parameter of type `Response` in your *path operation function* And then you can set the `status_code` in that *temporal* response object. ```Python hl_lines="1 9 12" -{!../../../docs_src/response_change_status_code/tutorial001.py!} +{!../../docs_src/response_change_status_code/tutorial001.py!} ``` And then you can return any object you need, as you normally would (a `dict`, a database model, etc). diff --git a/docs/en/docs/advanced/response-cookies.md b/docs/en/docs/advanced/response-cookies.md index 85e423f42..4467779ba 100644 --- a/docs/en/docs/advanced/response-cookies.md +++ b/docs/en/docs/advanced/response-cookies.md @@ -7,7 +7,7 @@ You can declare a parameter of type `Response` in your *path operation function* And then you can set cookies in that *temporal* response object. ```Python hl_lines="1 8-9" -{!../../../docs_src/response_cookies/tutorial002.py!} +{!../../docs_src/response_cookies/tutorial002.py!} ``` And then you can return any object you need, as you normally would (a `dict`, a database model, etc). @@ -27,7 +27,7 @@ To do that, you can create a response as described in [Return a Response Directl Then set Cookies in it, and then return it: ```Python hl_lines="10-12" -{!../../../docs_src/response_cookies/tutorial001.py!} +{!../../docs_src/response_cookies/tutorial001.py!} ``` /// tip diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md index 092aeceb1..8246b9674 100644 --- a/docs/en/docs/advanced/response-directly.md +++ b/docs/en/docs/advanced/response-directly.md @@ -35,7 +35,7 @@ For example, you cannot put a Pydantic model in a `JSONResponse` without first c For those cases, you can use the `jsonable_encoder` to convert your data before passing it to a response: ```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` /// note | "Technical Details" @@ -57,7 +57,7 @@ Let's say that you want to return an ../../../docs_src/security/tutorial006_an_py39.py!} +{!> ../../docs_src/security/tutorial006_an_py39.py!} ``` //// @@ -31,7 +31,7 @@ Then, when you type that username and password, the browser sends them in the he //// tab | Python 3.8+ ```Python hl_lines="2 7 11" -{!> ../../../docs_src/security/tutorial006_an.py!} +{!> ../../docs_src/security/tutorial006_an.py!} ``` //// @@ -45,7 +45,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="2 6 10" -{!> ../../../docs_src/security/tutorial006.py!} +{!> ../../docs_src/security/tutorial006.py!} ``` //// @@ -71,7 +71,7 @@ Then we can use `secrets.compare_digest()` to ensure that `credentials.username` //// tab | Python 3.9+ ```Python hl_lines="1 12-24" -{!> ../../../docs_src/security/tutorial007_an_py39.py!} +{!> ../../docs_src/security/tutorial007_an_py39.py!} ``` //// @@ -79,7 +79,7 @@ Then we can use `secrets.compare_digest()` to ensure that `credentials.username` //// tab | Python 3.8+ ```Python hl_lines="1 12-24" -{!> ../../../docs_src/security/tutorial007_an.py!} +{!> ../../docs_src/security/tutorial007_an.py!} ``` //// @@ -93,7 +93,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1 11-21" -{!> ../../../docs_src/security/tutorial007.py!} +{!> ../../docs_src/security/tutorial007.py!} ``` //// @@ -163,7 +163,7 @@ After detecting that the credentials are incorrect, return an `HTTPException` wi //// tab | Python 3.9+ ```Python hl_lines="26-30" -{!> ../../../docs_src/security/tutorial007_an_py39.py!} +{!> ../../docs_src/security/tutorial007_an_py39.py!} ``` //// @@ -171,7 +171,7 @@ After detecting that the credentials are incorrect, return an `HTTPException` wi //// tab | Python 3.8+ ```Python hl_lines="26-30" -{!> ../../../docs_src/security/tutorial007_an.py!} +{!> ../../docs_src/security/tutorial007_an.py!} ``` //// @@ -185,7 +185,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="23-27" -{!> ../../../docs_src/security/tutorial007.py!} +{!> ../../docs_src/security/tutorial007.py!} ``` //// diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index fdd8db7b9..3db284d02 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -65,7 +65,7 @@ First, let's quickly see the parts that change from the examples in the main **T //// tab | Python 3.10+ ```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -73,7 +73,7 @@ First, let's quickly see the parts that change from the examples in the main **T //// tab | Python 3.9+ ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -81,7 +81,7 @@ First, let's quickly see the parts that change from the examples in the main **T //// tab | Python 3.8+ ```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -95,7 +95,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -109,7 +109,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -123,7 +123,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -139,7 +139,7 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri //// tab | Python 3.10+ ```Python hl_lines="63-66" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -147,7 +147,7 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri //// tab | Python 3.9+ ```Python hl_lines="63-66" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -155,7 +155,7 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri //// tab | Python 3.8+ ```Python hl_lines="64-67" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -169,7 +169,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="62-65" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -183,7 +183,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="63-66" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -197,7 +197,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="63-66" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -229,7 +229,7 @@ But in your application, for security, you should make sure you only add the sco //// tab | Python 3.10+ ```Python hl_lines="156" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -237,7 +237,7 @@ But in your application, for security, you should make sure you only add the sco //// tab | Python 3.9+ ```Python hl_lines="156" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -245,7 +245,7 @@ But in your application, for security, you should make sure you only add the sco //// tab | Python 3.8+ ```Python hl_lines="157" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -259,7 +259,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="155" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -273,7 +273,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="156" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -287,7 +287,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="156" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -319,7 +319,7 @@ We are doing it here to demonstrate how **FastAPI** handles scopes declared at d //// tab | Python 3.10+ ```Python hl_lines="5 140 171" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -327,7 +327,7 @@ We are doing it here to demonstrate how **FastAPI** handles scopes declared at d //// tab | Python 3.9+ ```Python hl_lines="5 140 171" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -335,7 +335,7 @@ We are doing it here to demonstrate how **FastAPI** handles scopes declared at d //// tab | Python 3.8+ ```Python hl_lines="5 141 172" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -349,7 +349,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="4 139 168" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -363,7 +363,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="5 140 169" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -377,7 +377,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="5 140 169" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -409,7 +409,7 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t //// tab | Python 3.10+ ```Python hl_lines="9 106" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -417,7 +417,7 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t //// tab | Python 3.9+ ```Python hl_lines="9 106" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -425,7 +425,7 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t //// tab | Python 3.8+ ```Python hl_lines="9 107" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -439,7 +439,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8 105" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -453,7 +453,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9 106" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -467,7 +467,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9 106" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -487,7 +487,7 @@ In this exception, we include the scopes required (if any) as a string separated //// tab | Python 3.10+ ```Python hl_lines="106 108-116" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -495,7 +495,7 @@ In this exception, we include the scopes required (if any) as a string separated //// tab | Python 3.9+ ```Python hl_lines="106 108-116" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -503,7 +503,7 @@ In this exception, we include the scopes required (if any) as a string separated //// tab | Python 3.8+ ```Python hl_lines="107 109-117" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -517,7 +517,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="105 107-115" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -531,7 +531,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="106 108-116" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -545,7 +545,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="106 108-116" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -567,7 +567,7 @@ We also verify that we have a user with that username, and if not, we raise that //// tab | Python 3.10+ ```Python hl_lines="47 117-128" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -575,7 +575,7 @@ We also verify that we have a user with that username, and if not, we raise that //// tab | Python 3.9+ ```Python hl_lines="47 117-128" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -583,7 +583,7 @@ We also verify that we have a user with that username, and if not, we raise that //// tab | Python 3.8+ ```Python hl_lines="48 118-129" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -597,7 +597,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="46 116-127" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -611,7 +611,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="47 117-128" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -625,7 +625,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="47 117-128" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -639,7 +639,7 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these //// tab | Python 3.10+ ```Python hl_lines="129-135" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -647,7 +647,7 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these //// tab | Python 3.9+ ```Python hl_lines="129-135" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -655,7 +655,7 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these //// tab | Python 3.8+ ```Python hl_lines="130-136" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -669,7 +669,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="128-134" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -683,7 +683,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="129-135" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -697,7 +697,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="129-135" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index 8c04d2507..01810c438 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -63,7 +63,7 @@ You can use all the same validation features and tools you use for Pydantic mode //// tab | Pydantic v2 ```Python hl_lines="2 5-8 11" -{!> ../../../docs_src/settings/tutorial001.py!} +{!> ../../docs_src/settings/tutorial001.py!} ``` //// @@ -77,7 +77,7 @@ In Pydantic v1 you would import `BaseSettings` directly from `pydantic` instead /// ```Python hl_lines="2 5-8 11" -{!> ../../../docs_src/settings/tutorial001_pv1.py!} +{!> ../../docs_src/settings/tutorial001_pv1.py!} ``` //// @@ -97,7 +97,7 @@ Next it will convert and validate the data. So, when you use that `settings` obj Then you can use the new `settings` object in your application: ```Python hl_lines="18-20" -{!../../../docs_src/settings/tutorial001.py!} +{!../../docs_src/settings/tutorial001.py!} ``` ### Run the server @@ -133,13 +133,13 @@ You could put those settings in another module file as you saw in [Bigger Applic For example, you could have a file `config.py` with: ```Python -{!../../../docs_src/settings/app01/config.py!} +{!../../docs_src/settings/app01/config.py!} ``` And then use it in a file `main.py`: ```Python hl_lines="3 11-13" -{!../../../docs_src/settings/app01/main.py!} +{!../../docs_src/settings/app01/main.py!} ``` /// tip @@ -159,7 +159,7 @@ This could be especially useful during testing, as it's very easy to override a Coming from the previous example, your `config.py` file could look like: ```Python hl_lines="10" -{!../../../docs_src/settings/app02/config.py!} +{!../../docs_src/settings/app02/config.py!} ``` Notice that now we don't create a default instance `settings = Settings()`. @@ -171,7 +171,7 @@ Now we create a dependency that returns a new `config.Settings()`. //// tab | Python 3.9+ ```Python hl_lines="6 12-13" -{!> ../../../docs_src/settings/app02_an_py39/main.py!} +{!> ../../docs_src/settings/app02_an_py39/main.py!} ``` //// @@ -179,7 +179,7 @@ Now we create a dependency that returns a new `config.Settings()`. //// tab | Python 3.8+ ```Python hl_lines="6 12-13" -{!> ../../../docs_src/settings/app02_an/main.py!} +{!> ../../docs_src/settings/app02_an/main.py!} ``` //// @@ -193,7 +193,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="5 11-12" -{!> ../../../docs_src/settings/app02/main.py!} +{!> ../../docs_src/settings/app02/main.py!} ``` //// @@ -211,7 +211,7 @@ And then we can require it from the *path operation function* as a dependency an //// tab | Python 3.9+ ```Python hl_lines="17 19-21" -{!> ../../../docs_src/settings/app02_an_py39/main.py!} +{!> ../../docs_src/settings/app02_an_py39/main.py!} ``` //// @@ -219,7 +219,7 @@ And then we can require it from the *path operation function* as a dependency an //// tab | Python 3.8+ ```Python hl_lines="17 19-21" -{!> ../../../docs_src/settings/app02_an/main.py!} +{!> ../../docs_src/settings/app02_an/main.py!} ``` //// @@ -233,7 +233,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="16 18-20" -{!> ../../../docs_src/settings/app02/main.py!} +{!> ../../docs_src/settings/app02/main.py!} ``` //// @@ -243,7 +243,7 @@ Prefer to use the `Annotated` version if possible. Then it would be very easy to provide a different settings object during testing by creating a dependency override for `get_settings`: ```Python hl_lines="9-10 13 21" -{!../../../docs_src/settings/app02/test_main.py!} +{!../../docs_src/settings/app02/test_main.py!} ``` In the dependency override we set a new value for the `admin_email` when creating the new `Settings` object, and then we return that new object. @@ -288,7 +288,7 @@ And then update your `config.py` with: //// tab | Pydantic v2 ```Python hl_lines="9" -{!> ../../../docs_src/settings/app03_an/config.py!} +{!> ../../docs_src/settings/app03_an/config.py!} ``` /// tip @@ -302,7 +302,7 @@ The `model_config` attribute is used just for Pydantic configuration. You can re //// tab | Pydantic v1 ```Python hl_lines="9-10" -{!> ../../../docs_src/settings/app03_an/config_pv1.py!} +{!> ../../docs_src/settings/app03_an/config_pv1.py!} ``` /// tip @@ -347,7 +347,7 @@ But as we are using the `@lru_cache` decorator on top, the `Settings` object wil //// tab | Python 3.9+ ```Python hl_lines="1 11" -{!> ../../../docs_src/settings/app03_an_py39/main.py!} +{!> ../../docs_src/settings/app03_an_py39/main.py!} ``` //// @@ -355,7 +355,7 @@ But as we are using the `@lru_cache` decorator on top, the `Settings` object wil //// tab | Python 3.8+ ```Python hl_lines="1 11" -{!> ../../../docs_src/settings/app03_an/main.py!} +{!> ../../docs_src/settings/app03_an/main.py!} ``` //// @@ -369,7 +369,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1 10" -{!> ../../../docs_src/settings/app03/main.py!} +{!> ../../docs_src/settings/app03/main.py!} ``` //// diff --git a/docs/en/docs/advanced/sub-applications.md b/docs/en/docs/advanced/sub-applications.md index 568a9deca..befa9908a 100644 --- a/docs/en/docs/advanced/sub-applications.md +++ b/docs/en/docs/advanced/sub-applications.md @@ -11,7 +11,7 @@ If you need to have two independent FastAPI applications, with their own indepen First, create the main, top-level, **FastAPI** application, and its *path operations*: ```Python hl_lines="3 6-8" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Sub-application @@ -21,7 +21,7 @@ Then, create your sub-application, and its *path operations*. This sub-application is just another standard FastAPI application, but this is the one that will be "mounted": ```Python hl_lines="11 14-16" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Mount the sub-application @@ -31,7 +31,7 @@ In your top-level application, `app`, mount the sub-application, `subapi`. In this case, it will be mounted at the path `/subapi`: ```Python hl_lines="11 19" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Check the automatic API docs diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 416540ba4..d688c5cb7 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -28,7 +28,7 @@ $ pip install jinja2 * Use the `templates` you created to render and return a `TemplateResponse`, pass the name of the template, the request object, and a "context" dictionary with key-value pairs to be used inside of the Jinja2 template. ```Python hl_lines="4 11 15-18" -{!../../../docs_src/templates/tutorial001.py!} +{!../../docs_src/templates/tutorial001.py!} ``` /// note @@ -58,7 +58,7 @@ You could also use `from starlette.templating import Jinja2Templates`. Then you can write a template at `templates/item.html` with, for example: ```jinja hl_lines="7" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` ### Template Context Values @@ -112,13 +112,13 @@ For example, with an ID of `42`, this would render: You can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted with the `name="static"`. ```jinja hl_lines="4" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` In this example, it would link to a CSS file at `static/styles.css` with: ```CSS hl_lines="4" -{!../../../docs_src/templates/static/styles.css!} +{!../../docs_src/templates/static/styles.css!} ``` And because you are using `StaticFiles`, that CSS file would be served automatically by your **FastAPI** application at the URL `/static/styles.css`. diff --git a/docs/en/docs/advanced/testing-database.md b/docs/en/docs/advanced/testing-database.md index 974cf4caa..2b704f229 100644 --- a/docs/en/docs/advanced/testing-database.md +++ b/docs/en/docs/advanced/testing-database.md @@ -59,7 +59,7 @@ We'll use an in-memory database that persists during the tests instead of the lo But the rest of the session code is more or less the same, we just copy it. ```Python hl_lines="8-13" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` /// tip @@ -83,7 +83,7 @@ That is normally called in `main.py`, but the line in `main.py` uses the databas So we add that line here, with the new file. ```Python hl_lines="16" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` ## Dependency override @@ -91,7 +91,7 @@ So we add that line here, with the new file. Now we create the dependency override and add it to the overrides for our app. ```Python hl_lines="19-24 27" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` /// tip @@ -105,7 +105,7 @@ The code for `override_get_db()` is almost exactly the same as for `get_db()`, b Then we can just test the app as normally. ```Python hl_lines="32-47" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` And all the modifications we made in the database during the tests will be in the `test.db` database instead of the main `sql_app.db`. diff --git a/docs/en/docs/advanced/testing-dependencies.md b/docs/en/docs/advanced/testing-dependencies.md index 92e25f88d..1cc4313a1 100644 --- a/docs/en/docs/advanced/testing-dependencies.md +++ b/docs/en/docs/advanced/testing-dependencies.md @@ -31,7 +31,7 @@ And then **FastAPI** will call that override instead of the original dependency. //// tab | Python 3.10+ ```Python hl_lines="26-27 30" -{!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} +{!> ../../docs_src/dependency_testing/tutorial001_an_py310.py!} ``` //// @@ -39,7 +39,7 @@ And then **FastAPI** will call that override instead of the original dependency. //// tab | Python 3.9+ ```Python hl_lines="28-29 32" -{!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} +{!> ../../docs_src/dependency_testing/tutorial001_an_py39.py!} ``` //// @@ -47,7 +47,7 @@ And then **FastAPI** will call that override instead of the original dependency. //// tab | Python 3.8+ ```Python hl_lines="29-30 33" -{!> ../../../docs_src/dependency_testing/tutorial001_an.py!} +{!> ../../docs_src/dependency_testing/tutorial001_an.py!} ``` //// @@ -61,7 +61,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="24-25 28" -{!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} +{!> ../../docs_src/dependency_testing/tutorial001_py310.py!} ``` //// @@ -75,7 +75,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="28-29 32" -{!> ../../../docs_src/dependency_testing/tutorial001.py!} +{!> ../../docs_src/dependency_testing/tutorial001.py!} ``` //// diff --git a/docs/en/docs/advanced/testing-events.md b/docs/en/docs/advanced/testing-events.md index b24a2ccfe..f48907c7c 100644 --- a/docs/en/docs/advanced/testing-events.md +++ b/docs/en/docs/advanced/testing-events.md @@ -3,5 +3,5 @@ When you need your event handlers (`startup` and `shutdown`) to run in your tests, you can use the `TestClient` with a `with` statement: ```Python hl_lines="9-12 20-24" -{!../../../docs_src/app_testing/tutorial003.py!} +{!../../docs_src/app_testing/tutorial003.py!} ``` diff --git a/docs/en/docs/advanced/testing-websockets.md b/docs/en/docs/advanced/testing-websockets.md index 6c071bc19..ab08c90fe 100644 --- a/docs/en/docs/advanced/testing-websockets.md +++ b/docs/en/docs/advanced/testing-websockets.md @@ -5,7 +5,7 @@ You can use the same `TestClient` to test WebSockets. For this, you use the `TestClient` in a `with` statement, connecting to the WebSocket: ```Python hl_lines="27-31" -{!../../../docs_src/app_testing/tutorial002.py!} +{!../../docs_src/app_testing/tutorial002.py!} ``` /// note diff --git a/docs/en/docs/advanced/using-request-directly.md b/docs/en/docs/advanced/using-request-directly.md index 5473db5cb..917d77a95 100644 --- a/docs/en/docs/advanced/using-request-directly.md +++ b/docs/en/docs/advanced/using-request-directly.md @@ -30,7 +30,7 @@ Let's imagine you want to get the client's IP address/host inside of your *path For that you need to access the request directly. ```Python hl_lines="1 7-8" -{!../../../docs_src/using_request_directly/tutorial001.py!} +{!../../docs_src/using_request_directly/tutorial001.py!} ``` By declaring a *path operation function* parameter with the type being the `Request` **FastAPI** will know to pass the `Request` in that parameter. diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index 44c6c7428..8947f32e7 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -39,7 +39,7 @@ In production you would have one of the options above. But it's the simplest way to focus on the server-side of WebSockets and have a working example: ```Python hl_lines="2 6-38 41-43" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` ## Create a `websocket` @@ -47,7 +47,7 @@ But it's the simplest way to focus on the server-side of WebSockets and have a w In your **FastAPI** application, create a `websocket`: ```Python hl_lines="1 46-47" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` /// note | "Technical Details" @@ -63,7 +63,7 @@ You could also use `from starlette.websockets import WebSocket`. In your WebSocket route you can `await` for messages and send messages. ```Python hl_lines="48-52" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` You can receive and send binary, text, and JSON data. @@ -118,7 +118,7 @@ They work the same way as for other FastAPI endpoints/*path operations*: //// tab | Python 3.10+ ```Python hl_lines="68-69 82" -{!> ../../../docs_src/websockets/tutorial002_an_py310.py!} +{!> ../../docs_src/websockets/tutorial002_an_py310.py!} ``` //// @@ -126,7 +126,7 @@ They work the same way as for other FastAPI endpoints/*path operations*: //// tab | Python 3.9+ ```Python hl_lines="68-69 82" -{!> ../../../docs_src/websockets/tutorial002_an_py39.py!} +{!> ../../docs_src/websockets/tutorial002_an_py39.py!} ``` //// @@ -134,7 +134,7 @@ They work the same way as for other FastAPI endpoints/*path operations*: //// tab | Python 3.8+ ```Python hl_lines="69-70 83" -{!> ../../../docs_src/websockets/tutorial002_an.py!} +{!> ../../docs_src/websockets/tutorial002_an.py!} ``` //// @@ -148,7 +148,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="66-67 79" -{!> ../../../docs_src/websockets/tutorial002_py310.py!} +{!> ../../docs_src/websockets/tutorial002_py310.py!} ``` //// @@ -162,7 +162,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="68-69 81" -{!> ../../../docs_src/websockets/tutorial002.py!} +{!> ../../docs_src/websockets/tutorial002.py!} ``` //// @@ -213,7 +213,7 @@ When a WebSocket connection is closed, the `await websocket.receive_text()` will //// tab | Python 3.9+ ```Python hl_lines="79-81" -{!> ../../../docs_src/websockets/tutorial003_py39.py!} +{!> ../../docs_src/websockets/tutorial003_py39.py!} ``` //// @@ -221,7 +221,7 @@ When a WebSocket connection is closed, the `await websocket.receive_text()` will //// tab | Python 3.8+ ```Python hl_lines="81-83" -{!> ../../../docs_src/websockets/tutorial003.py!} +{!> ../../docs_src/websockets/tutorial003.py!} ``` //// diff --git a/docs/en/docs/advanced/wsgi.md b/docs/en/docs/advanced/wsgi.md index f07609ed6..3974d491c 100644 --- a/docs/en/docs/advanced/wsgi.md +++ b/docs/en/docs/advanced/wsgi.md @@ -13,7 +13,7 @@ Then wrap the WSGI (e.g. Flask) app with the middleware. And then mount that under a path. ```Python hl_lines="2-3 23" -{!../../../docs_src/wsgi/tutorial001.py!} +{!../../docs_src/wsgi/tutorial001.py!} ``` ## Check it diff --git a/docs/en/docs/how-to/async-sql-encode-databases.md b/docs/en/docs/how-to/async-sql-encode-databases.md index a75f8ef58..a72316c4d 100644 --- a/docs/en/docs/how-to/async-sql-encode-databases.md +++ b/docs/en/docs/how-to/async-sql-encode-databases.md @@ -43,7 +43,7 @@ This section doesn't apply those ideas, to be equivalent to the counterpart in < * Create a table `notes` using the `metadata` object. ```Python hl_lines="4 14 16-22" -{!../../../docs_src/async_sql_databases/tutorial001.py!} +{!../../docs_src/async_sql_databases/tutorial001.py!} ``` /// tip @@ -61,7 +61,7 @@ Notice that all this code is pure SQLAlchemy Core. * Create a `database` object. ```Python hl_lines="3 9 12" -{!../../../docs_src/async_sql_databases/tutorial001.py!} +{!../../docs_src/async_sql_databases/tutorial001.py!} ``` /// tip @@ -80,7 +80,7 @@ Here, this section would run directly, right before starting your **FastAPI** ap * Create all the tables from the `metadata` object. ```Python hl_lines="25-28" -{!../../../docs_src/async_sql_databases/tutorial001.py!} +{!../../docs_src/async_sql_databases/tutorial001.py!} ``` ## Create models @@ -91,7 +91,7 @@ Create Pydantic models for: * Notes to be returned (`Note`). ```Python hl_lines="31-33 36-39" -{!../../../docs_src/async_sql_databases/tutorial001.py!} +{!../../docs_src/async_sql_databases/tutorial001.py!} ``` By creating these Pydantic models, the input data will be validated, serialized (converted), and annotated (documented). @@ -104,7 +104,7 @@ So, you will be able to see it all in the interactive API docs. * Create event handlers to connect and disconnect from the database. ```Python hl_lines="42 45-47 50-52" -{!../../../docs_src/async_sql_databases/tutorial001.py!} +{!../../docs_src/async_sql_databases/tutorial001.py!} ``` ## Read notes @@ -112,7 +112,7 @@ So, you will be able to see it all in the interactive API docs. Create the *path operation function* to read notes: ```Python hl_lines="55-58" -{!../../../docs_src/async_sql_databases/tutorial001.py!} +{!../../docs_src/async_sql_databases/tutorial001.py!} ``` /// note @@ -132,7 +132,7 @@ That documents (and validates, serializes, filters) the output data, as a `list` Create the *path operation function* to create notes: ```Python hl_lines="61-65" -{!../../../docs_src/async_sql_databases/tutorial001.py!} +{!../../docs_src/async_sql_databases/tutorial001.py!} ``` /// info diff --git a/docs/en/docs/how-to/conditional-openapi.md b/docs/en/docs/how-to/conditional-openapi.md index add16fbec..6cd0385a2 100644 --- a/docs/en/docs/how-to/conditional-openapi.md +++ b/docs/en/docs/how-to/conditional-openapi.md @@ -30,7 +30,7 @@ You can easily use the same Pydantic settings to configure your generated OpenAP For example: ```Python hl_lines="6 11" -{!../../../docs_src/conditional_openapi/tutorial001.py!} +{!../../docs_src/conditional_openapi/tutorial001.py!} ``` Here we declare the setting `openapi_url` with the same default of `"/openapi.json"`. diff --git a/docs/en/docs/how-to/configure-swagger-ui.md b/docs/en/docs/how-to/configure-swagger-ui.md index 040c3926b..2c649c152 100644 --- a/docs/en/docs/how-to/configure-swagger-ui.md +++ b/docs/en/docs/how-to/configure-swagger-ui.md @@ -19,7 +19,7 @@ Without changing the settings, syntax highlighting is enabled by default: But you can disable it by setting `syntaxHighlight` to `False`: ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial001.py!} +{!../../docs_src/configure_swagger_ui/tutorial001.py!} ``` ...and then Swagger UI won't show the syntax highlighting anymore: @@ -31,7 +31,7 @@ But you can disable it by setting `syntaxHighlight` to `False`: The same way you could set the syntax highlighting theme with the key `"syntaxHighlight.theme"` (notice that it has a dot in the middle): ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial002.py!} +{!../../docs_src/configure_swagger_ui/tutorial002.py!} ``` That configuration would change the syntax highlighting color theme: @@ -45,7 +45,7 @@ FastAPI includes some default configuration parameters appropriate for most of t It includes these default configurations: ```Python -{!../../../fastapi/openapi/docs.py[ln:7-23]!} +{!../../fastapi/openapi/docs.py[ln:7-23]!} ``` You can override any of them by setting a different value in the argument `swagger_ui_parameters`. @@ -53,7 +53,7 @@ You can override any of them by setting a different value in the argument `swagg For example, to disable `deepLinking` you could pass these settings to `swagger_ui_parameters`: ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial003.py!} +{!../../docs_src/configure_swagger_ui/tutorial003.py!} ``` ## Other Swagger UI Parameters diff --git a/docs/en/docs/how-to/custom-docs-ui-assets.md b/docs/en/docs/how-to/custom-docs-ui-assets.md index 0c766d3e4..16c873d11 100644 --- a/docs/en/docs/how-to/custom-docs-ui-assets.md +++ b/docs/en/docs/how-to/custom-docs-ui-assets.md @@ -19,7 +19,7 @@ The first step is to disable the automatic docs, as by default, those use the de To disable them, set their URLs to `None` when creating your `FastAPI` app: ```Python hl_lines="8" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} +{!../../docs_src/custom_docs_ui/tutorial001.py!} ``` ### Include the custom docs @@ -37,7 +37,7 @@ You can reuse FastAPI's internal functions to create the HTML pages for the docs And similarly for ReDoc... ```Python hl_lines="2-6 11-19 22-24 27-33" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} +{!../../docs_src/custom_docs_ui/tutorial001.py!} ``` /// tip @@ -55,7 +55,7 @@ Swagger UI will handle it behind the scenes for you, but it needs this "redirect Now, to be able to test that everything works, create a *path operation*: ```Python hl_lines="36-38" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} +{!../../docs_src/custom_docs_ui/tutorial001.py!} ``` ### Test it @@ -125,7 +125,7 @@ After that, your file structure could look like: * "Mount" a `StaticFiles()` instance in a specific path. ```Python hl_lines="7 11" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` ### Test the static files @@ -159,7 +159,7 @@ The same as when using a custom CDN, the first step is to disable the automatic To disable them, set their URLs to `None` when creating your `FastAPI` app: ```Python hl_lines="9" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` ### Include the custom docs for static files @@ -177,7 +177,7 @@ Again, you can reuse FastAPI's internal functions to create the HTML pages for t And similarly for ReDoc... ```Python hl_lines="2-6 14-22 25-27 30-36" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` /// tip @@ -195,7 +195,7 @@ Swagger UI will handle it behind the scenes for you, but it needs this "redirect Now, to be able to test that everything works, create a *path operation*: ```Python hl_lines="39-41" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} +{!../../docs_src/custom_docs_ui/tutorial002.py!} ``` ### Test Static Files UI diff --git a/docs/en/docs/how-to/custom-request-and-route.md b/docs/en/docs/how-to/custom-request-and-route.md index 20e1904f1..a62ebf1d5 100644 --- a/docs/en/docs/how-to/custom-request-and-route.md +++ b/docs/en/docs/how-to/custom-request-and-route.md @@ -43,7 +43,7 @@ If there's no `gzip` in the header, it will not try to decompress the body. That way, the same route class can handle gzip compressed or uncompressed requests. ```Python hl_lines="8-15" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} +{!../../docs_src/custom_request_and_route/tutorial001.py!} ``` ### Create a custom `GzipRoute` class @@ -57,7 +57,7 @@ This method returns a function. And that function is what will receive a request Here we use it to create a `GzipRequest` from the original request. ```Python hl_lines="18-26" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} +{!../../docs_src/custom_request_and_route/tutorial001.py!} ``` /// note | "Technical Details" @@ -97,13 +97,13 @@ We can also use this same approach to access the request body in an exception ha All we need to do is handle the request inside a `try`/`except` block: ```Python hl_lines="13 15" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} +{!../../docs_src/custom_request_and_route/tutorial002.py!} ``` If an exception occurs, the`Request` instance will still be in scope, so we can read and make use of the request body when handling the error: ```Python hl_lines="16-18" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} +{!../../docs_src/custom_request_and_route/tutorial002.py!} ``` ## Custom `APIRoute` class in a router @@ -111,11 +111,11 @@ If an exception occurs, the`Request` instance will still be in scope, so we can You can also set the `route_class` parameter of an `APIRouter`: ```Python hl_lines="26" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} +{!../../docs_src/custom_request_and_route/tutorial003.py!} ``` In this example, the *path operations* under the `router` will use the custom `TimedRoute` class, and will have an extra `X-Response-Time` header in the response with the time it took to generate the response: ```Python hl_lines="13-20" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} +{!../../docs_src/custom_request_and_route/tutorial003.py!} ``` diff --git a/docs/en/docs/how-to/extending-openapi.md b/docs/en/docs/how-to/extending-openapi.md index 9909f778c..2b0367952 100644 --- a/docs/en/docs/how-to/extending-openapi.md +++ b/docs/en/docs/how-to/extending-openapi.md @@ -44,7 +44,7 @@ For example, let's add Strawberry documentation. diff --git a/docs/en/docs/how-to/nosql-databases-couchbase.md b/docs/en/docs/how-to/nosql-databases-couchbase.md index a0abfe21d..feb4025dd 100644 --- a/docs/en/docs/how-to/nosql-databases-couchbase.md +++ b/docs/en/docs/how-to/nosql-databases-couchbase.md @@ -39,7 +39,7 @@ There is an official project generator with **FastAPI** and **Couchbase**, all b For now, don't pay attention to the rest, only the imports: ```Python hl_lines="3-5" -{!../../../docs_src/nosql_databases/tutorial001.py!} +{!../../docs_src/nosql_databases/tutorial001.py!} ``` ## Define a constant to use as a "document type" @@ -49,7 +49,7 @@ We will use it later as a fixed field `type` in our documents. This is not required by Couchbase, but is a good practice that will help you afterwards. ```Python hl_lines="9" -{!../../../docs_src/nosql_databases/tutorial001.py!} +{!../../docs_src/nosql_databases/tutorial001.py!} ``` ## Add a function to get a `Bucket` @@ -74,7 +74,7 @@ This utility function will: * Return it. ```Python hl_lines="12-21" -{!../../../docs_src/nosql_databases/tutorial001.py!} +{!../../docs_src/nosql_databases/tutorial001.py!} ``` ## Create Pydantic models @@ -86,7 +86,7 @@ As **Couchbase** "documents" are actually just "JSON objects", we can model them First, let's create a `User` model: ```Python hl_lines="24-28" -{!../../../docs_src/nosql_databases/tutorial001.py!} +{!../../docs_src/nosql_databases/tutorial001.py!} ``` We will use this model in our *path operation function*, so, we don't include in it the `hashed_password`. @@ -100,7 +100,7 @@ This will have the data that is actually stored in the database. We don't create it as a subclass of Pydantic's `BaseModel` but as a subclass of our own `User`, because it will have all the attributes in `User` plus a couple more: ```Python hl_lines="31-33" -{!../../../docs_src/nosql_databases/tutorial001.py!} +{!../../docs_src/nosql_databases/tutorial001.py!} ``` /// note @@ -123,7 +123,7 @@ Now create a function that will: By creating a function that is only dedicated to getting your user from a `username` (or any other parameter) independent of your *path operation function*, you can more easily reuse it in multiple parts and also add unit tests for it: ```Python hl_lines="36-42" -{!../../../docs_src/nosql_databases/tutorial001.py!} +{!../../docs_src/nosql_databases/tutorial001.py!} ``` ### f-strings @@ -158,7 +158,7 @@ UserInDB(username="johndoe", hashed_password="some_hash") ### Create the `FastAPI` app ```Python hl_lines="46" -{!../../../docs_src/nosql_databases/tutorial001.py!} +{!../../docs_src/nosql_databases/tutorial001.py!} ``` ### Create the *path operation function* @@ -168,7 +168,7 @@ As our code is calling Couchbase and we are not using the threads", so, we can just get the bucket directly and pass it to our utility functions: ```Python hl_lines="49-53" -{!../../../docs_src/nosql_databases/tutorial001.py!} +{!../../docs_src/nosql_databases/tutorial001.py!} ``` ## Recap diff --git a/docs/en/docs/how-to/separate-openapi-schemas.md b/docs/en/docs/how-to/separate-openapi-schemas.md index 0ab5b1337..75fd3f9b6 100644 --- a/docs/en/docs/how-to/separate-openapi-schemas.md +++ b/docs/en/docs/how-to/separate-openapi-schemas.md @@ -13,7 +13,7 @@ Let's say you have a Pydantic model with default values, like this one: //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} # Code below omitted 👇 ``` @@ -22,7 +22,7 @@ Let's say you have a Pydantic model with default values, like this one: 👀 Full file preview ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} ``` @@ -32,7 +32,7 @@ Let's say you have a Pydantic model with default values, like this one: //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} # Code below omitted 👇 ``` @@ -41,7 +41,7 @@ Let's say you have a Pydantic model with default values, like this one: 👀 Full file preview ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} ``` @@ -51,7 +51,7 @@ Let's say you have a Pydantic model with default values, like this one: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} # Code below omitted 👇 ``` @@ -60,7 +60,7 @@ Let's say you have a Pydantic model with default values, like this one: 👀 Full file preview ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} ``` @@ -74,7 +74,7 @@ If you use this model as an input like here: //// tab | Python 3.10+ ```Python hl_lines="14" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} # Code below omitted 👇 ``` @@ -83,7 +83,7 @@ If you use this model as an input like here: 👀 Full file preview ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} ``` @@ -93,7 +93,7 @@ If you use this model as an input like here: //// tab | Python 3.9+ ```Python hl_lines="16" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} # Code below omitted 👇 ``` @@ -102,7 +102,7 @@ If you use this model as an input like here: 👀 Full file preview ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} ``` @@ -112,7 +112,7 @@ If you use this model as an input like here: //// tab | Python 3.8+ ```Python hl_lines="16" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} # Code below omitted 👇 ``` @@ -121,7 +121,7 @@ If you use this model as an input like here: 👀 Full file preview ```Python -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} ``` @@ -145,7 +145,7 @@ But if you use the same model as an output, like here: //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} ``` //// @@ -153,7 +153,7 @@ But if you use the same model as an output, like here: //// tab | Python 3.9+ ```Python hl_lines="21" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} ``` //// @@ -161,7 +161,7 @@ But if you use the same model as an output, like here: //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} ``` //// @@ -226,7 +226,7 @@ Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓 //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} ``` //// @@ -234,7 +234,7 @@ Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓 //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} ``` //// @@ -242,7 +242,7 @@ Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓 //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!} +{!> ../../docs_src/separate_openapi_schemas/tutorial002.py!} ``` //// diff --git a/docs/en/docs/how-to/sql-databases-peewee.md b/docs/en/docs/how-to/sql-databases-peewee.md index e411c200c..e73ca369b 100644 --- a/docs/en/docs/how-to/sql-databases-peewee.md +++ b/docs/en/docs/how-to/sql-databases-peewee.md @@ -89,7 +89,7 @@ Let's refer to the file `sql_app/database.py`. Let's first check all the normal Peewee code, create a Peewee database: ```Python hl_lines="3 5 22" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} +{!../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` /// tip @@ -149,7 +149,7 @@ This might seem a bit complex (and it actually is), you don't really need to com We will create a `PeeweeConnectionState`: ```Python hl_lines="10-19" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} +{!../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` This class inherits from a special internal class used by Peewee. @@ -173,7 +173,7 @@ But it doesn't give Peewee async super-powers. You should still use normal `def` Now, overwrite the `._state` internal attribute in the Peewee database `db` object using the new `PeeweeConnectionState`: ```Python hl_lines="24" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} +{!../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` /// tip @@ -209,7 +209,7 @@ But Pydantic also uses the term "**model**" to refer to something different, the Import `db` from `database` (the file `database.py` from above) and use it here. ```Python hl_lines="3 6-12 15-21" -{!../../../docs_src/sql_databases_peewee/sql_app/models.py!} +{!../../docs_src/sql_databases_peewee/sql_app/models.py!} ``` /// tip @@ -243,7 +243,7 @@ So this will help us avoiding confusion while using both. Create all the same Pydantic models as in the SQLAlchemy tutorial: ```Python hl_lines="16-18 21-22 25-30 34-35 38-39 42-48" -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} +{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} ``` /// tip @@ -271,7 +271,7 @@ But recent versions of Pydantic allow providing a custom class that inherits fro We are going to create a custom `PeeweeGetterDict` class and use it in all the same Pydantic *models* / schemas that use `orm_mode`: ```Python hl_lines="3 8-13 31 49" -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} +{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} ``` Here we are checking if the attribute that is being accessed (e.g. `.items` in `some_user.items`) is an instance of `peewee.ModelSelect`. @@ -295,7 +295,7 @@ Now let's see the file `sql_app/crud.py`. Create all the same CRUD utils as in the SQLAlchemy tutorial, all the code is very similar: ```Python hl_lines="1 4-5 8-9 12-13 16-20 23-24 27-30" -{!../../../docs_src/sql_databases_peewee/sql_app/crud.py!} +{!../../docs_src/sql_databases_peewee/sql_app/crud.py!} ``` There are some differences with the code for the SQLAlchemy tutorial. @@ -319,7 +319,7 @@ And now in the file `sql_app/main.py` let's integrate and use all the other part In a very simplistic way create the database tables: ```Python hl_lines="9-11" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ### Create a dependency @@ -327,7 +327,7 @@ In a very simplistic way create the database tables: Create a dependency that will connect the database right at the beginning of a request and disconnect it at the end: ```Python hl_lines="23-29" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` Here we have an empty `yield` because we are actually not using the database object directly. @@ -341,7 +341,7 @@ And then, in each *path operation function* that needs to access the database we But we are not using the value given by this dependency (it actually doesn't give any value, as it has an empty `yield`). So, we don't add it to the *path operation function* but to the *path operation decorator* in the `dependencies` parameter: ```Python hl_lines="32 40 47 59 65 72" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ### Context variable sub-dependency @@ -351,7 +351,7 @@ For all the `contextvars` parts to work, we need to make sure we have an indepen For that, we need to create another `async` dependency `reset_db_state()` that is used as a sub-dependency in `get_db()`. It will set the value for the context variable (with just a default `dict`) that will be used as the database state for the whole request. And then the dependency `get_db()` will store in it the database state (connection, transactions, etc). ```Python hl_lines="18-20" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` For the **next request**, as we will reset that context variable again in the `async` dependency `reset_db_state()` and then create a new connection in the `get_db()` dependency, that new request will have its own database state (connection, transactions, etc). @@ -383,7 +383,7 @@ async def reset_db_state(): Now, finally, here's the standard **FastAPI** *path operations* code. ```Python hl_lines="32-37 40-43 46-53 56-62 65-68 71-79" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ### About `def` vs `async def` @@ -500,31 +500,31 @@ Repeat the same process with the 10 tabs. This time all of them will wait and yo * `sql_app/database.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} +{!../../docs_src/sql_databases_peewee/sql_app/database.py!} ``` * `sql_app/models.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/models.py!} +{!../../docs_src/sql_databases_peewee/sql_app/models.py!} ``` * `sql_app/schemas.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} +{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} ``` * `sql_app/crud.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/crud.py!} +{!../../docs_src/sql_databases_peewee/sql_app/crud.py!} ``` * `sql_app/main.py`: ```Python -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} +{!../../docs_src/sql_databases_peewee/sql_app/main.py!} ``` ## Technical Details diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md index 6994adb5f..ee192d8cb 100644 --- a/docs/en/docs/python-types.md +++ b/docs/en/docs/python-types.md @@ -23,7 +23,7 @@ If you are a Python expert, and you already know everything about type hints, sk Let's start with a simple example: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Calling this program outputs: @@ -39,7 +39,7 @@ The function does the following: * Concatenates them with a space in the middle. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Edit it @@ -83,7 +83,7 @@ That's it. Those are the "type hints": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` That is not the same as declaring default values like would be with: @@ -113,7 +113,7 @@ With that, you can scroll, seeing the options, until you find the one that "ring Check this function, it already has type hints: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Because the editor knows the types of the variables, you don't only get completion, you also get error checks: @@ -123,7 +123,7 @@ Because the editor knows the types of the variables, you don't only get completi Now you know that you have to fix it, convert `age` to a string with `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Declaring types @@ -144,7 +144,7 @@ You can use, for example: * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Generic types with type parameters @@ -182,7 +182,7 @@ As the type, put `list`. As the list is a type that contains some internal types, you put them in square brackets: ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006_py39.py!} +{!> ../../docs_src/python_types/tutorial006_py39.py!} ``` //// @@ -192,7 +192,7 @@ As the list is a type that contains some internal types, you put them in square From `typing`, import `List` (with a capital `L`): ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` Declare the variable, with the same colon (`:`) syntax. @@ -202,7 +202,7 @@ As the type, put the `List` that you imported from `typing`. As the list is a type that contains some internal types, you put them in square brackets: ```Python hl_lines="4" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` //// @@ -240,7 +240,7 @@ You would do the same to declare `tuple`s and `set`s: //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial007_py39.py!} +{!> ../../docs_src/python_types/tutorial007_py39.py!} ``` //// @@ -248,7 +248,7 @@ You would do the same to declare `tuple`s and `set`s: //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial007.py!} +{!> ../../docs_src/python_types/tutorial007.py!} ``` //// @@ -269,7 +269,7 @@ The second type parameter is for the values of the `dict`: //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008_py39.py!} +{!> ../../docs_src/python_types/tutorial008_py39.py!} ``` //// @@ -277,7 +277,7 @@ The second type parameter is for the values of the `dict`: //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008.py!} +{!> ../../docs_src/python_types/tutorial008.py!} ``` //// @@ -299,7 +299,7 @@ In Python 3.10 there's also a **new syntax** where you can put the possible type //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +{!> ../../docs_src/python_types/tutorial008b_py310.py!} ``` //// @@ -307,7 +307,7 @@ In Python 3.10 there's also a **new syntax** where you can put the possible type //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008b.py!} +{!> ../../docs_src/python_types/tutorial008b.py!} ``` //// @@ -321,7 +321,7 @@ You can declare that a value could have a type, like `str`, but that it could al In Python 3.6 and above (including Python 3.10) you can declare it by importing and using `Optional` from the `typing` module. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Using `Optional[str]` instead of just `str` will let the editor help you detect errors where you could be assuming that a value is always a `str`, when it could actually be `None` too. @@ -333,7 +333,7 @@ This also means that in Python 3.10, you can use `Something | None`: //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial009_py310.py!} +{!> ../../docs_src/python_types/tutorial009_py310.py!} ``` //// @@ -341,7 +341,7 @@ This also means that in Python 3.10, you can use `Something | None`: //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009.py!} +{!> ../../docs_src/python_types/tutorial009.py!} ``` //// @@ -349,7 +349,7 @@ This also means that in Python 3.10, you can use `Something | None`: //// tab | Python 3.8+ alternative ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009b.py!} +{!> ../../docs_src/python_types/tutorial009b.py!} ``` //// @@ -370,7 +370,7 @@ It's just about the words and names. But those words can affect how you and your As an example, let's take this function: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c.py!} +{!../../docs_src/python_types/tutorial009c.py!} ``` The parameter `name` is defined as `Optional[str]`, but it is **not optional**, you cannot call the function without the parameter: @@ -388,7 +388,7 @@ say_hi(name=None) # This works, None is valid 🎉 The good news is, once you are on Python 3.10 you won't have to worry about that, as you will be able to simply use `|` to define unions of types: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c_py310.py!} +{!../../docs_src/python_types/tutorial009c_py310.py!} ``` And then you won't have to worry about names like `Optional` and `Union`. 😎 @@ -452,13 +452,13 @@ You can also declare a class as the type of a variable. Let's say you have a class `Person`, with a name: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Then you can declare a variable to be of type `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` And then, again, you get all the editor support: @@ -486,7 +486,7 @@ An example from the official Pydantic docs: //// tab | Python 3.10+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py310.py!} +{!> ../../docs_src/python_types/tutorial011_py310.py!} ``` //// @@ -494,7 +494,7 @@ An example from the official Pydantic docs: //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py39.py!} +{!> ../../docs_src/python_types/tutorial011_py39.py!} ``` //// @@ -502,7 +502,7 @@ An example from the official Pydantic docs: //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/python_types/tutorial011.py!} +{!> ../../docs_src/python_types/tutorial011.py!} ``` //// @@ -532,7 +532,7 @@ Python also has a feature that allows putting **additional ../../../docs_src/python_types/tutorial013_py39.py!} +{!> ../../docs_src/python_types/tutorial013_py39.py!} ``` //// @@ -544,7 +544,7 @@ In versions below Python 3.9, you import `Annotated` from `typing_extensions`. It will already be installed with **FastAPI**. ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial013.py!} +{!> ../../docs_src/python_types/tutorial013.py!} ``` //// diff --git a/docs/en/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md index 8b4476e41..1cd460b07 100644 --- a/docs/en/docs/tutorial/background-tasks.md +++ b/docs/en/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ This includes, for example: First, import `BackgroundTasks` and define a parameter in your *path operation function* with a type declaration of `BackgroundTasks`: ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** will create the object of type `BackgroundTasks` for you and pass it as that parameter. @@ -34,7 +34,7 @@ In this case, the task function will write to a file (simulating sending an emai And as the write operation doesn't use `async` and `await`, we define the function with normal `def`: ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## Add the background task @@ -42,7 +42,7 @@ And as the write operation doesn't use `async` and `await`, we define the functi Inside of your *path operation function*, pass your task function to the *background tasks* object with the method `.add_task()`: ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` receives as arguments: @@ -60,7 +60,7 @@ Using `BackgroundTasks` also works with the dependency injection system, you can //// tab | Python 3.10+ ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} +{!> ../../docs_src/background_tasks/tutorial002_an_py310.py!} ``` //// @@ -68,7 +68,7 @@ Using `BackgroundTasks` also works with the dependency injection system, you can //// tab | Python 3.9+ ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} +{!> ../../docs_src/background_tasks/tutorial002_an_py39.py!} ``` //// @@ -76,7 +76,7 @@ Using `BackgroundTasks` also works with the dependency injection system, you can //// tab | Python 3.8+ ```Python hl_lines="14 16 23 26" -{!> ../../../docs_src/background_tasks/tutorial002_an.py!} +{!> ../../docs_src/background_tasks/tutorial002_an.py!} ``` //// @@ -90,7 +90,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11 13 20 23" -{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +{!> ../../docs_src/background_tasks/tutorial002_py310.py!} ``` //// @@ -104,7 +104,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002.py!} +{!> ../../docs_src/background_tasks/tutorial002.py!} ``` //// diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md index 1c33fd051..4ec9b15bd 100644 --- a/docs/en/docs/tutorial/bigger-applications.md +++ b/docs/en/docs/tutorial/bigger-applications.md @@ -86,7 +86,7 @@ You can create the *path operations* for that module using `APIRouter`. You import it and create an "instance" the same way you would with the class `FastAPI`: ```Python hl_lines="1 3" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` ### *Path operations* with `APIRouter` @@ -96,7 +96,7 @@ And then you use it to declare your *path operations*. Use it the same way you would use the `FastAPI` class: ```Python hl_lines="6 11 16" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` You can think of `APIRouter` as a "mini `FastAPI`" class. @@ -124,7 +124,7 @@ We will now use a simple dependency to read a custom `X-Token` header: //// tab | Python 3.9+ ```Python hl_lines="3 6-8" title="app/dependencies.py" -{!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!} ``` //// @@ -132,7 +132,7 @@ We will now use a simple dependency to read a custom `X-Token` header: //// tab | Python 3.8+ ```Python hl_lines="1 5-7" title="app/dependencies.py" -{!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} +{!> ../../docs_src/bigger_applications/app_an/dependencies.py!} ``` //// @@ -146,7 +146,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1 4-6" title="app/dependencies.py" -{!> ../../../docs_src/bigger_applications/app/dependencies.py!} +{!> ../../docs_src/bigger_applications/app/dependencies.py!} ``` //// @@ -182,7 +182,7 @@ We know all the *path operations* in this module have the same: So, instead of adding all that to each *path operation*, we can add it to the `APIRouter`. ```Python hl_lines="5-10 16 21" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` As the path of each *path operation* has to start with `/`, like in: @@ -243,7 +243,7 @@ And we need to get the dependency function from the module `app.dependencies`, t So we use a relative import with `..` for the dependencies: ```Python hl_lines="3" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` #### How relative imports work @@ -316,7 +316,7 @@ We are not adding the prefix `/items` nor the `tags=["items"]` to each *path ope But we can still add _more_ `tags` that will be applied to a specific *path operation*, and also some extra `responses` specific to that *path operation*: ```Python hl_lines="30-31" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` /// tip @@ -344,7 +344,7 @@ You import and create a `FastAPI` class as normally. And we can even declare [global dependencies](dependencies/global-dependencies.md){.internal-link target=_blank} that will be combined with the dependencies for each `APIRouter`: ```Python hl_lines="1 3 7" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### Import the `APIRouter` @@ -352,7 +352,7 @@ And we can even declare [global dependencies](dependencies/global-dependencies.m Now we import the other submodules that have `APIRouter`s: ```Python hl_lines="4-5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` As the files `app/routers/users.py` and `app/routers/items.py` are submodules that are part of the same Python package `app`, we can use a single dot `.` to import them using "relative imports". @@ -417,7 +417,7 @@ the `router` from `users` would overwrite the one from `items` and we wouldn't b So, to be able to use both of them in the same file, we import the submodules directly: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### Include the `APIRouter`s for `users` and `items` @@ -425,7 +425,7 @@ So, to be able to use both of them in the same file, we import the submodules di Now, let's include the `router`s from the submodules `users` and `items`: ```Python hl_lines="10-11" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` /// info @@ -467,7 +467,7 @@ It contains an `APIRouter` with some admin *path operations* that your organizat For this example it will be super simple. But let's say that because it is shared with other projects in the organization, we cannot modify it and add a `prefix`, `dependencies`, `tags`, etc. directly to the `APIRouter`: ```Python hl_lines="3" title="app/internal/admin.py" -{!../../../docs_src/bigger_applications/app/internal/admin.py!} +{!../../docs_src/bigger_applications/app/internal/admin.py!} ``` But we still want to set a custom `prefix` when including the `APIRouter` so that all its *path operations* start with `/admin`, we want to secure it with the `dependencies` we already have for this project, and we want to include `tags` and `responses`. @@ -475,7 +475,7 @@ But we still want to set a custom `prefix` when including the `APIRouter` so tha We can declare all that without having to modify the original `APIRouter` by passing those parameters to `app.include_router()`: ```Python hl_lines="14-17" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` That way, the original `APIRouter` will stay unmodified, so we can still share that same `app/internal/admin.py` file with other projects in the organization. @@ -498,7 +498,7 @@ We can also add *path operations* directly to the `FastAPI` app. Here we do it... just to show that we can 🤷: ```Python hl_lines="21-23" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` and it will work correctly, together with all the other *path operations* added with `app.include_router()`. diff --git a/docs/en/docs/tutorial/body-fields.md b/docs/en/docs/tutorial/body-fields.md index 466df29f1..30a5c623f 100644 --- a/docs/en/docs/tutorial/body-fields.md +++ b/docs/en/docs/tutorial/body-fields.md @@ -9,7 +9,7 @@ First, you have to import it: //// tab | Python 3.10+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ First, you have to import it: //// tab | Python 3.9+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ First, you have to import it: //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="2" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// @@ -71,7 +71,7 @@ You can then use `Field` with model attributes: //// tab | Python 3.10+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -79,7 +79,7 @@ You can then use `Field` with model attributes: //// tab | Python 3.9+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -87,7 +87,7 @@ You can then use `Field` with model attributes: //// tab | Python 3.8+ ```Python hl_lines="12-15" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -101,7 +101,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9-12" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -115,7 +115,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md index d63cd2529..eebbb3fe4 100644 --- a/docs/en/docs/tutorial/body-multiple-params.md +++ b/docs/en/docs/tutorial/body-multiple-params.md @@ -11,7 +11,7 @@ And you can also declare body parameters as optional, by setting the default to //// tab | Python 3.10+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} ``` //// @@ -19,7 +19,7 @@ And you can also declare body parameters as optional, by setting the default to //// tab | Python 3.9+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} ``` //// @@ -27,7 +27,7 @@ And you can also declare body parameters as optional, by setting the default to //// tab | Python 3.8+ ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} ``` //// @@ -41,7 +41,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="17-19" -{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} ``` //// @@ -55,7 +55,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +{!> ../../docs_src/body_multiple_params/tutorial001.py!} ``` //// @@ -84,7 +84,7 @@ But you can also declare multiple body parameters, e.g. `item` and `user`: //// tab | Python 3.10+ ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} ``` //// @@ -92,7 +92,7 @@ But you can also declare multiple body parameters, e.g. `item` and `user`: //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +{!> ../../docs_src/body_multiple_params/tutorial002.py!} ``` //// @@ -139,7 +139,7 @@ But you can instruct **FastAPI** to treat it as another body key using `Body`: //// tab | Python 3.10+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} ``` //// @@ -147,7 +147,7 @@ But you can instruct **FastAPI** to treat it as another body key using `Body`: //// tab | Python 3.9+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} ``` //// @@ -155,7 +155,7 @@ But you can instruct **FastAPI** to treat it as another body key using `Body`: //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} ``` //// @@ -169,7 +169,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} ``` //// @@ -183,7 +183,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +{!> ../../docs_src/body_multiple_params/tutorial003.py!} ``` //// @@ -229,7 +229,7 @@ For example: //// tab | Python 3.10+ ```Python hl_lines="28" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} ``` //// @@ -237,7 +237,7 @@ For example: //// tab | Python 3.9+ ```Python hl_lines="28" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} ``` //// @@ -245,7 +245,7 @@ For example: //// tab | Python 3.8+ ```Python hl_lines="29" -{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} ``` //// @@ -259,7 +259,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="26" -{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` //// @@ -273,7 +273,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="28" -{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +{!> ../../docs_src/body_multiple_params/tutorial004.py!} ``` //// @@ -301,7 +301,7 @@ as in: //// tab | Python 3.10+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} ``` //// @@ -309,7 +309,7 @@ as in: //// tab | Python 3.9+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} ``` //// @@ -317,7 +317,7 @@ as in: //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} ``` //// @@ -331,7 +331,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="15" -{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} ``` //// @@ -345,7 +345,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +{!> ../../docs_src/body_multiple_params/tutorial005.py!} ``` //// diff --git a/docs/en/docs/tutorial/body-nested-models.md b/docs/en/docs/tutorial/body-nested-models.md index d2bda5979..38f3eb136 100644 --- a/docs/en/docs/tutorial/body-nested-models.md +++ b/docs/en/docs/tutorial/body-nested-models.md @@ -9,7 +9,7 @@ You can define an attribute to be a subtype. For example, a Python `list`: //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ You can define an attribute to be a subtype. For example, a Python `list`: //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial001.py!} +{!> ../../docs_src/body_nested_models/tutorial001.py!} ``` //// @@ -35,7 +35,7 @@ In Python 3.9 and above you can use the standard `list` to declare these type an But in Python versions before 3.9 (3.6 and above), you first need to import `List` from standard Python's `typing` module: ```Python hl_lines="1" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` ### Declare a `list` with a type parameter @@ -68,7 +68,7 @@ So, in our example, we can make `tags` be specifically a "list of strings": //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} ``` //// @@ -76,7 +76,7 @@ So, in our example, we can make `tags` be specifically a "list of strings": //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} ``` //// @@ -84,7 +84,7 @@ So, in our example, we can make `tags` be specifically a "list of strings": //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` //// @@ -100,7 +100,7 @@ Then we can declare `tags` as a set of strings: //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} ``` //// @@ -108,7 +108,7 @@ Then we can declare `tags` as a set of strings: //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} ``` //// @@ -116,7 +116,7 @@ Then we can declare `tags` as a set of strings: //// tab | Python 3.8+ ```Python hl_lines="1 14" -{!> ../../../docs_src/body_nested_models/tutorial003.py!} +{!> ../../docs_src/body_nested_models/tutorial003.py!} ``` //// @@ -144,7 +144,7 @@ For example, we can define an `Image` model: //// tab | Python 3.10+ ```Python hl_lines="7-9" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -152,7 +152,7 @@ For example, we can define an `Image` model: //// tab | Python 3.9+ ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -160,7 +160,7 @@ For example, we can define an `Image` model: //// tab | Python 3.8+ ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -172,7 +172,7 @@ And then we can use it as the type of an attribute: //// tab | Python 3.10+ ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -180,7 +180,7 @@ And then we can use it as the type of an attribute: //// tab | Python 3.9+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -188,7 +188,7 @@ And then we can use it as the type of an attribute: //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -227,7 +227,7 @@ For example, as in the `Image` model we have a `url` field, we can declare it to //// tab | Python 3.10+ ```Python hl_lines="2 8" -{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} ``` //// @@ -235,7 +235,7 @@ For example, as in the `Image` model we have a `url` field, we can declare it to //// tab | Python 3.9+ ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} ``` //// @@ -243,7 +243,7 @@ For example, as in the `Image` model we have a `url` field, we can declare it to //// tab | Python 3.8+ ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005.py!} +{!> ../../docs_src/body_nested_models/tutorial005.py!} ``` //// @@ -257,7 +257,7 @@ You can also use Pydantic models as subtypes of `list`, `set`, etc.: //// tab | Python 3.10+ ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} ``` //// @@ -265,7 +265,7 @@ You can also use Pydantic models as subtypes of `list`, `set`, etc.: //// tab | Python 3.9+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} ``` //// @@ -273,7 +273,7 @@ You can also use Pydantic models as subtypes of `list`, `set`, etc.: //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006.py!} +{!> ../../docs_src/body_nested_models/tutorial006.py!} ``` //// @@ -317,7 +317,7 @@ You can define arbitrarily deeply nested models: //// tab | Python 3.10+ ```Python hl_lines="7 12 18 21 25" -{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} ``` //// @@ -325,7 +325,7 @@ You can define arbitrarily deeply nested models: //// tab | Python 3.9+ ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} ``` //// @@ -333,7 +333,7 @@ You can define arbitrarily deeply nested models: //// tab | Python 3.8+ ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007.py!} +{!> ../../docs_src/body_nested_models/tutorial007.py!} ``` //// @@ -363,7 +363,7 @@ as in: //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} ``` //// @@ -371,7 +371,7 @@ as in: //// tab | Python 3.8+ ```Python hl_lines="15" -{!> ../../../docs_src/body_nested_models/tutorial008.py!} +{!> ../../docs_src/body_nested_models/tutorial008.py!} ``` //// @@ -407,7 +407,7 @@ In this case, you would accept any `dict` as long as it has `int` keys with `flo //// tab | Python 3.9+ ```Python hl_lines="7" -{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} ``` //// @@ -415,7 +415,7 @@ In this case, you would accept any `dict` as long as it has `int` keys with `flo //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/body_nested_models/tutorial009.py!} +{!> ../../docs_src/body_nested_models/tutorial009.py!} ``` //// diff --git a/docs/en/docs/tutorial/body-updates.md b/docs/en/docs/tutorial/body-updates.md index 3257f9a08..3ac2e3914 100644 --- a/docs/en/docs/tutorial/body-updates.md +++ b/docs/en/docs/tutorial/body-updates.md @@ -9,7 +9,7 @@ You can use the `jsonable_encoder` to convert the input data to data that can be //// tab | Python 3.10+ ```Python hl_lines="28-33" -{!> ../../../docs_src/body_updates/tutorial001_py310.py!} +{!> ../../docs_src/body_updates/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ You can use the `jsonable_encoder` to convert the input data to data that can be //// tab | Python 3.9+ ```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001_py39.py!} +{!> ../../docs_src/body_updates/tutorial001_py39.py!} ``` //// @@ -25,7 +25,7 @@ You can use the `jsonable_encoder` to convert the input data to data that can be //// tab | Python 3.8+ ```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001.py!} +{!> ../../docs_src/body_updates/tutorial001.py!} ``` //// @@ -87,7 +87,7 @@ Then you can use this to generate a `dict` with only the data that was set (sent //// tab | Python 3.10+ ```Python hl_lines="32" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -95,7 +95,7 @@ Then you can use this to generate a `dict` with only the data that was set (sent //// tab | Python 3.9+ ```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -103,7 +103,7 @@ Then you can use this to generate a `dict` with only the data that was set (sent //// tab | Python 3.8+ ```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// @@ -125,7 +125,7 @@ Like `stored_item_model.model_copy(update=update_data)`: //// tab | Python 3.10+ ```Python hl_lines="33" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -133,7 +133,7 @@ Like `stored_item_model.model_copy(update=update_data)`: //// tab | Python 3.9+ ```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -141,7 +141,7 @@ Like `stored_item_model.model_copy(update=update_data)`: //// tab | Python 3.8+ ```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// @@ -164,7 +164,7 @@ In summary, to apply partial updates you would: //// tab | Python 3.10+ ```Python hl_lines="28-35" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -172,7 +172,7 @@ In summary, to apply partial updates you would: //// tab | Python 3.9+ ```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -180,7 +180,7 @@ In summary, to apply partial updates you would: //// tab | Python 3.8+ ```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md index 83f08ce84..14d621418 100644 --- a/docs/en/docs/tutorial/body.md +++ b/docs/en/docs/tutorial/body.md @@ -25,7 +25,7 @@ First, you need to import `BaseModel` from `pydantic`: //// tab | Python 3.10+ ```Python hl_lines="2" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -33,7 +33,7 @@ First, you need to import `BaseModel` from `pydantic`: //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -47,7 +47,7 @@ Use standard Python types for all the attributes: //// tab | Python 3.10+ ```Python hl_lines="5-9" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -55,7 +55,7 @@ Use standard Python types for all the attributes: //// tab | Python 3.8+ ```Python hl_lines="7-11" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -89,7 +89,7 @@ To add it to your *path operation*, declare it the same way you declared path an //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -97,7 +97,7 @@ To add it to your *path operation*, declare it the same way you declared path an //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -170,7 +170,7 @@ Inside of the function, you can access all the attributes of the model object di //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/body/tutorial002_py310.py!} +{!> ../../docs_src/body/tutorial002_py310.py!} ``` //// @@ -178,7 +178,7 @@ Inside of the function, you can access all the attributes of the model object di //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/body/tutorial002.py!} +{!> ../../docs_src/body/tutorial002.py!} ``` //// @@ -192,7 +192,7 @@ You can declare path parameters and request body at the same time. //// tab | Python 3.10+ ```Python hl_lines="15-16" -{!> ../../../docs_src/body/tutorial003_py310.py!} +{!> ../../docs_src/body/tutorial003_py310.py!} ``` //// @@ -200,7 +200,7 @@ You can declare path parameters and request body at the same time. //// tab | Python 3.8+ ```Python hl_lines="17-18" -{!> ../../../docs_src/body/tutorial003.py!} +{!> ../../docs_src/body/tutorial003.py!} ``` //// @@ -214,7 +214,7 @@ You can also declare **body**, **path** and **query** parameters, all at the sam //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial004_py310.py!} +{!> ../../docs_src/body/tutorial004_py310.py!} ``` //// @@ -222,7 +222,7 @@ You can also declare **body**, **path** and **query** parameters, all at the sam //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial004.py!} +{!> ../../docs_src/body/tutorial004.py!} ``` //// diff --git a/docs/en/docs/tutorial/cookie-param-models.md b/docs/en/docs/tutorial/cookie-param-models.md index 2aa3a1f59..62cafbb23 100644 --- a/docs/en/docs/tutorial/cookie-param-models.md +++ b/docs/en/docs/tutorial/cookie-param-models.md @@ -23,7 +23,7 @@ Declare the **cookie** parameters that you need in a **Pydantic model**, and the //// tab | Python 3.10+ ```Python hl_lines="9-12 16" -{!> ../../../docs_src/cookie_param_models/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_param_models/tutorial001_an_py310.py!} ``` //// @@ -31,7 +31,7 @@ Declare the **cookie** parameters that you need in a **Pydantic model**, and the //// tab | Python 3.9+ ```Python hl_lines="9-12 16" -{!> ../../../docs_src/cookie_param_models/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_param_models/tutorial001_an_py39.py!} ``` //// @@ -39,7 +39,7 @@ Declare the **cookie** parameters that you need in a **Pydantic model**, and the //// tab | Python 3.8+ ```Python hl_lines="10-13 17" -{!> ../../../docs_src/cookie_param_models/tutorial001_an.py!} +{!> ../../docs_src/cookie_param_models/tutorial001_an.py!} ``` //// @@ -53,7 +53,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7-10 14" -{!> ../../../docs_src/cookie_param_models/tutorial001_py310.py!} +{!> ../../docs_src/cookie_param_models/tutorial001_py310.py!} ``` //// @@ -67,7 +67,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9-12 16" -{!> ../../../docs_src/cookie_param_models/tutorial001.py!} +{!> ../../docs_src/cookie_param_models/tutorial001.py!} ``` //// @@ -103,7 +103,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/cookie_param_models/tutorial002_an_py39.py!} +{!> ../../docs_src/cookie_param_models/tutorial002_an_py39.py!} ``` //// @@ -111,7 +111,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/cookie_param_models/tutorial002_an.py!} +{!> ../../docs_src/cookie_param_models/tutorial002_an.py!} ``` //// @@ -125,7 +125,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/cookie_param_models/tutorial002.py!} +{!> ../../docs_src/cookie_param_models/tutorial002.py!} ``` //// diff --git a/docs/en/docs/tutorial/cookie-params.md b/docs/en/docs/tutorial/cookie-params.md index 0214a9c38..8804f854f 100644 --- a/docs/en/docs/tutorial/cookie-params.md +++ b/docs/en/docs/tutorial/cookie-params.md @@ -9,7 +9,7 @@ First import `Cookie`: //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ First import `Cookie`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ First import `Cookie`: //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -67,7 +67,7 @@ You can define the default value as well as all the extra validation or annotati //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -75,7 +75,7 @@ You can define the default value as well as all the extra validation or annotati //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ You can define the default value as well as all the extra validation or annotati //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -97,7 +97,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -111,7 +111,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// diff --git a/docs/en/docs/tutorial/cors.md b/docs/en/docs/tutorial/cors.md index 7dd0a5df5..8dfc9bad9 100644 --- a/docs/en/docs/tutorial/cors.md +++ b/docs/en/docs/tutorial/cors.md @@ -47,7 +47,7 @@ You can also specify whether your backend allows: * Specific HTTP headers or all of them with the wildcard `"*"`. ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` The default parameters used by the `CORSMiddleware` implementation are restrictive by default, so you'll need to explicitly enable particular origins, methods, or headers, in order for browsers to be permitted to use them in a Cross-Domain context. diff --git a/docs/en/docs/tutorial/debugging.md b/docs/en/docs/tutorial/debugging.md index c520a631d..6c0177853 100644 --- a/docs/en/docs/tutorial/debugging.md +++ b/docs/en/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ You can connect the debugger in your editor, for example with Visual Studio Code In your FastAPI application, import and run `uvicorn` directly: ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### About `__name__ == "__main__"` diff --git a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md index b3394f14e..defd61a0d 100644 --- a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md @@ -9,7 +9,7 @@ In the previous example, we were returning a `dict` from our dependency ("depend //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ In the previous example, we were returning a `dict` from our dependency ("depend //// tab | Python 3.9+ ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ In the previous example, we were returning a `dict` from our dependency ("depend //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -122,7 +122,7 @@ Then, we can change the dependency "dependable" `common_parameters` from above t //// tab | Python 3.10+ ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -130,7 +130,7 @@ Then, we can change the dependency "dependable" `common_parameters` from above t //// tab | Python 3.9+ ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -138,7 +138,7 @@ Then, we can change the dependency "dependable" `common_parameters` from above t //// tab | Python 3.8+ ```Python hl_lines="12-16" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -152,7 +152,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9-13" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -166,7 +166,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -176,7 +176,7 @@ Pay attention to the `__init__` method used to create the instance of the class: //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -184,7 +184,7 @@ Pay attention to the `__init__` method used to create the instance of the class: //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -192,7 +192,7 @@ Pay attention to the `__init__` method used to create the instance of the class: //// tab | Python 3.8+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -206,7 +206,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -220,7 +220,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -230,7 +230,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -238,7 +238,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -246,7 +246,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -260,7 +260,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="6" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -274,7 +274,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -296,7 +296,7 @@ Now you can declare your dependency using this class. //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -304,7 +304,7 @@ Now you can declare your dependency using this class. //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -312,7 +312,7 @@ Now you can declare your dependency using this class. //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -326,7 +326,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -340,7 +340,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -440,7 +440,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_an_py310.py!} ``` //// @@ -448,7 +448,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial003_an_py39.py!} ``` //// @@ -456,7 +456,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial003_an.py!} +{!> ../../docs_src/dependencies/tutorial003_an.py!} ``` //// @@ -470,7 +470,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_py310.py!} ``` //// @@ -484,7 +484,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003.py!} +{!> ../../docs_src/dependencies/tutorial003.py!} ``` //// @@ -578,7 +578,7 @@ The same example would then look like: //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_an_py310.py!} ``` //// @@ -586,7 +586,7 @@ The same example would then look like: //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial004_an_py39.py!} ``` //// @@ -594,7 +594,7 @@ The same example would then look like: //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial004_an.py!} +{!> ../../docs_src/dependencies/tutorial004_an.py!} ``` //// @@ -608,7 +608,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_py310.py!} ``` //// @@ -622,7 +622,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004.py!} +{!> ../../docs_src/dependencies/tutorial004.py!} ``` //// diff --git a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 7c3ac7922..e89d520be 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -17,7 +17,7 @@ It should be a `list` of `Depends()`: //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ It should be a `list` of `Depends()`: //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -39,7 +39,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -75,7 +75,7 @@ They can declare request requirements (like headers) or other sub-dependencies: //// tab | Python 3.9+ ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ They can declare request requirements (like headers) or other sub-dependencies: //// tab | Python 3.8+ ```Python hl_lines="7 12" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -97,7 +97,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="6 11" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -109,7 +109,7 @@ These dependencies can `raise` exceptions, the same as normal dependencies: //// tab | Python 3.9+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -117,7 +117,7 @@ These dependencies can `raise` exceptions, the same as normal dependencies: //// tab | Python 3.8+ ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -131,7 +131,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -145,7 +145,7 @@ So, you can reuse a normal dependency (that returns a value) you already use som //// tab | Python 3.9+ ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -153,7 +153,7 @@ So, you can reuse a normal dependency (that returns a value) you already use som //// tab | Python 3.8+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -167,7 +167,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md index 2a3ac2237..97da668aa 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md @@ -30,19 +30,19 @@ For example, you could use this to create a database session and close it after Only the code prior to and including the `yield` statement is executed before creating a response: ```Python hl_lines="2-4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` The yielded value is what is injected into *path operations* and other dependencies: ```Python hl_lines="4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` The code following the `yield` statement is executed after the response has been delivered: ```Python hl_lines="5-6" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` /// tip @@ -64,7 +64,7 @@ So, you can look for that specific exception inside the dependency with `except In the same way, you can use `finally` to make sure the exit steps are executed, no matter if there was an exception or not. ```Python hl_lines="3 5" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` ## Sub-dependencies with `yield` @@ -78,7 +78,7 @@ For example, `dependency_c` can have a dependency on `dependency_b`, and `depend //// tab | Python 3.9+ ```Python hl_lines="6 14 22" -{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} ``` //// @@ -86,7 +86,7 @@ For example, `dependency_c` can have a dependency on `dependency_b`, and `depend //// tab | Python 3.8+ ```Python hl_lines="5 13 21" -{!> ../../../docs_src/dependencies/tutorial008_an.py!} +{!> ../../docs_src/dependencies/tutorial008_an.py!} ``` //// @@ -100,7 +100,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="4 12 20" -{!> ../../../docs_src/dependencies/tutorial008.py!} +{!> ../../docs_src/dependencies/tutorial008.py!} ``` //// @@ -114,7 +114,7 @@ And, in turn, `dependency_b` needs the value from `dependency_a` (here named `de //// tab | Python 3.9+ ```Python hl_lines="18-19 26-27" -{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} ``` //// @@ -122,7 +122,7 @@ And, in turn, `dependency_b` needs the value from `dependency_a` (here named `de //// tab | Python 3.8+ ```Python hl_lines="17-18 25-26" -{!> ../../../docs_src/dependencies/tutorial008_an.py!} +{!> ../../docs_src/dependencies/tutorial008_an.py!} ``` //// @@ -136,7 +136,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="16-17 24-25" -{!> ../../../docs_src/dependencies/tutorial008.py!} +{!> ../../docs_src/dependencies/tutorial008.py!} ``` //// @@ -174,7 +174,7 @@ But it's there for you if you need it. 🤓 //// tab | Python 3.9+ ```Python hl_lines="18-22 31" -{!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008b_an_py39.py!} ``` //// @@ -182,7 +182,7 @@ But it's there for you if you need it. 🤓 //// tab | Python 3.8+ ```Python hl_lines="17-21 30" -{!> ../../../docs_src/dependencies/tutorial008b_an.py!} +{!> ../../docs_src/dependencies/tutorial008b_an.py!} ``` //// @@ -196,7 +196,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="16-20 29" -{!> ../../../docs_src/dependencies/tutorial008b.py!} +{!> ../../docs_src/dependencies/tutorial008b.py!} ``` //// @@ -210,7 +210,7 @@ If you catch an exception using `except` in a dependency with `yield` and you do //// tab | Python 3.9+ ```Python hl_lines="15-16" -{!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008c_an_py39.py!} ``` //// @@ -218,7 +218,7 @@ If you catch an exception using `except` in a dependency with `yield` and you do //// tab | Python 3.8+ ```Python hl_lines="14-15" -{!> ../../../docs_src/dependencies/tutorial008c_an.py!} +{!> ../../docs_src/dependencies/tutorial008c_an.py!} ``` //// @@ -232,7 +232,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="13-14" -{!> ../../../docs_src/dependencies/tutorial008c.py!} +{!> ../../docs_src/dependencies/tutorial008c.py!} ``` //// @@ -248,7 +248,7 @@ You can re-raise the same exception using `raise`: //// tab | Python 3.9+ ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial008d_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008d_an_py39.py!} ``` //// @@ -256,7 +256,7 @@ You can re-raise the same exception using `raise`: //// tab | Python 3.8+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial008d_an.py!} +{!> ../../docs_src/dependencies/tutorial008d_an.py!} ``` //// @@ -270,7 +270,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="15" -{!> ../../../docs_src/dependencies/tutorial008d.py!} +{!> ../../docs_src/dependencies/tutorial008d.py!} ``` //// @@ -404,7 +404,7 @@ You can also use them inside of **FastAPI** dependencies with `yield` by using `with` or `async with` statements inside of the dependency function: ```Python hl_lines="1-9 13" -{!../../../docs_src/dependencies/tutorial010.py!} +{!../../docs_src/dependencies/tutorial010.py!} ``` /// tip diff --git a/docs/en/docs/tutorial/dependencies/global-dependencies.md b/docs/en/docs/tutorial/dependencies/global-dependencies.md index 03a9a42f0..21a8cb6be 100644 --- a/docs/en/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/global-dependencies.md @@ -9,7 +9,7 @@ In that case, they will be applied to all the *path operations* in the applicati //// tab | Python 3.9+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} ``` //// @@ -17,7 +17,7 @@ In that case, they will be applied to all the *path operations* in the applicati //// tab | Python 3.8+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial012_an.py!} +{!> ../../docs_src/dependencies/tutorial012_an.py!} ``` //// @@ -31,7 +31,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="15" -{!> ../../../docs_src/dependencies/tutorial012.py!} +{!> ../../docs_src/dependencies/tutorial012.py!} ``` //// diff --git a/docs/en/docs/tutorial/dependencies/index.md b/docs/en/docs/tutorial/dependencies/index.md index a608222f2..b50edb98e 100644 --- a/docs/en/docs/tutorial/dependencies/index.md +++ b/docs/en/docs/tutorial/dependencies/index.md @@ -34,7 +34,7 @@ It is just a function that can take all the same parameters that a *path operati //// tab | Python 3.10+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -42,7 +42,7 @@ It is just a function that can take all the same parameters that a *path operati //// tab | Python 3.9+ ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -50,7 +50,7 @@ It is just a function that can take all the same parameters that a *path operati //// tab | Python 3.8+ ```Python hl_lines="9-12" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -64,7 +64,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -78,7 +78,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -116,7 +116,7 @@ Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgradi //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -124,7 +124,7 @@ Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgradi //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -132,7 +132,7 @@ Make sure you [Upgrade the FastAPI version](../../deployment/versions.md#upgradi //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -146,7 +146,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -160,7 +160,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -172,7 +172,7 @@ The same way you use `Body`, `Query`, etc. with your *path operation function* p //// tab | Python 3.10+ ```Python hl_lines="13 18" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -180,7 +180,7 @@ The same way you use `Body`, `Query`, etc. with your *path operation function* p //// tab | Python 3.9+ ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -188,7 +188,7 @@ The same way you use `Body`, `Query`, etc. with your *path operation function* p //// tab | Python 3.8+ ```Python hl_lines="16 21" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -202,7 +202,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -216,7 +216,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -279,7 +279,7 @@ But because we are using `Annotated`, we can store that `Annotated` value in a v //// tab | Python 3.10+ ```Python hl_lines="12 16 21" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} ``` //// @@ -287,7 +287,7 @@ But because we are using `Annotated`, we can store that `Annotated` value in a v //// tab | Python 3.9+ ```Python hl_lines="14 18 23" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} ``` //// @@ -295,7 +295,7 @@ But because we are using `Annotated`, we can store that `Annotated` value in a v //// tab | Python 3.8+ ```Python hl_lines="15 19 24" -{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an.py!} ``` //// diff --git a/docs/en/docs/tutorial/dependencies/sub-dependencies.md b/docs/en/docs/tutorial/dependencies/sub-dependencies.md index 85b252e13..2b098d159 100644 --- a/docs/en/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/sub-dependencies.md @@ -13,7 +13,7 @@ You could create a first dependency ("dependable") like: //// tab | Python 3.10+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -21,7 +21,7 @@ You could create a first dependency ("dependable") like: //// tab | Python 3.9+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -29,7 +29,7 @@ You could create a first dependency ("dependable") like: //// tab | Python 3.8+ ```Python hl_lines="9-10" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -43,7 +43,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -57,7 +57,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -73,7 +73,7 @@ Then you can create another dependency function (a "dependable") that at the sam //// tab | Python 3.10+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -81,7 +81,7 @@ Then you can create another dependency function (a "dependable") that at the sam //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -89,7 +89,7 @@ Then you can create another dependency function (a "dependable") that at the sam //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -103,7 +103,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -117,7 +117,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -136,7 +136,7 @@ Then we can use the dependency with: //// tab | Python 3.10+ ```Python hl_lines="23" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -144,7 +144,7 @@ Then we can use the dependency with: //// tab | Python 3.9+ ```Python hl_lines="23" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -152,7 +152,7 @@ Then we can use the dependency with: //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -166,7 +166,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -180,7 +180,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="22" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// diff --git a/docs/en/docs/tutorial/encoder.md b/docs/en/docs/tutorial/encoder.md index c110a2ac5..039ac6714 100644 --- a/docs/en/docs/tutorial/encoder.md +++ b/docs/en/docs/tutorial/encoder.md @@ -23,7 +23,7 @@ It receives an object, like a Pydantic model, and returns a JSON compatible vers //// tab | Python 3.10+ ```Python hl_lines="4 21" -{!> ../../../docs_src/encoder/tutorial001_py310.py!} +{!> ../../docs_src/encoder/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ It receives an object, like a Pydantic model, and returns a JSON compatible vers //// tab | Python 3.8+ ```Python hl_lines="5 22" -{!> ../../../docs_src/encoder/tutorial001.py!} +{!> ../../docs_src/encoder/tutorial001.py!} ``` //// diff --git a/docs/en/docs/tutorial/extra-data-types.md b/docs/en/docs/tutorial/extra-data-types.md index 3009acaf3..65f9f1085 100644 --- a/docs/en/docs/tutorial/extra-data-types.md +++ b/docs/en/docs/tutorial/extra-data-types.md @@ -58,7 +58,7 @@ Here's an example *path operation* with parameters using some of the above types //// tab | Python 3.10+ ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} ``` //// @@ -66,7 +66,7 @@ Here's an example *path operation* with parameters using some of the above types //// tab | Python 3.9+ ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` //// @@ -74,7 +74,7 @@ Here's an example *path operation* with parameters using some of the above types //// tab | Python 3.8+ ```Python hl_lines="1 3 13-17" -{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} ``` //// @@ -88,7 +88,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1 2 11-15" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -102,7 +102,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1 2 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// @@ -112,7 +112,7 @@ Note that the parameters inside the function have their natural data type, and y //// tab | Python 3.10+ ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} ``` //// @@ -120,7 +120,7 @@ Note that the parameters inside the function have their natural data type, and y //// tab | Python 3.9+ ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` //// @@ -128,7 +128,7 @@ Note that the parameters inside the function have their natural data type, and y //// tab | Python 3.8+ ```Python hl_lines="19-20" -{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} ``` //// @@ -142,7 +142,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="17-18" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -156,7 +156,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// diff --git a/docs/en/docs/tutorial/extra-models.md b/docs/en/docs/tutorial/extra-models.md index 1c87e76ce..4e6f69f31 100644 --- a/docs/en/docs/tutorial/extra-models.md +++ b/docs/en/docs/tutorial/extra-models.md @@ -23,7 +23,7 @@ Here's a general idea of how the models could look like with their password fiel //// tab | Python 3.10+ ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +{!> ../../docs_src/extra_models/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ Here's a general idea of how the models could look like with their password fiel //// tab | Python 3.8+ ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../../docs_src/extra_models/tutorial001.py!} +{!> ../../docs_src/extra_models/tutorial001.py!} ``` //// @@ -179,7 +179,7 @@ That way, we can declare just the differences between the models (with plaintext //// tab | Python 3.10+ ```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +{!> ../../docs_src/extra_models/tutorial002_py310.py!} ``` //// @@ -187,7 +187,7 @@ That way, we can declare just the differences between the models (with plaintext //// tab | Python 3.8+ ```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../../docs_src/extra_models/tutorial002.py!} +{!> ../../docs_src/extra_models/tutorial002.py!} ``` //// @@ -209,7 +209,7 @@ When defining a ../../../docs_src/extra_models/tutorial003_py310.py!} +{!> ../../docs_src/extra_models/tutorial003_py310.py!} ``` //// @@ -217,7 +217,7 @@ When defining a ../../../docs_src/extra_models/tutorial003.py!} +{!> ../../docs_src/extra_models/tutorial003.py!} ``` //// @@ -245,7 +245,7 @@ For that, use the standard Python `typing.List` (or just `list` in Python 3.9 an //// tab | Python 3.9+ ```Python hl_lines="18" -{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +{!> ../../docs_src/extra_models/tutorial004_py39.py!} ``` //// @@ -253,7 +253,7 @@ For that, use the standard Python `typing.List` (or just `list` in Python 3.9 an //// tab | Python 3.8+ ```Python hl_lines="1 20" -{!> ../../../docs_src/extra_models/tutorial004.py!} +{!> ../../docs_src/extra_models/tutorial004.py!} ``` //// @@ -269,7 +269,7 @@ In this case, you can use `typing.Dict` (or just `dict` in Python 3.9 and above) //// tab | Python 3.9+ ```Python hl_lines="6" -{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +{!> ../../docs_src/extra_models/tutorial005_py39.py!} ``` //// @@ -277,7 +277,7 @@ In this case, you can use `typing.Dict` (or just `dict` in Python 3.9 and above) //// tab | Python 3.8+ ```Python hl_lines="1 8" -{!> ../../../docs_src/extra_models/tutorial005.py!} +{!> ../../docs_src/extra_models/tutorial005.py!} ``` //// diff --git a/docs/en/docs/tutorial/first-steps.md b/docs/en/docs/tutorial/first-steps.md index b48a0ee38..77728cebe 100644 --- a/docs/en/docs/tutorial/first-steps.md +++ b/docs/en/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ The simplest FastAPI file could look like this: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Copy that to a file `main.py`. @@ -158,7 +158,7 @@ You could also use it to generate code automatically, for clients that communica ### Step 1: import `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` is a Python class that provides all the functionality for your API. @@ -174,7 +174,7 @@ You can use all the ../../../docs_src/header_param_models/tutorial001_an_py310.py!} +{!> ../../docs_src/header_param_models/tutorial001_an_py310.py!} ``` //// @@ -25,7 +25,7 @@ Declare the **header parameters** that you need in a **Pydantic model**, and the //// tab | Python 3.9+ ```Python hl_lines="9-14 18" -{!> ../../../docs_src/header_param_models/tutorial001_an_py39.py!} +{!> ../../docs_src/header_param_models/tutorial001_an_py39.py!} ``` //// @@ -33,7 +33,7 @@ Declare the **header parameters** that you need in a **Pydantic model**, and the //// tab | Python 3.8+ ```Python hl_lines="10-15 19" -{!> ../../../docs_src/header_param_models/tutorial001_an.py!} +{!> ../../docs_src/header_param_models/tutorial001_an.py!} ``` //// @@ -47,7 +47,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7-12 16" -{!> ../../../docs_src/header_param_models/tutorial001_py310.py!} +{!> ../../docs_src/header_param_models/tutorial001_py310.py!} ``` //// @@ -61,7 +61,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9-14 18" -{!> ../../../docs_src/header_param_models/tutorial001_py39.py!} +{!> ../../docs_src/header_param_models/tutorial001_py39.py!} ``` //// @@ -75,7 +75,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7-12 16" -{!> ../../../docs_src/header_param_models/tutorial001_py310.py!} +{!> ../../docs_src/header_param_models/tutorial001_py310.py!} ``` //// @@ -99,7 +99,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/header_param_models/tutorial002_an_py310.py!} +{!> ../../docs_src/header_param_models/tutorial002_an_py310.py!} ``` //// @@ -107,7 +107,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/header_param_models/tutorial002_an_py39.py!} +{!> ../../docs_src/header_param_models/tutorial002_an_py39.py!} ``` //// @@ -115,7 +115,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/header_param_models/tutorial002_an.py!} +{!> ../../docs_src/header_param_models/tutorial002_an.py!} ``` //// @@ -129,7 +129,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/header_param_models/tutorial002_py310.py!} +{!> ../../docs_src/header_param_models/tutorial002_py310.py!} ``` //// @@ -143,7 +143,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/header_param_models/tutorial002_py39.py!} +{!> ../../docs_src/header_param_models/tutorial002_py39.py!} ``` //// @@ -157,7 +157,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/header_param_models/tutorial002.py!} +{!> ../../docs_src/header_param_models/tutorial002.py!} ``` //// diff --git a/docs/en/docs/tutorial/header-params.md b/docs/en/docs/tutorial/header-params.md index 2e07fe0e6..293de897f 100644 --- a/docs/en/docs/tutorial/header-params.md +++ b/docs/en/docs/tutorial/header-params.md @@ -9,7 +9,7 @@ First import `Header`: //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +{!> ../../docs_src/header_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ First import `Header`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +{!> ../../docs_src/header_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ First import `Header`: //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001_an.py!} +{!> ../../docs_src/header_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1" -{!> ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -67,7 +67,7 @@ You can define the default value as well as all the extra validation or annotati //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +{!> ../../docs_src/header_params/tutorial001_an_py310.py!} ``` //// @@ -75,7 +75,7 @@ You can define the default value as well as all the extra validation or annotati //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +{!> ../../docs_src/header_params/tutorial001_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ You can define the default value as well as all the extra validation or annotati //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial001_an.py!} +{!> ../../docs_src/header_params/tutorial001_an.py!} ``` //// @@ -97,7 +97,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -111,7 +111,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -149,7 +149,7 @@ If for some reason you need to disable automatic conversion of underscores to hy //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial002_an_py310.py!} +{!> ../../docs_src/header_params/tutorial002_an_py310.py!} ``` //// @@ -157,7 +157,7 @@ If for some reason you need to disable automatic conversion of underscores to hy //// tab | Python 3.9+ ```Python hl_lines="11" -{!> ../../../docs_src/header_params/tutorial002_an_py39.py!} +{!> ../../docs_src/header_params/tutorial002_an_py39.py!} ``` //// @@ -165,7 +165,7 @@ If for some reason you need to disable automatic conversion of underscores to hy //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/header_params/tutorial002_an.py!} +{!> ../../docs_src/header_params/tutorial002_an.py!} ``` //// @@ -179,7 +179,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/header_params/tutorial002_py310.py!} +{!> ../../docs_src/header_params/tutorial002_py310.py!} ``` //// @@ -193,7 +193,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial002.py!} +{!> ../../docs_src/header_params/tutorial002.py!} ``` //// @@ -217,7 +217,7 @@ For example, to declare a header of `X-Token` that can appear more than once, yo //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_an_py310.py!} +{!> ../../docs_src/header_params/tutorial003_an_py310.py!} ``` //// @@ -225,7 +225,7 @@ For example, to declare a header of `X-Token` that can appear more than once, yo //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_an_py39.py!} +{!> ../../docs_src/header_params/tutorial003_an_py39.py!} ``` //// @@ -233,7 +233,7 @@ For example, to declare a header of `X-Token` that can appear more than once, yo //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial003_an.py!} +{!> ../../docs_src/header_params/tutorial003_an.py!} ``` //// @@ -247,7 +247,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial003_py310.py!} +{!> ../../docs_src/header_params/tutorial003_py310.py!} ``` //// @@ -261,7 +261,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_py39.py!} +{!> ../../docs_src/header_params/tutorial003_py39.py!} ``` //// @@ -275,7 +275,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003.py!} +{!> ../../docs_src/header_params/tutorial003.py!} ``` //// diff --git a/docs/en/docs/tutorial/metadata.md b/docs/en/docs/tutorial/metadata.md index c62509b8b..715bb999a 100644 --- a/docs/en/docs/tutorial/metadata.md +++ b/docs/en/docs/tutorial/metadata.md @@ -19,7 +19,7 @@ You can set the following fields that are used in the OpenAPI specification and You can set them as follows: ```Python hl_lines="3-16 19-32" -{!../../../docs_src/metadata/tutorial001.py!} +{!../../docs_src/metadata/tutorial001.py!} ``` /// tip @@ -39,7 +39,7 @@ Since OpenAPI 3.1.0 and FastAPI 0.99.0, you can also set the `license_info` with For example: ```Python hl_lines="31" -{!../../../docs_src/metadata/tutorial001_1.py!} +{!../../docs_src/metadata/tutorial001_1.py!} ``` ## Metadata for tags @@ -63,7 +63,7 @@ Let's try that in an example with tags for `users` and `items`. Create metadata for your tags and pass it to the `openapi_tags` parameter: ```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` Notice that you can use Markdown inside of the descriptions, for example "login" will be shown in bold (**login**) and "fancy" will be shown in italics (_fancy_). @@ -79,7 +79,7 @@ You don't have to add metadata for all the tags that you use. Use the `tags` parameter with your *path operations* (and `APIRouter`s) to assign them to different tags: ```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` /// info @@ -109,7 +109,7 @@ But you can configure it with the parameter `openapi_url`. For example, to set it to be served at `/api/v1/openapi.json`: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} +{!../../docs_src/metadata/tutorial002.py!} ``` If you want to disable the OpenAPI schema completely you can set `openapi_url=None`, that will also disable the documentation user interfaces that use it. @@ -128,5 +128,5 @@ You can configure the two documentation user interfaces included: For example, to set Swagger UI to be served at `/documentation` and disable ReDoc: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} +{!../../docs_src/metadata/tutorial003.py!} ``` diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index 199b593d3..7c4954c7b 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -32,7 +32,7 @@ The middleware function receives: * You can then further modify the `response` before returning it. ```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` /// tip @@ -60,7 +60,7 @@ And also after the `response` is generated, before returning it. For example, you could add a custom header `X-Process-Time` containing the time in seconds that it took to process the request and generate a response: ```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` /// tip diff --git a/docs/en/docs/tutorial/path-operation-configuration.md b/docs/en/docs/tutorial/path-operation-configuration.md index a1a4953a6..4ca6ebf13 100644 --- a/docs/en/docs/tutorial/path-operation-configuration.md +++ b/docs/en/docs/tutorial/path-operation-configuration.md @@ -19,7 +19,7 @@ But if you don't remember what each number code is for, you can use the shortcut //// tab | Python 3.10+ ```Python hl_lines="1 15" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} ``` //// @@ -27,7 +27,7 @@ But if you don't remember what each number code is for, you can use the shortcut //// tab | Python 3.9+ ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} ``` //// @@ -35,7 +35,7 @@ But if you don't remember what each number code is for, you can use the shortcut //// tab | Python 3.8+ ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001.py!} ``` //// @@ -57,7 +57,7 @@ You can add tags to your *path operation*, pass the parameter `tags` with a `lis //// tab | Python 3.10+ ```Python hl_lines="15 20 25" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} ``` //// @@ -65,7 +65,7 @@ You can add tags to your *path operation*, pass the parameter `tags` with a `lis //// tab | Python 3.9+ ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} ``` //// @@ -73,7 +73,7 @@ You can add tags to your *path operation*, pass the parameter `tags` with a `lis //// tab | Python 3.8+ ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002.py!} ``` //// @@ -91,7 +91,7 @@ In these cases, it could make sense to store the tags in an `Enum`. **FastAPI** supports that the same way as with plain strings: ```Python hl_lines="1 8-10 13 18" -{!../../../docs_src/path_operation_configuration/tutorial002b.py!} +{!../../docs_src/path_operation_configuration/tutorial002b.py!} ``` ## Summary and description @@ -101,7 +101,7 @@ You can add a `summary` and `description`: //// tab | Python 3.10+ ```Python hl_lines="18-19" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} ``` //// @@ -109,7 +109,7 @@ You can add a `summary` and `description`: //// tab | Python 3.9+ ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} ``` //// @@ -117,7 +117,7 @@ You can add a `summary` and `description`: //// tab | Python 3.8+ ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003.py!} ``` //// @@ -131,7 +131,7 @@ You can write ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} ``` //// @@ -139,7 +139,7 @@ You can write ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} ``` //// @@ -147,7 +147,7 @@ You can write ../../../docs_src/path_operation_configuration/tutorial004.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004.py!} ``` //// @@ -163,7 +163,7 @@ You can specify the response description with the parameter `response_descriptio //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} ``` //// @@ -171,7 +171,7 @@ You can specify the response description with the parameter `response_descriptio //// tab | Python 3.9+ ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} ``` //// @@ -179,7 +179,7 @@ You can specify the response description with the parameter `response_descriptio //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005.py!} ``` //// @@ -205,7 +205,7 @@ So, if you don't provide one, **FastAPI** will automatically generate one of "Su If you need to mark a *path operation* as deprecated, but without removing it, pass the parameter `deprecated`: ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` It will be clearly marked as deprecated in the interactive docs: diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md index bd835d0d4..9ddf49ea9 100644 --- a/docs/en/docs/tutorial/path-params-numeric-validations.md +++ b/docs/en/docs/tutorial/path-params-numeric-validations.md @@ -9,7 +9,7 @@ First, import `Path` from `fastapi`, and import `Annotated`: //// tab | Python 3.10+ ```Python hl_lines="1 3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ First, import `Path` from `fastapi`, and import `Annotated`: //// tab | Python 3.9+ ```Python hl_lines="1 3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ First, import `Path` from `fastapi`, and import `Annotated`: //// tab | Python 3.8+ ```Python hl_lines="3-4" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -77,7 +77,7 @@ For example, to declare a `title` metadata value for the path parameter `item_id //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} ``` //// @@ -85,7 +85,7 @@ For example, to declare a `title` metadata value for the path parameter `item_id //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` //// @@ -93,7 +93,7 @@ For example, to declare a `title` metadata value for the path parameter `item_id //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} ``` //// @@ -107,7 +107,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -121,7 +121,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -163,7 +163,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` //// @@ -173,7 +173,7 @@ But keep in mind that if you use `Annotated`, you won't have this problem, it wo //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} ``` //// @@ -181,7 +181,7 @@ But keep in mind that if you use `Annotated`, you won't have this problem, it wo //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002_an.py!} ``` //// @@ -210,7 +210,7 @@ Pass `*`, as the first parameter of the function. Python won't do anything with that `*`, but it will know that all the following parameters should be called as keyword arguments (key-value pairs), also known as kwargs. Even if they don't have a default value. ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ### Better with `Annotated` @@ -220,7 +220,7 @@ Keep in mind that if you use `Annotated`, as you are not using function paramete //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} ``` //// @@ -228,7 +228,7 @@ Keep in mind that if you use `Annotated`, as you are not using function paramete //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial003_an.py!} ``` //// @@ -242,7 +242,7 @@ Here, with `ge=1`, `item_id` will need to be an integer number "`g`reater than o //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} ``` //// @@ -250,7 +250,7 @@ Here, with `ge=1`, `item_id` will need to be an integer number "`g`reater than o //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!} ``` //// @@ -264,7 +264,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` //// @@ -279,7 +279,7 @@ The same applies for: //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} ``` //// @@ -287,7 +287,7 @@ The same applies for: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005_an.py!} ``` //// @@ -301,7 +301,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` //// @@ -319,7 +319,7 @@ And the same for lt. //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} ``` //// @@ -327,7 +327,7 @@ And the same for lt. //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.py!} ``` //// @@ -341,7 +341,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` //// diff --git a/docs/en/docs/tutorial/path-params.md b/docs/en/docs/tutorial/path-params.md index a87a29e08..fd9e74585 100644 --- a/docs/en/docs/tutorial/path-params.md +++ b/docs/en/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ You can declare path "parameters" or "variables" with the same syntax used by Python format strings: ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` The value of the path parameter `item_id` will be passed to your function as the argument `item_id`. @@ -19,7 +19,7 @@ So, if you run this example and go to ../../../docs_src/query_param_models/tutorial001_an_py310.py!} +{!> ../../docs_src/query_param_models/tutorial001_an_py310.py!} ``` //// @@ -25,7 +25,7 @@ Declare the **query parameters** that you need in a **Pydantic model**, and then //// tab | Python 3.9+ ```Python hl_lines="8-12 16" -{!> ../../../docs_src/query_param_models/tutorial001_an_py39.py!} +{!> ../../docs_src/query_param_models/tutorial001_an_py39.py!} ``` //// @@ -33,7 +33,7 @@ Declare the **query parameters** that you need in a **Pydantic model**, and then //// tab | Python 3.8+ ```Python hl_lines="10-14 18" -{!> ../../../docs_src/query_param_models/tutorial001_an.py!} +{!> ../../docs_src/query_param_models/tutorial001_an.py!} ``` //// @@ -47,7 +47,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9-13 17" -{!> ../../../docs_src/query_param_models/tutorial001_py310.py!} +{!> ../../docs_src/query_param_models/tutorial001_py310.py!} ``` //// @@ -61,7 +61,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8-12 16" -{!> ../../../docs_src/query_param_models/tutorial001_py39.py!} +{!> ../../docs_src/query_param_models/tutorial001_py39.py!} ``` //// @@ -75,7 +75,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9-13 17" -{!> ../../../docs_src/query_param_models/tutorial001_py310.py!} +{!> ../../docs_src/query_param_models/tutorial001_py310.py!} ``` //// @@ -99,7 +99,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_param_models/tutorial002_an_py310.py!} +{!> ../../docs_src/query_param_models/tutorial002_an_py310.py!} ``` //// @@ -107,7 +107,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_param_models/tutorial002_an_py39.py!} +{!> ../../docs_src/query_param_models/tutorial002_an_py39.py!} ``` //// @@ -115,7 +115,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_param_models/tutorial002_an.py!} +{!> ../../docs_src/query_param_models/tutorial002_an.py!} ``` //// @@ -129,7 +129,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/query_param_models/tutorial002_py310.py!} +{!> ../../docs_src/query_param_models/tutorial002_py310.py!} ``` //// @@ -143,7 +143,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_param_models/tutorial002_py39.py!} +{!> ../../docs_src/query_param_models/tutorial002_py39.py!} ``` //// @@ -157,7 +157,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11" -{!> ../../../docs_src/query_param_models/tutorial002.py!} +{!> ../../docs_src/query_param_models/tutorial002.py!} ``` //// diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index dd101a2a6..12778d7fe 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -7,7 +7,7 @@ Let's take this application as example: //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} ``` //// @@ -15,7 +15,7 @@ Let's take this application as example: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial001.py!} +{!> ../../docs_src/query_params_str_validations/tutorial001.py!} ``` //// @@ -46,7 +46,7 @@ To achieve that, first import: In Python 3.9 or above, `Annotated` is part of the standard library, so you can import it from `typing`. ```Python hl_lines="1 3" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} ``` //// @@ -58,7 +58,7 @@ In versions of Python below Python 3.9 you import `Annotated` from `typing_exten It will already be installed with FastAPI. ```Python hl_lines="3-4" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} ``` //// @@ -126,7 +126,7 @@ Now that we have this `Annotated` where we can put more information (in this cas //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} ``` //// @@ -134,7 +134,7 @@ Now that we have this `Annotated` where we can put more information (in this cas //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} ``` //// @@ -170,7 +170,7 @@ This is how you would use `Query()` as the default value of your function parame //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} ``` //// @@ -178,7 +178,7 @@ This is how you would use `Query()` as the default value of your function parame //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002.py!} ``` //// @@ -284,7 +284,7 @@ You can also add a parameter `min_length`: //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} ``` //// @@ -292,7 +292,7 @@ You can also add a parameter `min_length`: //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} ``` //// @@ -300,7 +300,7 @@ You can also add a parameter `min_length`: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_an.py!} ``` //// @@ -314,7 +314,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} ``` //// @@ -328,7 +328,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003.py!} ``` //// @@ -340,7 +340,7 @@ You can define a ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} ``` //// @@ -348,7 +348,7 @@ You can define a ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} ``` //// @@ -356,7 +356,7 @@ You can define a ../../../docs_src/query_params_str_validations/tutorial004_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an.py!} ``` //// @@ -370,7 +370,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} ``` //// @@ -384,7 +384,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial004.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004.py!} ``` //// @@ -408,7 +408,7 @@ You could still see some code using it: //// tab | Python 3.10+ Pydantic v1 ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} ``` //// @@ -424,7 +424,7 @@ Let's say that you want to declare the `q` query parameter to have a `min_length //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} ``` //// @@ -432,7 +432,7 @@ Let's say that you want to declare the `q` query parameter to have a `min_length //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial005_an.py!} ``` //// @@ -446,7 +446,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial005.py!} +{!> ../../docs_src/query_params_str_validations/tutorial005.py!} ``` //// @@ -494,7 +494,7 @@ So, when you need to declare a value as required while using `Query`, you can si //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} ``` //// @@ -502,7 +502,7 @@ So, when you need to declare a value as required while using `Query`, you can si //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006_an.py!} ``` //// @@ -516,7 +516,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006.py!} ``` /// tip @@ -536,7 +536,7 @@ There's an alternative way to explicitly declare that a value is required. You c //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} ``` //// @@ -544,7 +544,7 @@ There's an alternative way to explicitly declare that a value is required. You c //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006b_an.py!} ``` //// @@ -558,7 +558,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006b.py!} ``` //// @@ -582,7 +582,7 @@ To do that, you can declare that `None` is a valid type but still use `...` as t //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} ``` //// @@ -590,7 +590,7 @@ To do that, you can declare that `None` is a valid type but still use `...` as t //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} ``` //// @@ -598,7 +598,7 @@ To do that, you can declare that `None` is a valid type but still use `...` as t //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_an.py!} ``` //// @@ -612,7 +612,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} ``` //// @@ -626,7 +626,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} ``` //// @@ -652,7 +652,7 @@ For example, to declare a query parameter `q` that can appear multiple times in //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} ``` //// @@ -660,7 +660,7 @@ For example, to declare a query parameter `q` that can appear multiple times in //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} ``` //// @@ -668,7 +668,7 @@ For example, to declare a query parameter `q` that can appear multiple times in //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_an.py!} ``` //// @@ -682,7 +682,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} ``` //// @@ -696,7 +696,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} ``` //// @@ -710,7 +710,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011.py!} ``` //// @@ -751,7 +751,7 @@ And you can also define a default `list` of values if none are provided: //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} ``` //// @@ -759,7 +759,7 @@ And you can also define a default `list` of values if none are provided: //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_an.py!} ``` //// @@ -773,7 +773,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} ``` //// @@ -787,7 +787,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial012.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012.py!} ``` //// @@ -816,7 +816,7 @@ You can also use `list` directly instead of `List[str]` (or `list[str]` in Pytho //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} ``` //// @@ -824,7 +824,7 @@ You can also use `list` directly instead of `List[str]` (or `list[str]` in Pytho //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial013_an.py!} ``` //// @@ -838,7 +838,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial013.py!} +{!> ../../docs_src/query_params_str_validations/tutorial013.py!} ``` //// @@ -870,7 +870,7 @@ You can add a `title`: //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} ``` //// @@ -878,7 +878,7 @@ You can add a `title`: //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} ``` //// @@ -886,7 +886,7 @@ You can add a `title`: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_an.py!} ``` //// @@ -900,7 +900,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} ``` //// @@ -914,7 +914,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007.py!} ``` //// @@ -924,7 +924,7 @@ And a `description`: //// tab | Python 3.10+ ```Python hl_lines="14" -{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} ``` //// @@ -932,7 +932,7 @@ And a `description`: //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} ``` //// @@ -940,7 +940,7 @@ And a `description`: //// tab | Python 3.8+ ```Python hl_lines="15" -{!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_an.py!} ``` //// @@ -954,7 +954,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} ``` //// @@ -968,7 +968,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="13" -{!> ../../../docs_src/query_params_str_validations/tutorial008.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008.py!} ``` //// @@ -994,7 +994,7 @@ Then you can declare an `alias`, and that alias is what will be used to find the //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} ``` //// @@ -1002,7 +1002,7 @@ Then you can declare an `alias`, and that alias is what will be used to find the //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} ``` //// @@ -1010,7 +1010,7 @@ Then you can declare an `alias`, and that alias is what will be used to find the //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_an.py!} ``` //// @@ -1024,7 +1024,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} ``` //// @@ -1038,7 +1038,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009.py!} ``` //// @@ -1054,7 +1054,7 @@ Then pass the parameter `deprecated=True` to `Query`: //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} ``` //// @@ -1062,7 +1062,7 @@ Then pass the parameter `deprecated=True` to `Query`: //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} ``` //// @@ -1070,7 +1070,7 @@ Then pass the parameter `deprecated=True` to `Query`: //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_an.py!} ``` //// @@ -1084,7 +1084,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="16" -{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} ``` //// @@ -1098,7 +1098,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="18" -{!> ../../../docs_src/query_params_str_validations/tutorial010.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010.py!} ``` //// @@ -1114,7 +1114,7 @@ To exclude a query parameter from the generated OpenAPI schema (and thus, from t //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} ``` //// @@ -1122,7 +1122,7 @@ To exclude a query parameter from the generated OpenAPI schema (and thus, from t //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} ``` //// @@ -1130,7 +1130,7 @@ To exclude a query parameter from the generated OpenAPI schema (and thus, from t //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!} ``` //// @@ -1144,7 +1144,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} ``` //// @@ -1158,7 +1158,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014.py!} ``` //// diff --git a/docs/en/docs/tutorial/query-params.md b/docs/en/docs/tutorial/query-params.md index a98ac9b28..0d31d453d 100644 --- a/docs/en/docs/tutorial/query-params.md +++ b/docs/en/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ When you declare other function parameters that are not part of the path parameters, they are automatically interpreted as "query" parameters. ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` The query is the set of key-value pairs that go after the `?` in a URL, separated by `&` characters. @@ -66,7 +66,7 @@ The same way, you can declare optional query parameters, by setting their defaul //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial002_py310.py!} +{!> ../../docs_src/query_params/tutorial002_py310.py!} ``` //// @@ -74,7 +74,7 @@ The same way, you can declare optional query parameters, by setting their defaul //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial002.py!} +{!> ../../docs_src/query_params/tutorial002.py!} ``` //// @@ -94,7 +94,7 @@ You can also declare `bool` types, and they will be converted: //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial003_py310.py!} +{!> ../../docs_src/query_params/tutorial003_py310.py!} ``` //// @@ -102,7 +102,7 @@ You can also declare `bool` types, and they will be converted: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial003.py!} +{!> ../../docs_src/query_params/tutorial003.py!} ``` //// @@ -151,7 +151,7 @@ They will be detected by name: //// tab | Python 3.10+ ```Python hl_lines="6 8" -{!> ../../../docs_src/query_params/tutorial004_py310.py!} +{!> ../../docs_src/query_params/tutorial004_py310.py!} ``` //// @@ -159,7 +159,7 @@ They will be detected by name: //// tab | Python 3.8+ ```Python hl_lines="8 10" -{!> ../../../docs_src/query_params/tutorial004.py!} +{!> ../../docs_src/query_params/tutorial004.py!} ``` //// @@ -173,7 +173,7 @@ If you don't want to add a specific value but just make it optional, set the def But when you want to make a query parameter required, you can just not declare any default value: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` Here the query parameter `needy` is a required query parameter of type `str`. @@ -223,7 +223,7 @@ And of course, you can define some parameters as required, some as having a defa //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params/tutorial006_py310.py!} +{!> ../../docs_src/query_params/tutorial006_py310.py!} ``` //// @@ -231,7 +231,7 @@ And of course, you can define some parameters as required, some as having a defa //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params/tutorial006.py!} +{!> ../../docs_src/query_params/tutorial006.py!} ``` //// diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md index 9f19596a8..f3f1eb103 100644 --- a/docs/en/docs/tutorial/request-files.md +++ b/docs/en/docs/tutorial/request-files.md @@ -23,7 +23,7 @@ Import `File` and `UploadFile` from `fastapi`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -31,7 +31,7 @@ Import `File` and `UploadFile` from `fastapi`: //// tab | Python 3.8+ ```Python hl_lines="1" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -45,7 +45,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -57,7 +57,7 @@ Create file parameters the same way you would for `Body` or `Form`: //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -65,7 +65,7 @@ Create file parameters the same way you would for `Body` or `Form`: //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -79,7 +79,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -113,7 +113,7 @@ Define a file parameter with a type of `UploadFile`: //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -121,7 +121,7 @@ Define a file parameter with a type of `UploadFile`: //// tab | Python 3.8+ ```Python hl_lines="13" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -135,7 +135,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="12" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -224,7 +224,7 @@ You can make a file optional by using standard type annotations and setting a de //// tab | Python 3.10+ ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} +{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} ``` //// @@ -232,7 +232,7 @@ You can make a file optional by using standard type annotations and setting a de //// tab | Python 3.9+ ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} ``` //// @@ -240,7 +240,7 @@ You can make a file optional by using standard type annotations and setting a de //// tab | Python 3.8+ ```Python hl_lines="10 18" -{!> ../../../docs_src/request_files/tutorial001_02_an.py!} +{!> ../../docs_src/request_files/tutorial001_02_an.py!} ``` //// @@ -254,7 +254,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7 15" -{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +{!> ../../docs_src/request_files/tutorial001_02_py310.py!} ``` //// @@ -268,7 +268,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02.py!} +{!> ../../docs_src/request_files/tutorial001_02.py!} ``` //// @@ -280,7 +280,7 @@ You can also use `File()` with `UploadFile`, for example, to set additional meta //// tab | Python 3.9+ ```Python hl_lines="9 15" -{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} ``` //// @@ -288,7 +288,7 @@ You can also use `File()` with `UploadFile`, for example, to set additional meta //// tab | Python 3.8+ ```Python hl_lines="8 14" -{!> ../../../docs_src/request_files/tutorial001_03_an.py!} +{!> ../../docs_src/request_files/tutorial001_03_an.py!} ``` //// @@ -302,7 +302,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7 13" -{!> ../../../docs_src/request_files/tutorial001_03.py!} +{!> ../../docs_src/request_files/tutorial001_03.py!} ``` //// @@ -318,7 +318,7 @@ To use that, declare a list of `bytes` or `UploadFile`: //// tab | Python 3.9+ ```Python hl_lines="10 15" -{!> ../../../docs_src/request_files/tutorial002_an_py39.py!} +{!> ../../docs_src/request_files/tutorial002_an_py39.py!} ``` //// @@ -326,7 +326,7 @@ To use that, declare a list of `bytes` or `UploadFile`: //// tab | Python 3.8+ ```Python hl_lines="11 16" -{!> ../../../docs_src/request_files/tutorial002_an.py!} +{!> ../../docs_src/request_files/tutorial002_an.py!} ``` //// @@ -340,7 +340,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8 13" -{!> ../../../docs_src/request_files/tutorial002_py39.py!} +{!> ../../docs_src/request_files/tutorial002_py39.py!} ``` //// @@ -354,7 +354,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10 15" -{!> ../../../docs_src/request_files/tutorial002.py!} +{!> ../../docs_src/request_files/tutorial002.py!} ``` //// @@ -376,7 +376,7 @@ And the same way as before, you can use `File()` to set additional parameters, e //// tab | Python 3.9+ ```Python hl_lines="11 18-20" -{!> ../../../docs_src/request_files/tutorial003_an_py39.py!} +{!> ../../docs_src/request_files/tutorial003_an_py39.py!} ``` //// @@ -384,7 +384,7 @@ And the same way as before, you can use `File()` to set additional parameters, e //// tab | Python 3.8+ ```Python hl_lines="12 19-21" -{!> ../../../docs_src/request_files/tutorial003_an.py!} +{!> ../../docs_src/request_files/tutorial003_an.py!} ``` //// @@ -398,7 +398,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9 16" -{!> ../../../docs_src/request_files/tutorial003_py39.py!} +{!> ../../docs_src/request_files/tutorial003_py39.py!} ``` //// @@ -412,7 +412,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11 18" -{!> ../../../docs_src/request_files/tutorial003.py!} +{!> ../../docs_src/request_files/tutorial003.py!} ``` //// diff --git a/docs/en/docs/tutorial/request-form-models.md b/docs/en/docs/tutorial/request-form-models.md index 1440d17b8..f1142877a 100644 --- a/docs/en/docs/tutorial/request-form-models.md +++ b/docs/en/docs/tutorial/request-form-models.md @@ -27,7 +27,7 @@ You just need to declare a **Pydantic model** with the fields you want to receiv //// tab | Python 3.9+ ```Python hl_lines="9-11 15" -{!> ../../../docs_src/request_form_models/tutorial001_an_py39.py!} +{!> ../../docs_src/request_form_models/tutorial001_an_py39.py!} ``` //// @@ -35,7 +35,7 @@ You just need to declare a **Pydantic model** with the fields you want to receiv //// tab | Python 3.8+ ```Python hl_lines="8-10 14" -{!> ../../../docs_src/request_form_models/tutorial001_an.py!} +{!> ../../docs_src/request_form_models/tutorial001_an.py!} ``` //// @@ -49,7 +49,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7-9 13" -{!> ../../../docs_src/request_form_models/tutorial001.py!} +{!> ../../docs_src/request_form_models/tutorial001.py!} ``` //// @@ -79,7 +79,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/request_form_models/tutorial002_an_py39.py!} +{!> ../../docs_src/request_form_models/tutorial002_an_py39.py!} ``` //// @@ -87,7 +87,7 @@ You can use Pydantic's model configuration to `forbid` any `extra` fields: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/request_form_models/tutorial002_an.py!} +{!> ../../docs_src/request_form_models/tutorial002_an.py!} ``` //// @@ -101,7 +101,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/request_form_models/tutorial002.py!} +{!> ../../docs_src/request_form_models/tutorial002.py!} ``` //// diff --git a/docs/en/docs/tutorial/request-forms-and-files.md b/docs/en/docs/tutorial/request-forms-and-files.md index 7830a2ba4..d60fc4c00 100644 --- a/docs/en/docs/tutorial/request-forms-and-files.md +++ b/docs/en/docs/tutorial/request-forms-and-files.md @@ -19,7 +19,7 @@ $ pip install python-multipart //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} ``` //// @@ -27,7 +27,7 @@ $ pip install python-multipart //// tab | Python 3.8+ ```Python hl_lines="1" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} ``` //// @@ -41,7 +41,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1" -{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001.py!} ``` //// @@ -53,7 +53,7 @@ Create file and form parameters the same way you would for `Body` or `Query`: //// tab | Python 3.9+ ```Python hl_lines="10-12" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} ``` //// @@ -61,7 +61,7 @@ Create file and form parameters the same way you would for `Body` or `Query`: //// tab | Python 3.8+ ```Python hl_lines="9-11" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} ``` //// @@ -75,7 +75,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001.py!} ``` //// diff --git a/docs/en/docs/tutorial/request-forms.md b/docs/en/docs/tutorial/request-forms.md index 87cfdefbc..2ccc6886e 100644 --- a/docs/en/docs/tutorial/request-forms.md +++ b/docs/en/docs/tutorial/request-forms.md @@ -21,7 +21,7 @@ Import `Form` from `fastapi`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} ``` //// @@ -29,7 +29,7 @@ Import `Form` from `fastapi`: //// tab | Python 3.8+ ```Python hl_lines="1" -{!> ../../../docs_src/request_forms/tutorial001_an.py!} +{!> ../../docs_src/request_forms/tutorial001_an.py!} ``` //// @@ -43,7 +43,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1" -{!> ../../../docs_src/request_forms/tutorial001.py!} +{!> ../../docs_src/request_forms/tutorial001.py!} ``` //// @@ -55,7 +55,7 @@ Create form parameters the same way you would for `Body` or `Query`: //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} ``` //// @@ -63,7 +63,7 @@ Create form parameters the same way you would for `Body` or `Query`: //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/request_forms/tutorial001_an.py!} +{!> ../../docs_src/request_forms/tutorial001_an.py!} ``` //// @@ -77,7 +77,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/request_forms/tutorial001.py!} +{!> ../../docs_src/request_forms/tutorial001.py!} ``` //// diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index 6a2093e6d..36ccfc4ce 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -7,7 +7,7 @@ You can use **type annotations** the same way you would for input data in functi //// tab | Python 3.10+ ```Python hl_lines="16 21" -{!> ../../../docs_src/response_model/tutorial001_01_py310.py!} +{!> ../../docs_src/response_model/tutorial001_01_py310.py!} ``` //// @@ -15,7 +15,7 @@ You can use **type annotations** the same way you would for input data in functi //// tab | Python 3.9+ ```Python hl_lines="18 23" -{!> ../../../docs_src/response_model/tutorial001_01_py39.py!} +{!> ../../docs_src/response_model/tutorial001_01_py39.py!} ``` //// @@ -23,7 +23,7 @@ You can use **type annotations** the same way you would for input data in functi //// tab | Python 3.8+ ```Python hl_lines="18 23" -{!> ../../../docs_src/response_model/tutorial001_01.py!} +{!> ../../docs_src/response_model/tutorial001_01.py!} ``` //// @@ -62,7 +62,7 @@ You can use the `response_model` parameter in any of the *path operations*: //// tab | Python 3.10+ ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001_py310.py!} +{!> ../../docs_src/response_model/tutorial001_py310.py!} ``` //// @@ -70,7 +70,7 @@ You can use the `response_model` parameter in any of the *path operations*: //// tab | Python 3.9+ ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001_py39.py!} +{!> ../../docs_src/response_model/tutorial001_py39.py!} ``` //// @@ -78,7 +78,7 @@ You can use the `response_model` parameter in any of the *path operations*: //// tab | Python 3.8+ ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001.py!} +{!> ../../docs_src/response_model/tutorial001.py!} ``` //// @@ -116,7 +116,7 @@ Here we are declaring a `UserIn` model, it will contain a plaintext password: //// tab | Python 3.10+ ```Python hl_lines="7 9" -{!> ../../../docs_src/response_model/tutorial002_py310.py!} +{!> ../../docs_src/response_model/tutorial002_py310.py!} ``` //// @@ -124,7 +124,7 @@ Here we are declaring a `UserIn` model, it will contain a plaintext password: //// tab | Python 3.8+ ```Python hl_lines="9 11" -{!> ../../../docs_src/response_model/tutorial002.py!} +{!> ../../docs_src/response_model/tutorial002.py!} ``` //// @@ -152,7 +152,7 @@ And we are using this model to declare our input and the same model to declare o //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/response_model/tutorial002_py310.py!} +{!> ../../docs_src/response_model/tutorial002_py310.py!} ``` //// @@ -160,7 +160,7 @@ And we are using this model to declare our input and the same model to declare o //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/response_model/tutorial002.py!} +{!> ../../docs_src/response_model/tutorial002.py!} ``` //// @@ -184,7 +184,7 @@ We can instead create an input model with the plaintext password and an output m //// tab | Python 3.10+ ```Python hl_lines="9 11 16" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -192,7 +192,7 @@ We can instead create an input model with the plaintext password and an output m //// tab | Python 3.8+ ```Python hl_lines="9 11 16" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -202,7 +202,7 @@ Here, even though our *path operation function* is returning the same input user //// tab | Python 3.10+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -210,7 +210,7 @@ Here, even though our *path operation function* is returning the same input user //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -220,7 +220,7 @@ Here, even though our *path operation function* is returning the same input user //// tab | Python 3.10+ ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -228,7 +228,7 @@ Here, even though our *path operation function* is returning the same input user //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -258,7 +258,7 @@ And in those cases, we can use classes and inheritance to take advantage of func //// tab | Python 3.10+ ```Python hl_lines="7-10 13-14 18" -{!> ../../../docs_src/response_model/tutorial003_01_py310.py!} +{!> ../../docs_src/response_model/tutorial003_01_py310.py!} ``` //// @@ -266,7 +266,7 @@ And in those cases, we can use classes and inheritance to take advantage of func //// tab | Python 3.8+ ```Python hl_lines="9-13 15-16 20" -{!> ../../../docs_src/response_model/tutorial003_01.py!} +{!> ../../docs_src/response_model/tutorial003_01.py!} ``` //// @@ -312,7 +312,7 @@ There might be cases where you return something that is not a valid Pydantic fie The most common case would be [returning a Response directly as explained later in the advanced docs](../advanced/response-directly.md){.internal-link target=_blank}. ```Python hl_lines="8 10-11" -{!> ../../../docs_src/response_model/tutorial003_02.py!} +{!> ../../docs_src/response_model/tutorial003_02.py!} ``` This simple case is handled automatically by FastAPI because the return type annotation is the class (or a subclass of) `Response`. @@ -324,7 +324,7 @@ And tools will also be happy because both `RedirectResponse` and `JSONResponse` You can also use a subclass of `Response` in the type annotation: ```Python hl_lines="8-9" -{!> ../../../docs_src/response_model/tutorial003_03.py!} +{!> ../../docs_src/response_model/tutorial003_03.py!} ``` This will also work because `RedirectResponse` is a subclass of `Response`, and FastAPI will automatically handle this simple case. @@ -338,7 +338,7 @@ The same would happen if you had something like a ../../../docs_src/response_model/tutorial003_04.py!} +{!> ../../docs_src/response_model/tutorial003_04.py!} ``` //// @@ -364,7 +364,7 @@ In this case, you can disable the response model generation by setting `response //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/response_model/tutorial003_05_py310.py!} +{!> ../../docs_src/response_model/tutorial003_05_py310.py!} ``` //// @@ -372,7 +372,7 @@ In this case, you can disable the response model generation by setting `response //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/response_model/tutorial003_05.py!} +{!> ../../docs_src/response_model/tutorial003_05.py!} ``` //// @@ -386,7 +386,7 @@ Your response model could have default values, like: //// tab | Python 3.10+ ```Python hl_lines="9 11-12" -{!> ../../../docs_src/response_model/tutorial004_py310.py!} +{!> ../../docs_src/response_model/tutorial004_py310.py!} ``` //// @@ -394,7 +394,7 @@ Your response model could have default values, like: //// tab | Python 3.9+ ```Python hl_lines="11 13-14" -{!> ../../../docs_src/response_model/tutorial004_py39.py!} +{!> ../../docs_src/response_model/tutorial004_py39.py!} ``` //// @@ -402,7 +402,7 @@ Your response model could have default values, like: //// tab | Python 3.8+ ```Python hl_lines="11 13-14" -{!> ../../../docs_src/response_model/tutorial004.py!} +{!> ../../docs_src/response_model/tutorial004.py!} ``` //// @@ -422,7 +422,7 @@ You can set the *path operation decorator* parameter `response_model_exclude_uns //// tab | Python 3.10+ ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial004_py310.py!} +{!> ../../docs_src/response_model/tutorial004_py310.py!} ``` //// @@ -430,7 +430,7 @@ You can set the *path operation decorator* parameter `response_model_exclude_uns //// tab | Python 3.9+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial004_py39.py!} +{!> ../../docs_src/response_model/tutorial004_py39.py!} ``` //// @@ -438,7 +438,7 @@ You can set the *path operation decorator* parameter `response_model_exclude_uns //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial004.py!} +{!> ../../docs_src/response_model/tutorial004.py!} ``` //// @@ -541,7 +541,7 @@ This also applies to `response_model_by_alias` that works similarly. //// tab | Python 3.10+ ```Python hl_lines="29 35" -{!> ../../../docs_src/response_model/tutorial005_py310.py!} +{!> ../../docs_src/response_model/tutorial005_py310.py!} ``` //// @@ -549,7 +549,7 @@ This also applies to `response_model_by_alias` that works similarly. //// tab | Python 3.8+ ```Python hl_lines="31 37" -{!> ../../../docs_src/response_model/tutorial005.py!} +{!> ../../docs_src/response_model/tutorial005.py!} ``` //// @@ -569,7 +569,7 @@ If you forget to use a `set` and use a `list` or `tuple` instead, FastAPI will s //// tab | Python 3.10+ ```Python hl_lines="29 35" -{!> ../../../docs_src/response_model/tutorial006_py310.py!} +{!> ../../docs_src/response_model/tutorial006_py310.py!} ``` //// @@ -577,7 +577,7 @@ If you forget to use a `set` and use a `list` or `tuple` instead, FastAPI will s //// tab | Python 3.8+ ```Python hl_lines="31 37" -{!> ../../../docs_src/response_model/tutorial006.py!} +{!> ../../docs_src/response_model/tutorial006.py!} ``` //// diff --git a/docs/en/docs/tutorial/response-status-code.md b/docs/en/docs/tutorial/response-status-code.md index 2613bf73d..73af62aed 100644 --- a/docs/en/docs/tutorial/response-status-code.md +++ b/docs/en/docs/tutorial/response-status-code.md @@ -9,7 +9,7 @@ The same way you can specify a response model, you can also declare the HTTP sta * etc. ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` /// note @@ -77,7 +77,7 @@ To know more about each status code and which code is for what, check the ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} ``` //// @@ -19,7 +19,7 @@ You can declare `examples` for a Pydantic model that will be added to the genera //// tab | Python 3.10+ Pydantic v1 ```Python hl_lines="13-23" -{!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} ``` //// @@ -27,7 +27,7 @@ You can declare `examples` for a Pydantic model that will be added to the genera //// tab | Python 3.8+ Pydantic v2 ```Python hl_lines="15-26" -{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +{!> ../../docs_src/schema_extra_example/tutorial001.py!} ``` //// @@ -35,7 +35,7 @@ You can declare `examples` for a Pydantic model that will be added to the genera //// tab | Python 3.8+ Pydantic v1 ```Python hl_lines="15-25" -{!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_pv1.py!} ``` //// @@ -83,7 +83,7 @@ When using `Field()` with Pydantic models, you can also declare additional `exam //// tab | Python 3.10+ ```Python hl_lines="2 8-11" -{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} ``` //// @@ -91,7 +91,7 @@ When using `Field()` with Pydantic models, you can also declare additional `exam //// tab | Python 3.8+ ```Python hl_lines="4 10-13" -{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +{!> ../../docs_src/schema_extra_example/tutorial002.py!} ``` //// @@ -117,7 +117,7 @@ Here we pass `examples` containing one example of the data expected in `Body()`: //// tab | Python 3.10+ ```Python hl_lines="22-29" -{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} ``` //// @@ -125,7 +125,7 @@ Here we pass `examples` containing one example of the data expected in `Body()`: //// tab | Python 3.9+ ```Python hl_lines="22-29" -{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} ``` //// @@ -133,7 +133,7 @@ Here we pass `examples` containing one example of the data expected in `Body()`: //// tab | Python 3.8+ ```Python hl_lines="23-30" -{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} ``` //// @@ -147,7 +147,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="18-25" -{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} ``` //// @@ -161,7 +161,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="20-27" -{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +{!> ../../docs_src/schema_extra_example/tutorial003.py!} ``` //// @@ -179,7 +179,7 @@ You can of course also pass multiple `examples`: //// tab | Python 3.10+ ```Python hl_lines="23-38" -{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!} ``` //// @@ -187,7 +187,7 @@ You can of course also pass multiple `examples`: //// tab | Python 3.9+ ```Python hl_lines="23-38" -{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!} ``` //// @@ -195,7 +195,7 @@ You can of course also pass multiple `examples`: //// tab | Python 3.8+ ```Python hl_lines="24-39" -{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an.py!} ``` //// @@ -209,7 +209,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="19-34" -{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} ``` //// @@ -223,7 +223,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="21-36" -{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +{!> ../../docs_src/schema_extra_example/tutorial004.py!} ``` //// @@ -270,7 +270,7 @@ You can use it like this: //// tab | Python 3.10+ ```Python hl_lines="23-49" -{!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_an_py310.py!} ``` //// @@ -278,7 +278,7 @@ You can use it like this: //// tab | Python 3.9+ ```Python hl_lines="23-49" -{!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_an_py39.py!} ``` //// @@ -286,7 +286,7 @@ You can use it like this: //// tab | Python 3.8+ ```Python hl_lines="24-50" -{!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_an.py!} ``` //// @@ -300,7 +300,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="19-45" -{!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_py310.py!} ``` //// @@ -314,7 +314,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="21-47" -{!> ../../../docs_src/schema_extra_example/tutorial005.py!} +{!> ../../docs_src/schema_extra_example/tutorial005.py!} ``` //// diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index d1fe0163e..ead2aa799 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -23,7 +23,7 @@ Copy the example in a file `main.py`: //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -31,7 +31,7 @@ Copy the example in a file `main.py`: //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -45,7 +45,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// @@ -163,7 +163,7 @@ When we create an instance of the `OAuth2PasswordBearer` class we pass in the `t //// tab | Python 3.9+ ```Python hl_lines="8" -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -171,7 +171,7 @@ When we create an instance of the `OAuth2PasswordBearer` class we pass in the `t //// tab | Python 3.8+ ```Python hl_lines="7" -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -185,7 +185,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="6" -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// @@ -229,7 +229,7 @@ Now you can pass that `oauth2_scheme` in a dependency with `Depends`. //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -237,7 +237,7 @@ Now you can pass that `oauth2_scheme` in a dependency with `Depends`. //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -251,7 +251,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// diff --git a/docs/en/docs/tutorial/security/get-current-user.md b/docs/en/docs/tutorial/security/get-current-user.md index 7faaa3e13..069806621 100644 --- a/docs/en/docs/tutorial/security/get-current-user.md +++ b/docs/en/docs/tutorial/security/get-current-user.md @@ -5,7 +5,7 @@ In the previous chapter the security system (which is based on the dependency in //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -13,7 +13,7 @@ In the previous chapter the security system (which is based on the dependency in //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -27,7 +27,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// @@ -45,7 +45,7 @@ The same way we use Pydantic to declare bodies, we can use it anywhere else: //// tab | Python 3.10+ ```Python hl_lines="5 12-16" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -53,7 +53,7 @@ The same way we use Pydantic to declare bodies, we can use it anywhere else: //// tab | Python 3.9+ ```Python hl_lines="5 12-16" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -61,7 +61,7 @@ The same way we use Pydantic to declare bodies, we can use it anywhere else: //// tab | Python 3.8+ ```Python hl_lines="5 13-17" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -75,7 +75,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="3 10-14" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -89,7 +89,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="5 12-16" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -107,7 +107,7 @@ The same as we were doing before in the *path operation* directly, our new depen //// tab | Python 3.10+ ```Python hl_lines="25" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -115,7 +115,7 @@ The same as we were doing before in the *path operation* directly, our new depen //// tab | Python 3.9+ ```Python hl_lines="25" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -123,7 +123,7 @@ The same as we were doing before in the *path operation* directly, our new depen //// tab | Python 3.8+ ```Python hl_lines="26" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -137,7 +137,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="23" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -151,7 +151,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="25" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -163,7 +163,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.10+ ```Python hl_lines="19-22 26-27" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -171,7 +171,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.9+ ```Python hl_lines="19-22 26-27" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -179,7 +179,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.8+ ```Python hl_lines="20-23 27-28" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -193,7 +193,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="17-20 24-25" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -207,7 +207,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="19-22 26-27" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -219,7 +219,7 @@ So now we can use the same `Depends` with our `get_current_user` in the *path op //// tab | Python 3.10+ ```Python hl_lines="31" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -227,7 +227,7 @@ So now we can use the same `Depends` with our `get_current_user` in the *path op //// tab | Python 3.9+ ```Python hl_lines="31" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -235,7 +235,7 @@ So now we can use the same `Depends` with our `get_current_user` in the *path op //// tab | Python 3.8+ ```Python hl_lines="32" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -249,7 +249,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="29" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -263,7 +263,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="31" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -323,7 +323,7 @@ And all these thousands of *path operations* can be as small as 3 lines: //// tab | Python 3.10+ ```Python hl_lines="30-32" -{!> ../../../docs_src/security/tutorial002_an_py310.py!} +{!> ../../docs_src/security/tutorial002_an_py310.py!} ``` //// @@ -331,7 +331,7 @@ And all these thousands of *path operations* can be as small as 3 lines: //// tab | Python 3.9+ ```Python hl_lines="30-32" -{!> ../../../docs_src/security/tutorial002_an_py39.py!} +{!> ../../docs_src/security/tutorial002_an_py39.py!} ``` //// @@ -339,7 +339,7 @@ And all these thousands of *path operations* can be as small as 3 lines: //// tab | Python 3.8+ ```Python hl_lines="31-33" -{!> ../../../docs_src/security/tutorial002_an.py!} +{!> ../../docs_src/security/tutorial002_an.py!} ``` //// @@ -353,7 +353,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="28-30" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -367,7 +367,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="30-32" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index ba2bfef29..f454a8b28 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -119,7 +119,7 @@ And another one to authenticate and return a user. //// tab | Python 3.10+ ```Python hl_lines="8 49 56-57 60-61 70-76" -{!> ../../../docs_src/security/tutorial004_an_py310.py!} +{!> ../../docs_src/security/tutorial004_an_py310.py!} ``` //// @@ -127,7 +127,7 @@ And another one to authenticate and return a user. //// tab | Python 3.9+ ```Python hl_lines="8 49 56-57 60-61 70-76" -{!> ../../../docs_src/security/tutorial004_an_py39.py!} +{!> ../../docs_src/security/tutorial004_an_py39.py!} ``` //// @@ -135,7 +135,7 @@ And another one to authenticate and return a user. //// tab | Python 3.8+ ```Python hl_lines="8 50 57-58 61-62 71-77" -{!> ../../../docs_src/security/tutorial004_an.py!} +{!> ../../docs_src/security/tutorial004_an.py!} ``` //// @@ -149,7 +149,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -163,7 +163,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8 49 56-57 60-61 70-76" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -205,7 +205,7 @@ Create a utility function to generate a new access token. //// tab | Python 3.10+ ```Python hl_lines="4 7 13-15 29-31 79-87" -{!> ../../../docs_src/security/tutorial004_an_py310.py!} +{!> ../../docs_src/security/tutorial004_an_py310.py!} ``` //// @@ -213,7 +213,7 @@ Create a utility function to generate a new access token. //// tab | Python 3.9+ ```Python hl_lines="4 7 13-15 29-31 79-87" -{!> ../../../docs_src/security/tutorial004_an_py39.py!} +{!> ../../docs_src/security/tutorial004_an_py39.py!} ``` //// @@ -221,7 +221,7 @@ Create a utility function to generate a new access token. //// tab | Python 3.8+ ```Python hl_lines="4 7 14-16 30-32 80-88" -{!> ../../../docs_src/security/tutorial004_an.py!} +{!> ../../docs_src/security/tutorial004_an.py!} ``` //// @@ -235,7 +235,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="3 6 12-14 28-30 78-86" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -249,7 +249,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="4 7 13-15 29-31 79-87" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -265,7 +265,7 @@ If the token is invalid, return an HTTP error right away. //// tab | Python 3.10+ ```Python hl_lines="90-107" -{!> ../../../docs_src/security/tutorial004_an_py310.py!} +{!> ../../docs_src/security/tutorial004_an_py310.py!} ``` //// @@ -273,7 +273,7 @@ If the token is invalid, return an HTTP error right away. //// tab | Python 3.9+ ```Python hl_lines="90-107" -{!> ../../../docs_src/security/tutorial004_an_py39.py!} +{!> ../../docs_src/security/tutorial004_an_py39.py!} ``` //// @@ -281,7 +281,7 @@ If the token is invalid, return an HTTP error right away. //// tab | Python 3.8+ ```Python hl_lines="91-108" -{!> ../../../docs_src/security/tutorial004_an.py!} +{!> ../../docs_src/security/tutorial004_an.py!} ``` //// @@ -295,7 +295,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="89-106" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -309,7 +309,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="90-107" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// @@ -323,7 +323,7 @@ Create a real JWT access token and return it. //// tab | Python 3.10+ ```Python hl_lines="118-133" -{!> ../../../docs_src/security/tutorial004_an_py310.py!} +{!> ../../docs_src/security/tutorial004_an_py310.py!} ``` //// @@ -331,7 +331,7 @@ Create a real JWT access token and return it. //// tab | Python 3.9+ ```Python hl_lines="118-133" -{!> ../../../docs_src/security/tutorial004_an_py39.py!} +{!> ../../docs_src/security/tutorial004_an_py39.py!} ``` //// @@ -339,7 +339,7 @@ Create a real JWT access token and return it. //// tab | Python 3.8+ ```Python hl_lines="119-134" -{!> ../../../docs_src/security/tutorial004_an.py!} +{!> ../../docs_src/security/tutorial004_an.py!} ``` //// @@ -353,7 +353,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="115-130" -{!> ../../../docs_src/security/tutorial004_py310.py!} +{!> ../../docs_src/security/tutorial004_py310.py!} ``` //// @@ -367,7 +367,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="116-131" -{!> ../../../docs_src/security/tutorial004.py!} +{!> ../../docs_src/security/tutorial004.py!} ``` //// diff --git a/docs/en/docs/tutorial/security/simple-oauth2.md b/docs/en/docs/tutorial/security/simple-oauth2.md index c9f6a1382..dc15bef20 100644 --- a/docs/en/docs/tutorial/security/simple-oauth2.md +++ b/docs/en/docs/tutorial/security/simple-oauth2.md @@ -55,7 +55,7 @@ First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depe //// tab | Python 3.10+ ```Python hl_lines="4 78" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -63,7 +63,7 @@ First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depe //// tab | Python 3.9+ ```Python hl_lines="4 78" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -71,7 +71,7 @@ First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depe //// tab | Python 3.8+ ```Python hl_lines="4 79" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -85,7 +85,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="2 74" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -99,7 +99,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="4 76" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -153,7 +153,7 @@ For the error, we use the exception `HTTPException`: //// tab | Python 3.10+ ```Python hl_lines="3 79-81" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -161,7 +161,7 @@ For the error, we use the exception `HTTPException`: //// tab | Python 3.9+ ```Python hl_lines="3 79-81" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -169,7 +169,7 @@ For the error, we use the exception `HTTPException`: //// tab | Python 3.8+ ```Python hl_lines="3 80-82" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -183,7 +183,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1 75-77" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -197,7 +197,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="3 77-79" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -229,7 +229,7 @@ So, the thief won't be able to try to use those same passwords in another system //// tab | Python 3.10+ ```Python hl_lines="82-85" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -237,7 +237,7 @@ So, the thief won't be able to try to use those same passwords in another system //// tab | Python 3.9+ ```Python hl_lines="82-85" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -245,7 +245,7 @@ So, the thief won't be able to try to use those same passwords in another system //// tab | Python 3.8+ ```Python hl_lines="83-86" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -259,7 +259,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="78-81" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -273,7 +273,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="80-83" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -321,7 +321,7 @@ But for now, let's focus on the specific details we need. //// tab | Python 3.10+ ```Python hl_lines="87" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -329,7 +329,7 @@ But for now, let's focus on the specific details we need. //// tab | Python 3.9+ ```Python hl_lines="87" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -337,7 +337,7 @@ But for now, let's focus on the specific details we need. //// tab | Python 3.8+ ```Python hl_lines="88" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -351,7 +351,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="83" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -365,7 +365,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="85" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -397,7 +397,7 @@ So, in our endpoint, we will only get a user if the user exists, was correctly a //// tab | Python 3.10+ ```Python hl_lines="58-66 69-74 94" -{!> ../../../docs_src/security/tutorial003_an_py310.py!} +{!> ../../docs_src/security/tutorial003_an_py310.py!} ``` //// @@ -405,7 +405,7 @@ So, in our endpoint, we will only get a user if the user exists, was correctly a //// tab | Python 3.9+ ```Python hl_lines="58-66 69-74 94" -{!> ../../../docs_src/security/tutorial003_an_py39.py!} +{!> ../../docs_src/security/tutorial003_an_py39.py!} ``` //// @@ -413,7 +413,7 @@ So, in our endpoint, we will only get a user if the user exists, was correctly a //// tab | Python 3.8+ ```Python hl_lines="59-67 70-75 95" -{!> ../../../docs_src/security/tutorial003_an.py!} +{!> ../../docs_src/security/tutorial003_an.py!} ``` //// @@ -427,7 +427,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="56-64 67-70 88" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -441,7 +441,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="58-66 69-72 90" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 56971bf9d..f65fa773c 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -122,13 +122,13 @@ Let's refer to the file `sql_app/database.py`. ### Import the SQLAlchemy parts ```Python hl_lines="1-3" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` ### Create a database URL for SQLAlchemy ```Python hl_lines="5-6" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` In this example, we are "connecting" to a SQLite database (opening a file with the SQLite database). @@ -158,7 +158,7 @@ The first step is to create a SQLAlchemy "engine". We will later use this `engine` in other places. ```Python hl_lines="8-10" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` #### Note @@ -196,7 +196,7 @@ We will use `Session` (the one imported from SQLAlchemy) later. To create the `SessionLocal` class, use the function `sessionmaker`: ```Python hl_lines="11" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` ### Create a `Base` class @@ -206,7 +206,7 @@ Now we will use the function `declarative_base()` that returns a class. Later we will inherit from this class to create each of the database models or classes (the ORM models): ```Python hl_lines="13" -{!../../../docs_src/sql_databases/sql_app/database.py!} +{!../../docs_src/sql_databases/sql_app/database.py!} ``` ## Create the database models @@ -232,7 +232,7 @@ Create classes that inherit from it. These classes are the SQLAlchemy models. ```Python hl_lines="4 7-8 18-19" -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` The `__tablename__` attribute tells SQLAlchemy the name of the table to use in the database for each of these models. @@ -248,7 +248,7 @@ We use `Column` from SQLAlchemy as the default value. And we pass a SQLAlchemy class "type", as `Integer`, `String`, and `Boolean`, that defines the type in the database, as an argument. ```Python hl_lines="1 10-13 21-24" -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` ### Create the relationships @@ -260,7 +260,7 @@ For this, we use `relationship` provided by SQLAlchemy ORM. This will become, more or less, a "magic" attribute that will contain the values from other tables related to this one. ```Python hl_lines="2 15 26" -{!../../../docs_src/sql_databases/sql_app/models.py!} +{!../../docs_src/sql_databases/sql_app/models.py!} ``` When accessing the attribute `items` in a `User`, as in `my_user.items`, it will have a list of `Item` SQLAlchemy models (from the `items` table) that have a foreign key pointing to this record in the `users` table. @@ -478,7 +478,7 @@ Create utility functions to: * Read multiple items. ```Python hl_lines="1 3 6-7 10-11 14-15 27-28" -{!../../../docs_src/sql_databases/sql_app/crud.py!} +{!../../docs_src/sql_databases/sql_app/crud.py!} ``` /// tip @@ -499,7 +499,7 @@ The steps are: * `refresh` your instance (so that it contains any new data from the database, like the generated ID). ```Python hl_lines="18-24 31-36" -{!../../../docs_src/sql_databases/sql_app/crud.py!} +{!../../docs_src/sql_databases/sql_app/crud.py!} ``` /// info @@ -752,13 +752,13 @@ For example, in a background task worker with ../../../docs_src/app_testing/app_b_an_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} ``` //// @@ -137,7 +137,7 @@ Both *path operations* require an `X-Token` header. //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} ``` //// @@ -145,7 +145,7 @@ Both *path operations* require an `X-Token` header. //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/app_testing/app_b_an/main.py!} +{!> ../../docs_src/app_testing/app_b_an/main.py!} ``` //// @@ -159,7 +159,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python -{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_py310/main.py!} ``` //// @@ -173,7 +173,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python -{!> ../../../docs_src/app_testing/app_b/main.py!} +{!> ../../docs_src/app_testing/app_b/main.py!} ``` //// @@ -183,7 +183,7 @@ Prefer to use the `Annotated` version if possible. You could then update `test_main.py` with the extended tests: ```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} +{!> ../../docs_src/app_testing/app_b/test_main.py!} ``` Whenever you need the client to pass information in the request and you don't know how to, you can search (Google) how to do it in `httpx`, or even how to do it with `requests`, as HTTPX's design is based on Requests' design. diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 5161b891b..a18af2022 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -305,7 +305,6 @@ markdown_extensions: # Other extensions mdx_include: - base_path: docs extra: analytics: diff --git a/docs/es/docs/advanced/additional-status-codes.md b/docs/es/docs/advanced/additional-status-codes.md index 664604c59..4a0625c25 100644 --- a/docs/es/docs/advanced/additional-status-codes.md +++ b/docs/es/docs/advanced/additional-status-codes.md @@ -15,7 +15,7 @@ Pero también quieres que acepte nuevos ítems. Cuando los ítems no existan ant Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu contenido, asignando el `status_code` que quieras: ```Python hl_lines="4 25" -{!../../../docs_src/additional_status_codes/tutorial001.py!} +{!../../docs_src/additional_status_codes/tutorial001.py!} ``` /// warning | Advertencia diff --git a/docs/es/docs/advanced/path-operation-advanced-configuration.md b/docs/es/docs/advanced/path-operation-advanced-configuration.md index 18f96213f..f6813f0ff 100644 --- a/docs/es/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/es/docs/advanced/path-operation-advanced-configuration.md @@ -13,7 +13,7 @@ Puedes asignar el `operationId` de OpenAPI para ser usado en tu *operación de p En este caso tendrías que asegurarte de que sea único para cada operación. ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} ``` ### Usando el nombre de la *función de la operación de path* en el operationId @@ -23,7 +23,7 @@ Si quieres usar tus nombres de funciones de API como `operationId`s, puedes iter Deberías hacerlo después de adicionar todas tus *operaciones de path*. ```Python hl_lines="2 12 13 14 15 16 17 18 19 20 21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` /// tip | Consejo @@ -45,7 +45,7 @@ Incluso si están en diferentes módulos (archivos Python). Para excluir una *operación de path* del esquema OpenAPI generado (y por tanto del la documentación generada automáticamente), usa el parámetro `include_in_schema` y asigna el valor como `False`; ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} ``` ## Descripción avanzada desde el docstring @@ -57,5 +57,5 @@ Agregar un `\f` (un carácter de "form feed" escapado) hace que **FastAPI** trun No será mostrado en la documentación, pero otras herramientas (como Sphinx) serán capaces de usar el resto. ```Python hl_lines="19 20 21 22 23 24 25 26 27 28 29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} ``` diff --git a/docs/es/docs/advanced/response-change-status-code.md b/docs/es/docs/advanced/response-change-status-code.md index ecd9fad41..ddfd05a77 100644 --- a/docs/es/docs/advanced/response-change-status-code.md +++ b/docs/es/docs/advanced/response-change-status-code.md @@ -21,7 +21,7 @@ Puedes declarar un parámetro de tipo `Response` en tu *función de la operació Y luego puedes establecer el `status_code` en ese objeto de respuesta *temporal*. ```Python hl_lines="1 9 12" -{!../../../docs_src/response_change_status_code/tutorial001.py!} +{!../../docs_src/response_change_status_code/tutorial001.py!} ``` Y luego puedes retornar cualquier objeto que necesites, como normalmente lo harías (un `dict`, un modelo de base de datos, etc). diff --git a/docs/es/docs/advanced/response-directly.md b/docs/es/docs/advanced/response-directly.md index 4eeab3fd0..8800d2510 100644 --- a/docs/es/docs/advanced/response-directly.md +++ b/docs/es/docs/advanced/response-directly.md @@ -35,7 +35,7 @@ Por ejemplo, no puedes poner un modelo Pydantic en una `JSONResponse` sin primer Para esos casos, puedes usar el `jsonable_encoder` para convertir tus datos antes de pasarlos a la respuesta: ```Python hl_lines="4 6 20 21" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` /// note | Detalles Técnicos @@ -57,7 +57,7 @@ Digamos que quieres devolver una respuesta documentación de Strawberry. diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md index c873385bc..156907ad1 100644 --- a/docs/es/docs/python-types.md +++ b/docs/es/docs/python-types.md @@ -23,7 +23,7 @@ Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al s Comencemos con un ejemplo simple: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Llamar este programa nos muestra el siguiente output: @@ -39,7 +39,7 @@ La función hace lo siguiente: * Las concatena con un espacio en la mitad. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Edítalo @@ -83,7 +83,7 @@ Eso es todo. Esos son los "type hints": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` No es lo mismo a declarar valores por defecto, como sería con: @@ -113,7 +113,7 @@ Con esto puedes moverte hacia abajo viendo las opciones hasta que encuentras una Mira esta función que ya tiene type hints: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Como el editor conoce el tipo de las variables no solo obtienes auto-completado, si no que también obtienes chequeo de errores: @@ -123,7 +123,7 @@ Como el editor conoce el tipo de las variables no solo obtienes auto-completado, Ahora que sabes que tienes que arreglarlo convierte `age` a un string con `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Declarando tipos @@ -144,7 +144,7 @@ Por ejemplo, puedes usar: * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Tipos con sub-tipos @@ -162,7 +162,7 @@ Por ejemplo, vamos a definir una variable para que sea una `list` compuesta de ` De `typing`, importa `List` (con una `L` mayúscula): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` Declara la variable con la misma sintaxis de los dos puntos (`:`). @@ -172,7 +172,7 @@ Pon `List` como el tipo. Como la lista es un tipo que permite tener un "sub-tipo" pones el sub-tipo en corchetes `[]`: ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` Esto significa: la variable `items` es una `list` y cada uno de los ítems en esta lista es un `str`. @@ -192,7 +192,7 @@ El editor aún sabe que es un `str` y provee soporte para ello. Harías lo mismo para declarar `tuple`s y `set`s: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` Esto significa: @@ -209,7 +209,7 @@ El primer sub-tipo es para los keys del `dict`. El segundo sub-tipo es para los valores del `dict`: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` Esto significa: @@ -225,13 +225,13 @@ También puedes declarar una clase como el tipo de una variable. Digamos que tienes una clase `Person`con un nombre: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Entonces puedes declarar una variable que sea de tipo `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Una vez más tendrás todo el soporte del editor: @@ -253,7 +253,7 @@ Y obtienes todo el soporte del editor con el objeto resultante. Tomado de la documentación oficial de Pydantic: ```Python -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` /// info | Información diff --git a/docs/es/docs/tutorial/cookie-params.md b/docs/es/docs/tutorial/cookie-params.md index 3eaea31f9..e858e34e8 100644 --- a/docs/es/docs/tutorial/cookie-params.md +++ b/docs/es/docs/tutorial/cookie-params.md @@ -9,7 +9,7 @@ Primero importa `Cookie`: //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ Primero importa `Cookie`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Primero importa `Cookie`: //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Es preferible utilizar la versión `Annotated` si es posible. /// ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Es preferible utilizar la versión `Annotated` si es posible. /// ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -67,7 +67,7 @@ El primer valor es el valor por defecto, puedes pasar todos los parámetros adic //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -75,7 +75,7 @@ El primer valor es el valor por defecto, puedes pasar todos los parámetros adic //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ El primer valor es el valor por defecto, puedes pasar todos los parámetros adic //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -97,7 +97,7 @@ Es preferible utilizar la versión `Annotated` si es posible. /// ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -111,7 +111,7 @@ Es preferible utilizar la versión `Annotated` si es posible. /// ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md index 8d8909b97..68df00e64 100644 --- a/docs/es/docs/tutorial/first-steps.md +++ b/docs/es/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ Un archivo muy simple de FastAPI podría verse así: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Copia eso a un archivo `main.py`. @@ -134,7 +134,7 @@ También podrías usarlo para generar código automáticamente, para los cliente ### Paso 1: importa `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` es una clase de Python que provee toda la funcionalidad para tu API. @@ -150,7 +150,7 @@ También puedes usar toda la funcionalidad de parsé en tant que JSON, il est lu directement en tant que `bytes`, et la fonction `magic_data_reader()` serait chargé de l'analyser d'une manière ou d'une autre. @@ -164,7 +164,7 @@ Et vous pouvez le faire même si le type de données dans la requête n'est pas Dans cet exemple, nous n'utilisons pas les fonctionnalités de FastAPI pour extraire le schéma JSON des modèles Pydantic ni la validation automatique pour JSON. En fait, nous déclarons le type de contenu de la requête en tant que YAML, et non JSON : ```Python hl_lines="17-22 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` Néanmoins, bien que nous n'utilisions pas la fonctionnalité par défaut, nous utilisons toujours un modèle Pydantic pour générer manuellement le schéma JSON pour les données que nous souhaitons recevoir en YAML. @@ -174,7 +174,7 @@ Ensuite, nous utilisons directement la requête et extrayons son contenu en tant Et nous analysons directement ce contenu YAML, puis nous utilisons à nouveau le même modèle Pydantic pour valider le contenu YAML : ```Python hl_lines="26-33" -{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial007.py!} ``` /// tip | "Astuce" diff --git a/docs/fr/docs/advanced/response-directly.md b/docs/fr/docs/advanced/response-directly.md index 49ca32230..80876bc18 100644 --- a/docs/fr/docs/advanced/response-directly.md +++ b/docs/fr/docs/advanced/response-directly.md @@ -35,7 +35,7 @@ Par exemple, vous ne pouvez pas mettre un modèle Pydantic dans une `JSONRespons Pour ces cas, vous pouvez spécifier un appel à `jsonable_encoder` pour convertir vos données avant de les passer à une réponse : ```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` /// note | "Détails techniques" @@ -57,7 +57,7 @@ Disons que vous voulez retourner une réponse chaîne de caractères grâce à `str(age)` : ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Déclarer des types @@ -146,7 +146,7 @@ Comme par exemple : * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Types génériques avec des paramètres de types @@ -164,7 +164,7 @@ Par exemple, définissons une variable comme `list` de `str`. Importez `List` (avec un `L` majuscule) depuis `typing`. ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` Déclarez la variable, en utilisant la syntaxe des deux-points (`:`). @@ -174,7 +174,7 @@ Et comme type, mettez `List`. Les listes étant un type contenant des types internes, mettez ces derniers entre crochets (`[`, `]`) : ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` /// tip | "Astuce" @@ -202,7 +202,7 @@ Et pourtant, l'éditeur sait qu'elle est de type `str` et pourra donc vous aider C'est le même fonctionnement pour déclarer un `tuple` ou un `set` : ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` Dans cet exemple : @@ -217,7 +217,7 @@ Pour définir un `dict`, il faut lui passer 2 paramètres, séparés par une vir Le premier paramètre de type est pour les clés et le second pour les valeurs du dictionnaire (`dict`). ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` Dans cet exemple : @@ -231,7 +231,7 @@ Dans cet exemple : Vous pouvez aussi utiliser `Optional` pour déclarer qu'une variable a un type, comme `str` mais qu'il est "optionnel" signifiant qu'il pourrait aussi être `None`. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Utiliser `Optional[str]` plutôt que `str` permettra à l'éditeur de vous aider à détecter les erreurs où vous supposeriez qu'une valeur est toujours de type `str`, alors qu'elle pourrait aussi être `None`. @@ -256,13 +256,13 @@ Vous pouvez aussi déclarer une classe comme type d'une variable. Disons que vous avez une classe `Person`, avec une variable `name` : ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Vous pouvez ensuite déclarer une variable de type `Person` : ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Et vous aurez accès, encore une fois, au support complet offert par l'éditeur : @@ -284,7 +284,7 @@ Ainsi, votre éditeur vous offrira un support adapté pour l'objet résultant. Extrait de la documentation officielle de **Pydantic** : ```Python -{!../../../docs_src/python_types/tutorial011.py!} +{!../../docs_src/python_types/tutorial011.py!} ``` /// info diff --git a/docs/fr/docs/tutorial/background-tasks.md b/docs/fr/docs/tutorial/background-tasks.md index f7cf1a6cc..d971d293d 100644 --- a/docs/fr/docs/tutorial/background-tasks.md +++ b/docs/fr/docs/tutorial/background-tasks.md @@ -17,7 +17,7 @@ Cela comprend, par exemple : Pour commencer, importez `BackgroundTasks` et définissez un paramètre dans votre *fonction de chemin* avec `BackgroundTasks` comme type déclaré. ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** créera l'objet de type `BackgroundTasks` pour vous et le passera comme paramètre. @@ -33,7 +33,7 @@ Dans cet exemple, la fonction de tâche écrira dans un fichier (afin de simuler L'opération d'écriture n'utilisant ni `async` ni `await`, on définit la fonction avec un `def` normal. ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## Ajouter une tâche d'arrière-plan @@ -42,7 +42,7 @@ Dans votre *fonction de chemin*, passez votre fonction de tâche à l'objet de t ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` reçoit comme arguments : @@ -58,7 +58,7 @@ Utiliser `BackgroundTasks` fonctionne aussi avec le système d'injection de dép **FastAPI** sait quoi faire dans chaque cas et comment réutiliser le même objet, afin que tous les paramètres de type `BackgroundTasks` soient fusionnés et que les tâches soient exécutées en arrière-plan : ```Python hl_lines="13 15 22 25" -{!../../../docs_src/background_tasks/tutorial002.py!} +{!../../docs_src/background_tasks/tutorial002.py!} ``` Dans cet exemple, les messages seront écrits dans le fichier `log.txt` après que la réponse soit envoyée. diff --git a/docs/fr/docs/tutorial/body-multiple-params.md b/docs/fr/docs/tutorial/body-multiple-params.md index fd8e5d688..dafd869e3 100644 --- a/docs/fr/docs/tutorial/body-multiple-params.md +++ b/docs/fr/docs/tutorial/body-multiple-params.md @@ -11,7 +11,7 @@ Vous pouvez également déclarer des paramètres body comme étant optionnels, e //// tab | Python 3.10+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} ``` //// @@ -19,7 +19,7 @@ Vous pouvez également déclarer des paramètres body comme étant optionnels, e //// tab | Python 3.9+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} ``` //// @@ -27,7 +27,7 @@ Vous pouvez également déclarer des paramètres body comme étant optionnels, e //// tab | Python 3.8+ ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} ``` //// @@ -41,7 +41,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="17-19" -{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} ``` //// @@ -55,7 +55,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +{!> ../../docs_src/body_multiple_params/tutorial001.py!} ``` //// @@ -84,7 +84,7 @@ Mais vous pouvez également déclarer plusieurs paramètres provenant de body, p //// tab | Python 3.10+ ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} ``` //// @@ -92,7 +92,7 @@ Mais vous pouvez également déclarer plusieurs paramètres provenant de body, p //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +{!> ../../docs_src/body_multiple_params/tutorial002.py!} ``` //// @@ -138,7 +138,7 @@ Mais vous pouvez indiquer à **FastAPI** de la traiter comme une variable de bod //// tab | Python 3.10+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} ``` //// @@ -146,7 +146,7 @@ Mais vous pouvez indiquer à **FastAPI** de la traiter comme une variable de bod //// tab | Python 3.9+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} ``` //// @@ -154,7 +154,7 @@ Mais vous pouvez indiquer à **FastAPI** de la traiter comme une variable de bod //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} ``` //// @@ -168,7 +168,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} ``` //// @@ -182,7 +182,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +{!> ../../docs_src/body_multiple_params/tutorial003.py!} ``` //// @@ -228,7 +228,7 @@ Par exemple : //// tab | Python 3.10+ ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} ``` //// @@ -236,7 +236,7 @@ Par exemple : //// tab | Python 3.9+ ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} ``` //// @@ -244,7 +244,7 @@ Par exemple : //// tab | Python 3.8+ ```Python hl_lines="28" -{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} ``` //// @@ -258,7 +258,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="25" -{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` //// @@ -272,7 +272,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +{!> ../../docs_src/body_multiple_params/tutorial004.py!} ``` //// @@ -300,7 +300,7 @@ Voici un exemple complet : //// tab | Python 3.10+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} ``` //// @@ -308,7 +308,7 @@ Voici un exemple complet : //// tab | Python 3.9+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} ``` //// @@ -316,7 +316,7 @@ Voici un exemple complet : //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} ``` //// @@ -330,7 +330,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="15" -{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} ``` //// @@ -344,7 +344,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +{!> ../../docs_src/body_multiple_params/tutorial005.py!} ``` //// diff --git a/docs/fr/docs/tutorial/body.md b/docs/fr/docs/tutorial/body.md index 9a5121f10..96fff2ca6 100644 --- a/docs/fr/docs/tutorial/body.md +++ b/docs/fr/docs/tutorial/body.md @@ -23,7 +23,7 @@ Ceci étant découragé, la documentation interactive générée par Swagger UI Commencez par importer la classe `BaseModel` du module `pydantic` : ```Python hl_lines="4" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` ## Créez votre modèle de données @@ -33,7 +33,7 @@ Déclarez ensuite votre modèle de données en tant que classe qui hérite de `B Utilisez les types Python standard pour tous les attributs : ```Python hl_lines="7-11" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` Tout comme pour la déclaration de paramètres de requête, quand un attribut de modèle a une valeur par défaut, il n'est pas nécessaire. Sinon, cet attribut doit être renseigné dans le corps de la requête. Pour rendre ce champ optionnel simplement, utilisez `None` comme valeur par défaut. @@ -63,7 +63,7 @@ Par exemple, le modèle ci-dessus déclare un "objet" JSON (ou `dict` Python) te Pour l'ajouter à votre *opération de chemin*, déclarez-le comme vous déclareriez des paramètres de chemin ou de requête : ```Python hl_lines="18" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` ...et déclarez que son type est le modèle que vous avez créé : `Item`. @@ -132,7 +132,7 @@ Ce qui améliore le support pour les modèles Pydantic avec : Dans la fonction, vous pouvez accéder à tous les attributs de l'objet du modèle directement : ```Python hl_lines="21" -{!../../../docs_src/body/tutorial002.py!} +{!../../docs_src/body/tutorial002.py!} ``` ## Corps de la requête + paramètres de chemin @@ -142,7 +142,7 @@ Vous pouvez déclarer des paramètres de chemin et un corps de requête pour la **FastAPI** est capable de reconnaître que les paramètres de la fonction qui correspondent aux paramètres de chemin doivent être **récupérés depuis le chemin**, et que les paramètres de fonctions déclarés comme modèles Pydantic devraient être **récupérés depuis le corps de la requête**. ```Python hl_lines="17-18" -{!../../../docs_src/body/tutorial003.py!} +{!../../docs_src/body/tutorial003.py!} ``` ## Corps de la requête + paramètres de chemin et de requête @@ -152,7 +152,7 @@ Vous pouvez aussi déclarer un **corps**, et des paramètres de **chemin** et de **FastAPI** saura reconnaître chacun d'entre eux et récupérer la bonne donnée au bon endroit. ```Python hl_lines="18" -{!../../../docs_src/body/tutorial004.py!} +{!../../docs_src/body/tutorial004.py!} ``` Les paramètres de la fonction seront reconnus comme tel : diff --git a/docs/fr/docs/tutorial/debugging.md b/docs/fr/docs/tutorial/debugging.md index bcd780a82..914277699 100644 --- a/docs/fr/docs/tutorial/debugging.md +++ b/docs/fr/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ Vous pouvez connecter le débogueur da Dans votre application FastAPI, importez et exécutez directement `uvicorn` : ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### À propos de `__name__ == "__main__"` diff --git a/docs/fr/docs/tutorial/first-steps.md b/docs/fr/docs/tutorial/first-steps.md index bf476d990..e9511b029 100644 --- a/docs/fr/docs/tutorial/first-steps.md +++ b/docs/fr/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ Le fichier **FastAPI** le plus simple possible pourrait ressembler à cela : ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Copiez ce code dans un fichier nommé `main.py`. @@ -135,7 +135,7 @@ Vous pourriez aussi l'utiliser pour générer du code automatiquement, pour les ### Étape 1 : import `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` est une classe Python qui fournit toutes les fonctionnalités nécessaires au lancement de votre API. @@ -151,7 +151,7 @@ Vous pouvez donc aussi utiliser toutes les fonctionnalités de ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ Tout d'abord, importez `Path` de `fastapi`, et importez `Annotated` : //// tab | Python 3.9+ ```Python hl_lines="1 3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Tout d'abord, importez `Path` de `fastapi`, et importez `Annotated` : //// tab | Python 3.8+ ```Python hl_lines="3-4" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="1" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -77,7 +77,7 @@ Par exemple, pour déclarer une valeur de métadonnée `title` pour le paramètr //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} ``` //// @@ -85,7 +85,7 @@ Par exemple, pour déclarer une valeur de métadonnée `title` pour le paramètr //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` //// @@ -93,7 +93,7 @@ Par exemple, pour déclarer une valeur de métadonnée `title` pour le paramètr //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} ``` //// @@ -107,7 +107,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -121,7 +121,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -163,7 +163,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` //// @@ -173,7 +173,7 @@ Mais gardez à l'esprit que si vous utilisez `Annotated`, vous n'aurez pas ce pr //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} ``` //// @@ -181,7 +181,7 @@ Mais gardez à l'esprit que si vous utilisez `Annotated`, vous n'aurez pas ce pr //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002_an.py!} ``` //// @@ -210,7 +210,7 @@ Passez `*`, comme premier paramètre de la fonction. Python ne fera rien avec ce `*`, mais il saura que tous les paramètres suivants doivent être appelés comme arguments "mots-clés" (paires clé-valeur), également connus sous le nom de kwargs. Même s'ils n'ont pas de valeur par défaut. ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` # Avec `Annotated` @@ -220,7 +220,7 @@ Gardez à l'esprit que si vous utilisez `Annotated`, comme vous n'utilisez pas l //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} ``` //// @@ -228,7 +228,7 @@ Gardez à l'esprit que si vous utilisez `Annotated`, comme vous n'utilisez pas l //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial003_an.py!} ``` //// @@ -242,7 +242,7 @@ Ici, avec `ge=1`, `item_id` devra être un nombre entier "`g`reater than or `e`q //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} ``` //// @@ -250,7 +250,7 @@ Ici, avec `ge=1`, `item_id` devra être un nombre entier "`g`reater than or `e`q //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!} ``` //// @@ -264,7 +264,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` //// @@ -279,7 +279,7 @@ La même chose s'applique pour : //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} ``` //// @@ -287,7 +287,7 @@ La même chose s'applique pour : //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!} ``` //// @@ -301,7 +301,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` //// @@ -316,7 +316,7 @@ La même chose s'applique pour : //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} ``` //// @@ -324,7 +324,7 @@ La même chose s'applique pour : //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005_an.py!} ``` //// @@ -338,7 +338,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` //// @@ -356,7 +356,7 @@ Et la même chose pour lt. //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} ``` //// @@ -364,7 +364,7 @@ Et la même chose pour lt. //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.py!} ``` //// @@ -378,7 +378,7 @@ Préférez utiliser la version `Annotated` si possible. /// ```Python hl_lines="11" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` //// diff --git a/docs/fr/docs/tutorial/path-params.md b/docs/fr/docs/tutorial/path-params.md index 94c36a20d..34012c278 100644 --- a/docs/fr/docs/tutorial/path-params.md +++ b/docs/fr/docs/tutorial/path-params.md @@ -5,7 +5,7 @@ Vous pouvez déclarer des "paramètres" ou "variables" de chemin avec la même s ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` La valeur du paramètre `item_id` sera transmise à la fonction dans l'argument `item_id`. @@ -23,7 +23,7 @@ Vous pouvez déclarer le type d'un paramètre de chemin dans la fonction, en uti ```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} +{!../../docs_src/path_params/tutorial002.py!} ``` Ici, `item_id` est déclaré comme `int`. @@ -132,7 +132,7 @@ Et vous avez un second chemin : `/users/{user_id}` pour récupérer de la donné Les *fonctions de chemin* étant évaluées dans l'ordre, il faut s'assurer que la fonction correspondant à `/users/me` est déclarée avant celle de `/users/{user_id}` : ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} +{!../../docs_src/path_params/tutorial003.py!} ``` Sinon, le chemin `/users/{user_id}` correspondrait aussi à `/users/me`, la fonction "croyant" qu'elle a reçu un paramètre `user_id` avec pour valeur `"me"`. @@ -150,7 +150,7 @@ En héritant de `str` la documentation sera capable de savoir que les valeurs do Créez ensuite des attributs de classe avec des valeurs fixes, qui seront les valeurs autorisées pour cette énumération. ```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// info @@ -170,7 +170,7 @@ Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms Créez ensuite un *paramètre de chemin* avec une annotation de type désignant l'énumération créée précédemment (`ModelName`) : ```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` ### Documentation @@ -188,7 +188,7 @@ La valeur du *paramètre de chemin* sera un des "membres" de l'énumération. Vous pouvez comparer ce paramètre avec les membres de votre énumération `ModelName` : ```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` #### Récupérer la *valeur de l'énumération* @@ -196,7 +196,7 @@ Vous pouvez comparer ce paramètre avec les membres de votre énumération `Mode Vous pouvez obtenir la valeur réel d'un membre (une chaîne de caractères ici), avec `model_name.value`, ou en général, `votre_membre_d'enum.value` : ```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// tip | "Astuce" @@ -212,7 +212,7 @@ Vous pouvez retourner des *membres d'énumération* dans vos *fonctions de chemi Ils seront convertis vers leurs valeurs correspondantes (chaînes de caractères ici) avant d'être transmis au client : ```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` Le client recevra une réponse JSON comme celle-ci : @@ -253,7 +253,7 @@ Dans ce cas, le nom du paramètre est `file_path`, et la dernière partie, `:pat Vous pouvez donc l'utilisez comme tel : ```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} +{!../../docs_src/path_params/tutorial004.py!} ``` /// tip | "Astuce" diff --git a/docs/fr/docs/tutorial/query-params-str-validations.md b/docs/fr/docs/tutorial/query-params-str-validations.md index 63578ec40..b71d1548a 100644 --- a/docs/fr/docs/tutorial/query-params-str-validations.md +++ b/docs/fr/docs/tutorial/query-params-str-validations.md @@ -5,7 +5,7 @@ Commençons avec cette application pour exemple : ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial001.py!} +{!../../docs_src/query_params_str_validations/tutorial001.py!} ``` Le paramètre de requête `q` a pour type `Union[str, None]` (ou `str | None` en Python 3.10), signifiant qu'il est de type `str` mais pourrait aussi être égal à `None`, et bien sûr, la valeur par défaut est `None`, donc **FastAPI** saura qu'il n'est pas requis. @@ -27,7 +27,7 @@ Nous allons imposer que bien que `q` soit un paramètre optionnel, dès qu'il es Pour cela, importez d'abord `Query` depuis `fastapi` : ```Python hl_lines="3" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` ## Utiliser `Query` comme valeur par défaut @@ -35,7 +35,7 @@ Pour cela, importez d'abord `Query` depuis `fastapi` : Construisez ensuite la valeur par défaut de votre paramètre avec `Query`, en choisissant 50 comme `max_length` : ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` Comme nous devons remplacer la valeur par défaut `None` dans la fonction par `Query()`, nous pouvons maintenant définir la valeur par défaut avec le paramètre `Query(default=None)`, il sert le même objectif qui est de définir cette valeur par défaut. @@ -87,7 +87,7 @@ Cela va valider les données, montrer une erreur claire si ces dernières ne son Vous pouvez aussi rajouter un second paramètre `min_length` : ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial003.py!} +{!../../docs_src/query_params_str_validations/tutorial003.py!} ``` ## Ajouter des validations par expressions régulières @@ -95,7 +95,7 @@ Vous pouvez aussi rajouter un second paramètre `min_length` : On peut définir une expression régulière à laquelle le paramètre doit correspondre : ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial004.py!} +{!../../docs_src/query_params_str_validations/tutorial004.py!} ``` Cette expression régulière vérifie que la valeur passée comme paramètre : @@ -115,7 +115,7 @@ De la même façon que vous pouvez passer `None` comme premier argument pour l'u Disons que vous déclarez le paramètre `q` comme ayant une longueur minimale de `3`, et une valeur par défaut étant `"fixedquery"` : ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} +{!../../docs_src/query_params_str_validations/tutorial005.py!} ``` /// note | "Rappel" @@ -147,7 +147,7 @@ q: Union[str, None] = Query(default=None, min_length=3) Donc pour déclarer une valeur comme requise tout en utilisant `Query`, il faut utiliser `...` comme premier argument : ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} +{!../../docs_src/query_params_str_validations/tutorial006.py!} ``` /// info @@ -165,7 +165,7 @@ Quand on définit un paramètre de requête explicitement avec `Query` on peut a Par exemple, pour déclarer un paramètre de requête `q` qui peut apparaître plusieurs fois dans une URL, on écrit : ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial011.py!} +{!../../docs_src/query_params_str_validations/tutorial011.py!} ``` Ce qui fait qu'avec une URL comme : @@ -202,7 +202,7 @@ La documentation sera donc mise à jour automatiquement pour autoriser plusieurs Et l'on peut aussi définir une liste de valeurs par défaut si aucune n'est fournie : ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial012.py!} +{!../../docs_src/query_params_str_validations/tutorial012.py!} ``` Si vous allez à : @@ -229,7 +229,7 @@ et la réponse sera : Il est aussi possible d'utiliser directement `list` plutôt que `List[str]` : ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} +{!../../docs_src/query_params_str_validations/tutorial013.py!} ``` /// note @@ -257,13 +257,13 @@ Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnée Vous pouvez ajouter un `title` : ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial007.py!} +{!../../docs_src/query_params_str_validations/tutorial007.py!} ``` Et une `description` : ```Python hl_lines="13" -{!../../../docs_src/query_params_str_validations/tutorial008.py!} +{!../../docs_src/query_params_str_validations/tutorial008.py!} ``` ## Alias de paramètres @@ -285,7 +285,7 @@ Mais vous avez vraiment envie que ce soit exactement `item-query`... Pour cela vous pouvez déclarer un `alias`, et cet alias est ce qui sera utilisé pour trouver la valeur du paramètre : ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial009.py!} +{!../../docs_src/query_params_str_validations/tutorial009.py!} ``` ## Déprécier des paramètres @@ -297,7 +297,7 @@ Il faut qu'il continue à exister pendant un certain temps car vos clients l'uti On utilise alors l'argument `deprecated=True` de `Query` : ```Python hl_lines="18" -{!../../../docs_src/query_params_str_validations/tutorial010.py!} +{!../../docs_src/query_params_str_validations/tutorial010.py!} ``` La documentation le présentera comme il suit : diff --git a/docs/fr/docs/tutorial/query-params.md b/docs/fr/docs/tutorial/query-params.md index b9f1540c9..c847a8f5b 100644 --- a/docs/fr/docs/tutorial/query-params.md +++ b/docs/fr/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ Quand vous déclarez des paramètres dans votre fonction de chemin qui ne font pas partie des paramètres indiqués dans le chemin associé, ces paramètres sont automatiquement considérés comme des paramètres de "requête". ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` La partie appelée requête (ou **query**) dans une URL est l'ensemble des paires clés-valeurs placées après le `?` , séparées par des `&`. @@ -64,7 +64,7 @@ Les valeurs des paramètres de votre fonction seront : De la même façon, vous pouvez définir des paramètres de requête comme optionnels, en leur donnant comme valeur par défaut `None` : ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial002.py!} +{!../../docs_src/query_params/tutorial002.py!} ``` Ici, le paramètre `q` sera optionnel, et aura `None` comme valeur par défaut. @@ -88,7 +88,7 @@ Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI Vous pouvez aussi déclarer des paramètres de requête comme booléens (`bool`), **FastAPI** les convertira : ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial003.py!} +{!../../docs_src/query_params/tutorial003.py!} ``` Avec ce code, en allant sur : @@ -132,7 +132,7 @@ Et vous n'avez pas besoin de les déclarer dans un ordre spécifique. Ils seront détectés par leurs noms : ```Python hl_lines="8 10" -{!../../../docs_src/query_params/tutorial004.py!} +{!../../docs_src/query_params/tutorial004.py!} ``` ## Paramètres de requête requis @@ -144,7 +144,7 @@ Si vous ne voulez pas leur donner de valeur par défaut mais juste les rendre op Mais si vous voulez rendre un paramètre de requête obligatoire, vous pouvez juste ne pas y affecter de valeur par défaut : ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` Ici le paramètre `needy` est un paramètre requis (ou obligatoire) de type `str`. @@ -190,7 +190,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Et bien sur, vous pouvez définir certains paramètres comme requis, certains avec des valeurs par défaut et certains entièrement optionnels : ```Python hl_lines="10" -{!../../../docs_src/query_params/tutorial006.py!} +{!../../docs_src/query_params/tutorial006.py!} ``` Ici, on a donc 3 paramètres de requête : diff --git a/docs/ja/docs/advanced/additional-status-codes.md b/docs/ja/docs/advanced/additional-status-codes.md index 622affa6e..904d539e7 100644 --- a/docs/ja/docs/advanced/additional-status-codes.md +++ b/docs/ja/docs/advanced/additional-status-codes.md @@ -15,7 +15,7 @@ これを達成するには、 `JSONResponse` をインポートし、 `status_code` を設定して直接内容を返します。 ```Python hl_lines="4 25" -{!../../../docs_src/additional_status_codes/tutorial001.py!} +{!../../docs_src/additional_status_codes/tutorial001.py!} ``` /// warning | "注意" diff --git a/docs/ja/docs/advanced/custom-response.md b/docs/ja/docs/advanced/custom-response.md index a7ce6b54d..88269700e 100644 --- a/docs/ja/docs/advanced/custom-response.md +++ b/docs/ja/docs/advanced/custom-response.md @@ -25,7 +25,7 @@ 使いたい `Response` クラス (サブクラス) をインポートし、 *path operationデコレータ* に宣言します。 ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001b.py!} +{!../../docs_src/custom_response/tutorial001b.py!} ``` /// info | "情報" @@ -52,7 +52,7 @@ * *path operation* のパラメータ `content_type` に `HTMLResponse` を渡す。 ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial002.py!} +{!../../docs_src/custom_response/tutorial002.py!} ``` /// info | "情報" @@ -72,7 +72,7 @@ 上記と同じ例において、 `HTMLResponse` を返すと、このようになります: ```Python hl_lines="2 7 19" -{!../../../docs_src/custom_response/tutorial003.py!} +{!../../docs_src/custom_response/tutorial003.py!} ``` /// warning | "注意" @@ -98,7 +98,7 @@ 例えば、このようになります: ```Python hl_lines="7 21 23" -{!../../../docs_src/custom_response/tutorial004.py!} +{!../../docs_src/custom_response/tutorial004.py!} ``` この例では、関数 `generate_html_response()` は、`str` のHTMLを返すのではなく `Response` を生成して返しています。 @@ -139,7 +139,7 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含みます。また、media_typeに基づいたContent-Typeヘッダーを含み、テキストタイプのためにcharsetを追加します。 ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ### `HTMLResponse` @@ -151,7 +151,7 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含 テキストやバイトを受け取り、プレーンテキストのレスポンスを返します。 ```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial005.py!} +{!../../docs_src/custom_response/tutorial005.py!} ``` ### `JSONResponse` @@ -175,7 +175,7 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含 /// ```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001.py!} +{!../../docs_src/custom_response/tutorial001.py!} ``` /// tip | "豆知識" @@ -189,7 +189,7 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含 HTTPリダイレクトを返します。デフォルトでは307ステータスコード (Temporary Redirect) となります。 ```Python hl_lines="2 9" -{!../../../docs_src/custom_response/tutorial006.py!} +{!../../docs_src/custom_response/tutorial006.py!} ``` ### `StreamingResponse` @@ -197,7 +197,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス 非同期なジェネレータか通常のジェネレータ・イテレータを受け取り、レスポンスボディをストリームします。 ```Python hl_lines="2 14" -{!../../../docs_src/custom_response/tutorial007.py!} +{!../../docs_src/custom_response/tutorial007.py!} ``` #### `StreamingResponse` をファイルライクなオブジェクトとともに使う @@ -207,7 +207,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス これにはクラウドストレージとの連携や映像処理など、多くのライブラリが含まれています。 ```Python hl_lines="2 10-12 14" -{!../../../docs_src/custom_response/tutorial008.py!} +{!../../docs_src/custom_response/tutorial008.py!} ``` /// tip | "豆知識" @@ -230,7 +230,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス ファイルレスポンスには、適切な `Content-Length` 、 `Last-Modified` 、 `ETag` ヘッダーが含まれます。 ```Python hl_lines="2 10" -{!../../../docs_src/custom_response/tutorial009.py!} +{!../../docs_src/custom_response/tutorial009.py!} ``` ## デフォルトレスポンスクラス @@ -242,7 +242,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス 以下の例では、 **FastAPI** は、全ての *path operation* で `JSONResponse` の代わりに `ORJSONResponse` をデフォルトとして利用します。 ```Python hl_lines="2 4" -{!../../../docs_src/custom_response/tutorial010.py!} +{!../../docs_src/custom_response/tutorial010.py!} ``` /// tip | "豆知識" diff --git a/docs/ja/docs/advanced/path-operation-advanced-configuration.md b/docs/ja/docs/advanced/path-operation-advanced-configuration.md index ae60126cb..2dab4aec1 100644 --- a/docs/ja/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/ja/docs/advanced/path-operation-advanced-configuration.md @@ -13,7 +13,7 @@ `operation_id` は各オペレーションで一意にする必要があります。 ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} ``` ### *path operation関数* の名前をoperationIdとして使用する @@ -23,7 +23,7 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP そうする場合は、すべての *path operation* を追加した後に行う必要があります。 ```Python hl_lines="2 12-21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` /// tip | "豆知識" @@ -45,7 +45,7 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP 生成されるOpenAPIスキーマ (つまり、自動ドキュメント生成の仕組み) から *path operation* を除外するには、 `include_in_schema` パラメータを `False` にします。 ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} ``` ## docstringによる説明の高度な設定 @@ -57,5 +57,5 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP ドキュメントには表示されませんが、他のツール (例えばSphinx) では残りの部分を利用できるでしょう。 ```Python hl_lines="19-29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} ``` diff --git a/docs/ja/docs/advanced/response-directly.md b/docs/ja/docs/advanced/response-directly.md index 5c25471b1..167d15589 100644 --- a/docs/ja/docs/advanced/response-directly.md +++ b/docs/ja/docs/advanced/response-directly.md @@ -35,7 +35,7 @@ このようなケースでは、レスポンスにデータを含める前に `jsonable_encoder` を使ってデータを変換できます。 ```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` /// note | "技術詳細" @@ -57,7 +57,7 @@ XMLを文字列にし、`Response` に含め、それを返します。 ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ## 備考 diff --git a/docs/ja/docs/advanced/websockets.md b/docs/ja/docs/advanced/websockets.md index 615f9d17c..f7bcb6af3 100644 --- a/docs/ja/docs/advanced/websockets.md +++ b/docs/ja/docs/advanced/websockets.md @@ -39,7 +39,7 @@ $ pip install websockets しかし、これはWebSocketのサーバーサイドに焦点を当て、実用的な例を示す最も簡単な方法です。 ```Python hl_lines="2 6-38 41-43" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` ## `websocket` を作成する @@ -47,7 +47,7 @@ $ pip install websockets **FastAPI** アプリケーションで、`websocket` を作成します。 ```Python hl_lines="1 46-47" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` /// note | "技術詳細" @@ -63,7 +63,7 @@ $ pip install websockets WebSocketルートでは、 `await` を使ってメッセージの送受信ができます。 ```Python hl_lines="48-52" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` バイナリやテキストデータ、JSONデータを送受信できます。 @@ -116,7 +116,7 @@ WebSocketエンドポイントでは、`fastapi` から以下をインポート これらは、他のFastAPI エンドポイント/*path operation* の場合と同じように機能します。 ```Python hl_lines="58-65 68-83" -{!../../../docs_src/websockets/tutorial002.py!} +{!../../docs_src/websockets/tutorial002.py!} ``` /// info | "情報" @@ -165,7 +165,7 @@ $ uvicorn main:app --reload WebSocket接続が閉じられると、 `await websocket.receive_text()` は例外 `WebSocketDisconnect` を発生させ、この例のようにキャッチして処理することができます。 ```Python hl_lines="81-83" -{!../../../docs_src/websockets/tutorial003.py!} +{!../../docs_src/websockets/tutorial003.py!} ``` 試してみるには、 diff --git a/docs/ja/docs/how-to/conditional-openapi.md b/docs/ja/docs/how-to/conditional-openapi.md index b892ed6c6..053d481f7 100644 --- a/docs/ja/docs/how-to/conditional-openapi.md +++ b/docs/ja/docs/how-to/conditional-openapi.md @@ -30,7 +30,7 @@ 例えば、 ```Python hl_lines="6 11" -{!../../../docs_src/conditional_openapi/tutorial001.py!} +{!../../docs_src/conditional_openapi/tutorial001.py!} ``` ここでは `openapi_url` の設定を、デフォルトの `"/openapi.json"` のまま宣言しています。 diff --git a/docs/ja/docs/python-types.md b/docs/ja/docs/python-types.md index 730a209ab..7af6ce0c0 100644 --- a/docs/ja/docs/python-types.md +++ b/docs/ja/docs/python-types.md @@ -23,7 +23,7 @@ 簡単な例から始めてみましょう: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` このプログラムを実行すると以下が出力されます: @@ -39,7 +39,7 @@ John Doe * 真ん中にスペースを入れて連結します。 ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### 編集 @@ -83,7 +83,7 @@ John Doe それが「型ヒント」です: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` これは、以下のようにデフォルト値を宣言するのと同じではありません: @@ -113,7 +113,7 @@ John Doe この関数を見てください。すでに型ヒントを持っています: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` エディタは変数の型を知っているので、補完だけでなく、エラーチェックをすることもできます。 @@ -123,7 +123,7 @@ John Doe これで`age`を`str(age)`で文字列に変換して修正する必要があることがわかります: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## 型の宣言 @@ -144,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### 型パラメータを持つジェネリック型 @@ -162,7 +162,7 @@ John Doe `typing`から`List`をインポートします(大文字の`L`を含む): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` 同じようにコロン(`:`)の構文で変数を宣言します。 @@ -172,7 +172,7 @@ John Doe リストはいくつかの内部の型を含む型なので、それらを角括弧で囲んでいます。 ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` /// tip | "豆知識" @@ -200,7 +200,7 @@ John Doe `tuple`と`set`の宣言も同様です: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` つまり: @@ -218,7 +218,7 @@ John Doe 2番目の型パラメータは`dict`の値です。 ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` つまり: @@ -232,7 +232,7 @@ John Doe また、`Optional`を使用して、変数が`str`のような型を持つことを宣言することもできますが、それは「オプション」であり、`None`にすることもできます。 ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` ただの`str`の代わりに`Optional[str]`を使用することで、エディタは値が常に`str`であると仮定している場合に実際には`None`である可能性があるエラーを検出するのに役立ちます。 @@ -257,13 +257,13 @@ John Doe 例えば、`Person`クラスという名前のクラスがあるとしましょう: ```Python hl_lines="1 2 3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` 変数の型を`Person`として宣言することができます: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` そして、再び、すべてのエディタのサポートを得ることができます: @@ -285,7 +285,7 @@ John Doe Pydanticの公式ドキュメントから引用: ```Python -{!../../../docs_src/python_types/tutorial011.py!} +{!../../docs_src/python_types/tutorial011.py!} ``` /// info | "情報" diff --git a/docs/ja/docs/tutorial/background-tasks.md b/docs/ja/docs/tutorial/background-tasks.md index 6094c370f..6f9340817 100644 --- a/docs/ja/docs/tutorial/background-tasks.md +++ b/docs/ja/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ まず初めに、`BackgroundTasks` をインポートし、` BackgroundTasks` の型宣言と共に、*path operation 関数* のパラメーターを定義します: ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** は、`BackgroundTasks` 型のオブジェクトを作成し、そのパラメーターに渡します。 @@ -34,7 +34,7 @@ また、書き込み操作では `async` と `await` を使用しないため、通常の `def` で関数を定義します。 ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## バックグラウンドタスクの追加 @@ -42,7 +42,7 @@ *path operations 関数* 内で、`.add_task()` メソッドを使用してタスク関数を *background tasks* オブジェクトに渡します。 ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` は以下の引数を受け取ります: @@ -58,7 +58,7 @@ **FastAPI** は、それぞれの場合の処理​​方法と同じオブジェクトの再利用方法を知っているため、すべてのバックグラウンドタスクがマージされ、バックグラウンドで後で実行されます。 ```Python hl_lines="13 15 22 25" -{!../../../docs_src/background_tasks/tutorial002.py!} +{!../../docs_src/background_tasks/tutorial002.py!} ``` この例では、レスポンスが送信された *後* にメッセージが `log.txt` ファイルに書き込まれます。 diff --git a/docs/ja/docs/tutorial/body-fields.md b/docs/ja/docs/tutorial/body-fields.md index b9f6d694b..1d386040a 100644 --- a/docs/ja/docs/tutorial/body-fields.md +++ b/docs/ja/docs/tutorial/body-fields.md @@ -7,7 +7,7 @@ まず、以下のようにインポートします: ```Python hl_lines="4" -{!../../../docs_src/body_fields/tutorial001.py!} +{!../../docs_src/body_fields/tutorial001.py!} ``` /// warning | "注意" @@ -21,7 +21,7 @@ 以下のように`Field`をモデルの属性として使用することができます: ```Python hl_lines="11 12 13 14" -{!../../../docs_src/body_fields/tutorial001.py!} +{!../../docs_src/body_fields/tutorial001.py!} ``` `Field`は`Query`や`Path`、`Body`と同じように動作し、全く同様のパラメータなどを持ちます。 diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md index c051fde24..647143ee5 100644 --- a/docs/ja/docs/tutorial/body-multiple-params.md +++ b/docs/ja/docs/tutorial/body-multiple-params.md @@ -9,7 +9,7 @@ また、デフォルトの`None`を設定することで、ボディパラメータをオプションとして宣言することもできます: ```Python hl_lines="19 20 21" -{!../../../docs_src/body_multiple_params/tutorial001.py!} +{!../../docs_src/body_multiple_params/tutorial001.py!} ``` /// note | "備考" @@ -34,7 +34,7 @@ しかし、`item`と`user`のように複数のボディパラメータを宣言することもできます: ```Python hl_lines="22" -{!../../../docs_src/body_multiple_params/tutorial002.py!} +{!../../docs_src/body_multiple_params/tutorial002.py!} ``` この場合、**FastAPI**は関数内に複数のボディパラメータ(Pydanticモデルである2つのパラメータ)があることに気付きます。 @@ -78,7 +78,7 @@ ```Python hl_lines="23" -{!../../../docs_src/body_multiple_params/tutorial003.py!} +{!../../docs_src/body_multiple_params/tutorial003.py!} ``` この場合、**FastAPI** は以下のようなボディを期待します: @@ -115,7 +115,7 @@ q: str = None 以下において: ```Python hl_lines="27" -{!../../../docs_src/body_multiple_params/tutorial004.py!} +{!../../docs_src/body_multiple_params/tutorial004.py!} ``` /// info | "情報" @@ -139,7 +139,7 @@ item: Item = Body(..., embed=True) 以下において: ```Python hl_lines="17" -{!../../../docs_src/body_multiple_params/tutorial005.py!} +{!../../docs_src/body_multiple_params/tutorial005.py!} ``` この場合、**FastAPI** は以下のようなボディを期待します: diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md index 59ee67295..8703a40e7 100644 --- a/docs/ja/docs/tutorial/body-nested-models.md +++ b/docs/ja/docs/tutorial/body-nested-models.md @@ -7,7 +7,7 @@ 属性をサブタイプとして定義することができます。例えば、Pythonの`list`は以下のように定義できます: ```Python hl_lines="12" -{!../../../docs_src/body_nested_models/tutorial001.py!} +{!../../docs_src/body_nested_models/tutorial001.py!} ``` これにより、各項目の型は宣言されていませんが、`tags`はある項目のリストになります。 @@ -21,7 +21,7 @@ まず、Pythonの標準の`typing`モジュールから`List`をインポートします: ```Python hl_lines="1" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!../../docs_src/body_nested_models/tutorial002.py!} ``` ### タイプパラメータを持つ`List`の宣言 @@ -44,7 +44,7 @@ my_list: List[str] そのため、以下の例では`tags`を具体的な「文字列のリスト」にすることができます: ```Python hl_lines="14" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!../../docs_src/body_nested_models/tutorial002.py!} ``` ## セット型 @@ -56,7 +56,7 @@ my_list: List[str] そのため、以下のように、`Set`をインポートして`str`の`set`として`tags`を宣言することができます: ```Python hl_lines="1 14" -{!../../../docs_src/body_nested_models/tutorial003.py!} +{!../../docs_src/body_nested_models/tutorial003.py!} ``` これを使えば、データが重複しているリクエストを受けた場合でも、ユニークな項目のセットに変換されます。 @@ -80,7 +80,7 @@ Pydanticモデルの各属性には型があります。 例えば、`Image`モデルを定義することができます: ```Python hl_lines="9 10 11" -{!../../../docs_src/body_nested_models/tutorial004.py!} +{!../../docs_src/body_nested_models/tutorial004.py!} ``` ### サブモデルを型として使用 @@ -88,7 +88,7 @@ Pydanticモデルの各属性には型があります。 そして、それを属性の型として使用することができます: ```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial004.py!} +{!../../docs_src/body_nested_models/tutorial004.py!} ``` これは **FastAPI** が以下のようなボディを期待することを意味します: @@ -123,7 +123,7 @@ Pydanticモデルの各属性には型があります。 例えば、`Image`モデルのように`url`フィールドがある場合、`str`の代わりにPydanticの`HttpUrl`を指定することができます: ```Python hl_lines="4 10" -{!../../../docs_src/body_nested_models/tutorial005.py!} +{!../../docs_src/body_nested_models/tutorial005.py!} ``` 文字列は有効なURLであることが確認され、そのようにJSONスキーマ・OpenAPIで文書化されます。 @@ -133,7 +133,7 @@ Pydanticモデルの各属性には型があります。 Pydanticモデルを`list`や`set`などのサブタイプとして使用することもできます: ```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial006.py!} +{!../../docs_src/body_nested_models/tutorial006.py!} ``` これは、次のようなJSONボディを期待します(変換、検証、ドキュメントなど): @@ -173,7 +173,7 @@ Pydanticモデルを`list`や`set`などのサブタイプとして使用する 深くネストされた任意のモデルを定義することができます: ```Python hl_lines="9 14 20 23 27" -{!../../../docs_src/body_nested_models/tutorial007.py!} +{!../../docs_src/body_nested_models/tutorial007.py!} ``` /// info | "情報" @@ -193,7 +193,7 @@ images: List[Image] 以下のように: ```Python hl_lines="15" -{!../../../docs_src/body_nested_models/tutorial008.py!} +{!../../docs_src/body_nested_models/tutorial008.py!} ``` ## あらゆる場所でのエディタサポート @@ -225,7 +225,7 @@ Pydanticモデルではなく、`dict`を直接使用している場合はこの この場合、`int`のキーと`float`の値を持つものであれば、どんな`dict`でも受け入れることができます: ```Python hl_lines="15" -{!../../../docs_src/body_nested_models/tutorial009.py!} +{!../../docs_src/body_nested_models/tutorial009.py!} ``` /// tip | "豆知識" diff --git a/docs/ja/docs/tutorial/body-updates.md b/docs/ja/docs/tutorial/body-updates.md index 672a03a64..fde9f4f5e 100644 --- a/docs/ja/docs/tutorial/body-updates.md +++ b/docs/ja/docs/tutorial/body-updates.md @@ -7,7 +7,7 @@ `jsonable_encoder`を用いて、入力データをJSON形式で保存できるデータに変換することができます(例:NoSQLデータベース)。例えば、`datetime`を`str`に変換します。 ```Python hl_lines="30 31 32 33 34 35" -{!../../../docs_src/body_updates/tutorial001.py!} +{!../../docs_src/body_updates/tutorial001.py!} ``` 既存のデータを置き換えるべきデータを受け取るために`PUT`は使用されます。 @@ -57,7 +57,7 @@ これを使うことで、デフォルト値を省略して、設定された(リクエストで送られた)データのみを含む`dict`を生成することができます: ```Python hl_lines="34" -{!../../../docs_src/body_updates/tutorial002.py!} +{!../../docs_src/body_updates/tutorial002.py!} ``` ### Pydanticの`update`パラメータ @@ -67,7 +67,7 @@ `stored_item_model.copy(update=update_data)`のように: ```Python hl_lines="35" -{!../../../docs_src/body_updates/tutorial002.py!} +{!../../docs_src/body_updates/tutorial002.py!} ``` ### 部分的更新のまとめ @@ -86,7 +86,7 @@ * 更新されたモデルを返します。 ```Python hl_lines="30 31 32 33 34 35 36 37" -{!../../../docs_src/body_updates/tutorial002.py!} +{!../../docs_src/body_updates/tutorial002.py!} ``` /// tip | "豆知識" diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md index 017ff8986..888d4388a 100644 --- a/docs/ja/docs/tutorial/body.md +++ b/docs/ja/docs/tutorial/body.md @@ -23,7 +23,7 @@ GET リクエストでボディを送信することは、仕様では未定義 ます初めに、 `pydantic` から `BaseModel` をインポートする必要があります: ```Python hl_lines="2" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` ## データモデルの作成 @@ -33,7 +33,7 @@ GET リクエストでボディを送信することは、仕様では未定義 すべての属性にpython標準の型を使用します: ```Python hl_lines="5-9" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` クエリパラメータの宣言と同様に、モデル属性がデフォルト値をもつとき、必須な属性ではなくなります。それ以外は必須になります。オプショナルな属性にしたい場合は `None` を使用してください。 @@ -63,7 +63,7 @@ GET リクエストでボディを送信することは、仕様では未定義 *パスオペレーション* に加えるために、パスパラメータやクエリパラメータと同じ様に宣言します: ```Python hl_lines="16" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` ...そして、作成したモデル `Item` で型を宣言します。 @@ -132,7 +132,7 @@ GET リクエストでボディを送信することは、仕様では未定義 関数内部で、モデルの全ての属性に直接アクセスできます: ```Python hl_lines="19" -{!../../../docs_src/body/tutorial002.py!} +{!../../docs_src/body/tutorial002.py!} ``` ## リクエストボディ + パスパラメータ @@ -142,7 +142,7 @@ GET リクエストでボディを送信することは、仕様では未定義 **FastAPI** はパスパラメータである関数パラメータは**パスから受け取り**、Pydanticモデルによって宣言された関数パラメータは**リクエストボディから受け取る**ということを認識します。 ```Python hl_lines="15-16" -{!../../../docs_src/body/tutorial003.py!} +{!../../docs_src/body/tutorial003.py!} ``` ## リクエストボディ + パスパラメータ + クエリパラメータ @@ -152,7 +152,7 @@ GET リクエストでボディを送信することは、仕様では未定義 **FastAPI** はそれぞれを認識し、適切な場所からデータを取得します。 ```Python hl_lines="16" -{!../../../docs_src/body/tutorial004.py!} +{!../../docs_src/body/tutorial004.py!} ``` 関数パラメータは以下の様に認識されます: diff --git a/docs/ja/docs/tutorial/cookie-params.md b/docs/ja/docs/tutorial/cookie-params.md index 212885209..1f45db17c 100644 --- a/docs/ja/docs/tutorial/cookie-params.md +++ b/docs/ja/docs/tutorial/cookie-params.md @@ -7,7 +7,7 @@ まず、`Cookie`をインポートします: ```Python hl_lines="3" -{!../../../docs_src/cookie_params/tutorial001.py!} +{!../../docs_src/cookie_params/tutorial001.py!} ``` ## `Cookie`のパラメータを宣言 @@ -17,7 +17,7 @@ 最初の値がデフォルト値で、追加の検証パラメータや注釈パラメータをすべて渡すことができます: ```Python hl_lines="9" -{!../../../docs_src/cookie_params/tutorial001.py!} +{!../../docs_src/cookie_params/tutorial001.py!} ``` /// note | "技術詳細" diff --git a/docs/ja/docs/tutorial/cors.md b/docs/ja/docs/tutorial/cors.md index 738240342..9530c51bf 100644 --- a/docs/ja/docs/tutorial/cors.md +++ b/docs/ja/docs/tutorial/cors.md @@ -47,7 +47,7 @@ * 特定のHTTPヘッダー、またはワイルドカード `"*"`を使用してすべて許可。 ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` `CORSMiddleware` 実装のデフォルトのパラメータはCORSに関して制限を与えるものになっているので、ブラウザにドメインを跨いで特定のオリジン、メソッド、またはヘッダーを使用可能にするためには、それらを明示的に有効にする必要があります diff --git a/docs/ja/docs/tutorial/debugging.md b/docs/ja/docs/tutorial/debugging.md index 06b8ad277..be0ff81d4 100644 --- a/docs/ja/docs/tutorial/debugging.md +++ b/docs/ja/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ Visual Studio CodeやPyCharmなどを使用して、エディター上でデバ FastAPIアプリケーション上で、`uvicorn` を直接インポートして実行します: ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### `__name__ == "__main__"` について diff --git a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md index 69b67d042..fb23a7b2b 100644 --- a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md @@ -7,7 +7,7 @@ 前の例では、依存関係("dependable")から`dict`を返していました: ```Python hl_lines="9" -{!../../../docs_src/dependencies/tutorial001.py!} +{!../../docs_src/dependencies/tutorial001.py!} ``` しかし、*path operation関数*のパラメータ`commons`に`dict`が含まれています。 @@ -72,19 +72,19 @@ FastAPIが実際にチェックしているのは、それが「呼び出し可 そこで、上で紹介した依存関係の`common_parameters`を`CommonQueryParams`クラスに変更します: ```Python hl_lines="11 12 13 14 15" -{!../../../docs_src/dependencies/tutorial002.py!} +{!../../docs_src/dependencies/tutorial002.py!} ``` クラスのインスタンスを作成するために使用される`__init__`メソッドに注目してください: ```Python hl_lines="12" -{!../../../docs_src/dependencies/tutorial002.py!} +{!../../docs_src/dependencies/tutorial002.py!} ``` ...以前の`common_parameters`と同じパラメータを持っています: ```Python hl_lines="8" -{!../../../docs_src/dependencies/tutorial001.py!} +{!../../docs_src/dependencies/tutorial001.py!} ``` これらのパラメータは **FastAPI** が依存関係を「解決」するために使用するものです。 @@ -102,7 +102,7 @@ FastAPIが実際にチェックしているのは、それが「呼び出し可 これで、このクラスを使用して依存関係を宣言することができます。 ```Python hl_lines="19" -{!../../../docs_src/dependencies/tutorial002.py!} +{!../../docs_src/dependencies/tutorial002.py!} ``` **FastAPI** は`CommonQueryParams`クラスを呼び出します。これにより、そのクラスの「インスタンス」が作成され、インスタンスはパラメータ`commons`として関数に渡されます。 @@ -144,7 +144,7 @@ commons = Depends(CommonQueryParams) 以下にあるように: ```Python hl_lines="19" -{!../../../docs_src/dependencies/tutorial003.py!} +{!../../docs_src/dependencies/tutorial003.py!} ``` しかし、型を宣言することは推奨されています。そうすれば、エディタは`commons`のパラメータとして何が渡されるかを知ることができ、コードの補完や型チェックなどを行うのに役立ちます: @@ -180,7 +180,7 @@ commons: CommonQueryParams = Depends() 同じ例では以下のようになります: ```Python hl_lines="19" -{!../../../docs_src/dependencies/tutorial004.py!} +{!../../docs_src/dependencies/tutorial004.py!} ``` ...そして **FastAPI** は何をすべきか知っています。 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index c6472cab5..59f21c3df 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -15,7 +15,7 @@ それは`Depends()`の`list`であるべきです: ```Python hl_lines="17" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` これらの依存関係は、通常の依存関係と同様に実行・解決されます。しかし、それらの値(何かを返す場合)は*path operation関数*には渡されません。 @@ -39,7 +39,7 @@ これらはリクエストの要件(ヘッダのようなもの)やその他のサブ依存関係を宣言することができます: ```Python hl_lines="6 11" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ### 例外の発生 @@ -47,7 +47,7 @@ これらの依存関係は通常の依存関係と同じように、例外を`raise`発生させることができます: ```Python hl_lines="8 13" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ### 戻り値 @@ -57,7 +57,7 @@ つまり、すでにどこかで使っている通常の依存関係(値を返すもの)を再利用することができ、値は使われなくても依存関係は実行されます: ```Python hl_lines="9 14" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ## *path operations*のグループに対する依存関係 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md index 3f22a7a7b..7ef1caf0d 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md @@ -42,19 +42,19 @@ pip install async-exit-stack async-generator レスポンスを送信する前に`yield`文を含む前のコードのみが実行されます。 ```Python hl_lines="2 3 4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` 生成された値は、*path operations*や他の依存関係に注入されるものです: ```Python hl_lines="4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` `yield`文に続くコードは、レスポンスが送信された後に実行されます: ```Python hl_lines="5 6" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` /// tip | "豆知識" @@ -76,7 +76,7 @@ pip install async-exit-stack async-generator 同様に、`finally`を用いて例外があったかどうかにかかわらず、終了ステップを確実に実行することができます。 ```Python hl_lines="3 5" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` ## `yield`を持つサブ依存関係 @@ -88,7 +88,7 @@ pip install async-exit-stack async-generator 例えば、`dependency_c`は`dependency_b`と`dependency_b`に依存する`dependency_a`に、依存することができます: ```Python hl_lines="4 12 20" -{!../../../docs_src/dependencies/tutorial008.py!} +{!../../docs_src/dependencies/tutorial008.py!} ``` そして、それらはすべて`yield`を使用することができます。 @@ -98,7 +98,7 @@ pip install async-exit-stack async-generator そして、`dependency_b`は`dependency_a`(ここでは`dep_a`という名前)の値を終了コードで利用できるようにする必要があります。 ```Python hl_lines="16 17 24 25" -{!../../../docs_src/dependencies/tutorial008.py!} +{!../../docs_src/dependencies/tutorial008.py!} ``` 同様に、`yield`と`return`が混在した依存関係を持つこともできます。 @@ -234,7 +234,7 @@ Pythonでは、`typing.Union`を使用します: ```Python hl_lines="1 14 15 18 19 20 33" -{!../../../docs_src/extra_models/tutorial003.py!} +{!../../docs_src/extra_models/tutorial003.py!} ``` ## モデルのリスト @@ -179,7 +179,7 @@ OpenAPIでは`anyOf`で定義されます。 そのためには、標準のPythonの`typing.List`を使用する: ```Python hl_lines="1 20" -{!../../../docs_src/extra_models/tutorial004.py!} +{!../../docs_src/extra_models/tutorial004.py!} ``` ## 任意の`dict`を持つレスポンス @@ -191,7 +191,7 @@ OpenAPIでは`anyOf`で定義されます。 この場合、`typing.Dict`を使用することができます: ```Python hl_lines="1 8" -{!../../../docs_src/extra_models/tutorial005.py!} +{!../../docs_src/extra_models/tutorial005.py!} ``` ## まとめ diff --git a/docs/ja/docs/tutorial/first-steps.md b/docs/ja/docs/tutorial/first-steps.md index dbe8e4518..77f3b5fbe 100644 --- a/docs/ja/docs/tutorial/first-steps.md +++ b/docs/ja/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ 最もシンプルなFastAPIファイルは以下のようになります: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` これを`main.py`にコピーします。 @@ -134,7 +134,7 @@ OpenAPIスキーマは、FastAPIに含まれている2つのインタラクテ ### Step 1: `FastAPI`をインポート ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI`は、APIのすべての機能を提供するPythonクラスです。 @@ -150,7 +150,7 @@ OpenAPIスキーマは、FastAPIに含まれている2つのインタラクテ ### Step 2: `FastAPI`の「インスタンス」を生成 ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` ここで、`app`変数が`FastAPI`クラスの「インスタンス」になります。 @@ -171,7 +171,7 @@ $ uvicorn main:app --reload 以下のようなアプリを作成したとき: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` そして、それを`main.py`ファイルに置き、次のように`uvicorn`を呼び出します: @@ -250,7 +250,7 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを #### *パスオペレーションデコレータ*を定義 ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `@app.get("/")`は直下の関数が下記のリクエストの処理を担当することを**FastAPI**に伝えます: @@ -305,7 +305,7 @@ Pythonにおける`@something`シンタックスはデコレータと呼ばれ * **関数**: 「デコレータ」の直下にある関数 (`@app.get("/")`の直下) です。 ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` これは、Pythonの関数です。 @@ -319,7 +319,7 @@ Pythonにおける`@something`シンタックスはデコレータと呼ばれ `async def`の代わりに通常の関数として定義することもできます: ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` /// note | "備考" @@ -331,7 +331,7 @@ Pythonにおける`@something`シンタックスはデコレータと呼ばれ ### Step 5: コンテンツの返信 ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `dict`、`list`、`str`、`int`などを返すことができます。 diff --git a/docs/ja/docs/tutorial/handling-errors.md b/docs/ja/docs/tutorial/handling-errors.md index 8be054858..e94f16b21 100644 --- a/docs/ja/docs/tutorial/handling-errors.md +++ b/docs/ja/docs/tutorial/handling-errors.md @@ -26,7 +26,7 @@ HTTPレスポンスをエラーでクライアントに返すには、`HTTPExcep ### `HTTPException`のインポート ```Python hl_lines="1" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### コード内での`HTTPException`の発生 @@ -42,7 +42,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 この例では、クライアントが存在しないIDでアイテムを要求した場合、`404`のステータスコードを持つ例外を発生させます: ```Python hl_lines="11" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### レスポンス結果 @@ -82,7 +82,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 しかし、高度なシナリオのために必要な場合には、カスタムヘッダーを追加することができます: ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial002.py!} +{!../../docs_src/handling_errors/tutorial002.py!} ``` ## カスタム例外ハンドラのインストール @@ -96,7 +96,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 カスタム例外ハンドラを`@app.exception_handler()`で追加することができます: ```Python hl_lines="5 6 7 13 14 15 16 17 18 24" -{!../../../docs_src/handling_errors/tutorial003.py!} +{!../../docs_src/handling_errors/tutorial003.py!} ``` ここで、`/unicorns/yolo`をリクエストすると、*path operation*は`UnicornException`を`raise`します。 @@ -136,7 +136,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 この例外ハンドラは`Requset`と例外を受け取ります。 ```Python hl_lines="2 14 15 16" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` これで、`/items/foo`にアクセスすると、デフォルトのJSONエラーの代わりに以下が返されます: @@ -189,7 +189,7 @@ path -> item_id 例えば、これらのエラーに対しては、JSONではなくプレーンテキストを返すようにすることができます: ```Python hl_lines="3 4 9 10 11 22" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` /// note | "技術詳細" @@ -207,7 +207,7 @@ path -> item_id アプリ開発中に本体のログを取ってデバッグしたり、ユーザーに返したりなどに使用することができます。 ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial005.py!} +{!../../docs_src/handling_errors/tutorial005.py!} ``` ここで、以下のような無効な項目を送信してみてください: @@ -269,7 +269,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException デフォルトの例外ハンドラを`fastapi.exception_handlers`からインポートして再利用することができます: ```Python hl_lines="2 3 4 5 15 21" -{!../../../docs_src/handling_errors/tutorial006.py!} +{!../../docs_src/handling_errors/tutorial006.py!} ``` この例では、非常に表現力のあるメッセージでエラーを`print`しています。 diff --git a/docs/ja/docs/tutorial/header-params.md b/docs/ja/docs/tutorial/header-params.md index 4fab3d423..3180b78b5 100644 --- a/docs/ja/docs/tutorial/header-params.md +++ b/docs/ja/docs/tutorial/header-params.md @@ -7,7 +7,7 @@ まず、`Header`をインポートします: ```Python hl_lines="3" -{!../../../docs_src/header_params/tutorial001.py!} +{!../../docs_src/header_params/tutorial001.py!} ``` ## `Header`のパラメータの宣言 @@ -17,7 +17,7 @@ 最初の値がデフォルト値で、追加の検証パラメータや注釈パラメータをすべて渡すことができます。 ```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial001.py!} +{!../../docs_src/header_params/tutorial001.py!} ``` /// note | "技術詳細" @@ -51,7 +51,7 @@ もしなんらかの理由でアンダースコアからハイフンへの自動変換を無効にする必要がある場合は、`Header`の`convert_underscores`に`False`を設定してください: ```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial002.py!} +{!../../docs_src/header_params/tutorial002.py!} ``` /// warning | "注意" @@ -71,7 +71,7 @@ 例えば、複数回出現する可能性のある`X-Token`のヘッダを定義するには、以下のように書くことができます: ```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial003.py!} +{!../../docs_src/header_params/tutorial003.py!} ``` もし、その*path operation*で通信する場合は、次のように2つのHTTPヘッダーを送信します: diff --git a/docs/ja/docs/tutorial/metadata.md b/docs/ja/docs/tutorial/metadata.md index eb85dc389..8285b479e 100644 --- a/docs/ja/docs/tutorial/metadata.md +++ b/docs/ja/docs/tutorial/metadata.md @@ -14,7 +14,7 @@ これらを設定するには、パラメータ `title`、`description`、`version` を使用します: ```Python hl_lines="4-6" -{!../../../docs_src/metadata/tutorial001.py!} +{!../../docs_src/metadata/tutorial001.py!} ``` この設定では、自動APIドキュメントは以下の様になります: @@ -42,7 +42,7 @@ タグのためのメタデータを作成し、それを `openapi_tags` パラメータに渡します。 ```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` 説明文 (description) の中で Markdown を使用できることに注意してください。たとえば、「login」は太字 (**login**) で表示され、「fancy」は斜体 (_fancy_) で表示されます。 @@ -58,7 +58,7 @@ `tags` パラメーターを使用して、それぞれの *path operations* (および `APIRouter`) を異なるタグに割り当てます: ```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` /// info | "情報" @@ -88,7 +88,7 @@ たとえば、`/api/v1/openapi.json` で提供されるように設定するには: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} +{!../../docs_src/metadata/tutorial002.py!} ``` OpenAPIスキーマを完全に無効にする場合は、`openapi_url=None` を設定できます。これにより、それを使用するドキュメントUIも無効になります。 @@ -107,5 +107,5 @@ OpenAPIスキーマを完全に無効にする場合は、`openapi_url=None` を たとえば、`/documentation` でSwagger UIが提供されるように設定し、ReDocを無効にするには: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} +{!../../docs_src/metadata/tutorial003.py!} ``` diff --git a/docs/ja/docs/tutorial/middleware.md b/docs/ja/docs/tutorial/middleware.md index 05e1b7a8c..f4a503720 100644 --- a/docs/ja/docs/tutorial/middleware.md +++ b/docs/ja/docs/tutorial/middleware.md @@ -32,7 +32,7 @@ * その後、`response` を返す前にさらに `response` を変更することもできます。 ```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` /// tip | "豆知識" @@ -60,7 +60,7 @@ 例えば、リクエストの処理とレスポンスの生成にかかった秒数を含むカスタムヘッダー `X-Process-Time` を追加できます: ```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` ## その他のミドルウェア diff --git a/docs/ja/docs/tutorial/path-operation-configuration.md b/docs/ja/docs/tutorial/path-operation-configuration.md index def12bd08..7eceb377d 100644 --- a/docs/ja/docs/tutorial/path-operation-configuration.md +++ b/docs/ja/docs/tutorial/path-operation-configuration.md @@ -17,7 +17,7 @@ しかし、それぞれの番号コードが何のためのものか覚えていない場合は、`status`のショートカット定数を使用することができます: ```Python hl_lines="3 17" -{!../../../docs_src/path_operation_configuration/tutorial001.py!} +{!../../docs_src/path_operation_configuration/tutorial001.py!} ``` そのステータスコードはレスポンスで使用され、OpenAPIスキーマに追加されます。 @@ -35,7 +35,7 @@ `tags`パラメータを`str`の`list`(通常は1つの`str`)と一緒に渡すと、*path operation*にタグを追加できます: ```Python hl_lines="17 22 27" -{!../../../docs_src/path_operation_configuration/tutorial002.py!} +{!../../docs_src/path_operation_configuration/tutorial002.py!} ``` これらはOpenAPIスキーマに追加され、自動ドキュメントのインターフェースで使用されます: @@ -47,7 +47,7 @@ `summary`と`description`を追加できます: ```Python hl_lines="20-21" -{!../../../docs_src/path_operation_configuration/tutorial003.py!} +{!../../docs_src/path_operation_configuration/tutorial003.py!} ``` ## docstringを用いた説明 @@ -57,7 +57,7 @@ docstringにMarkdownを記述すれば、正しく解釈されて表示されます。(docstringのインデントを考慮して) ```Python hl_lines="19-27" -{!../../../docs_src/path_operation_configuration/tutorial004.py!} +{!../../docs_src/path_operation_configuration/tutorial004.py!} ``` これは対話的ドキュメントで使用されます: @@ -69,7 +69,7 @@ docstringにdeprecatedとしてマークする必要があるが、それを削除しない場合は、`deprecated`パラメータを渡します: ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` 対話的ドキュメントでは非推奨と明記されます: diff --git a/docs/ja/docs/tutorial/path-params-numeric-validations.md b/docs/ja/docs/tutorial/path-params-numeric-validations.md index 9f0b72585..42fbb2ee2 100644 --- a/docs/ja/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ja/docs/tutorial/path-params-numeric-validations.md @@ -7,7 +7,7 @@ まず初めに、`fastapi`から`Path`をインポートします: ```Python hl_lines="1" -{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` ## メタデータの宣言 @@ -17,7 +17,7 @@ 例えば、パスパラメータ`item_id`に対して`title`のメタデータを宣言するには以下のようにします: ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` /// note | "備考" @@ -47,7 +47,7 @@ Pythonは「デフォルト」を持たない値の前に「デフォルト」 そのため、以下のように関数を宣言することができます: ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` ## 必要に応じてパラメータを並び替えるトリック @@ -59,7 +59,7 @@ Pythonは「デフォルト」を持たない値の前に「デフォルト」 Pythonはその`*`で何かをすることはありませんが、それ以降のすべてのパラメータがキーワード引数(キーと値のペア)として呼ばれるべきものであると知っているでしょう。それはkwargsとしても知られています。たとえデフォルト値がなくても。 ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ## 数値の検証: 以上 @@ -69,7 +69,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなれけばなりません。 ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` ## 数値の検証: より大きいと小なりイコール @@ -80,7 +80,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 * `le`: 小なりイコール(`l`ess than or `e`qual) ```Python hl_lines="9" -{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` ## 数値の検証: 浮動小数点、 大なり小なり @@ -94,7 +94,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 これはltも同じです。 ```Python hl_lines="11" -{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` ## まとめ diff --git a/docs/ja/docs/tutorial/path-params.md b/docs/ja/docs/tutorial/path-params.md index 0a7916012..e1cb67a13 100644 --- a/docs/ja/docs/tutorial/path-params.md +++ b/docs/ja/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメータ」や「パス変数」を宣言できます: ```Python hl_lines="6 7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` パスパラメータ `item_id` の値は、引数 `item_id` として関数に渡されます。 @@ -19,7 +19,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー 標準のPythonの型アノテーションを使用して、関数内のパスパラメータの型を宣言できます: ```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} +{!../../docs_src/path_params/tutorial002.py!} ``` ここでは、 `item_id` は `int` として宣言されています。 @@ -122,7 +122,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー *path operations* は順に評価されるので、 `/users/me` が `/users/{user_id}` よりも先に宣言されているか確認する必要があります: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} +{!../../docs_src/path_params/tutorial003.py!} ``` それ以外の場合、 `/users/{users_id}` は `/users/me` としてもマッチします。値が「"me"」であるパラメータ `user_id` を受け取ると「考え」ます。 @@ -140,7 +140,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー そして、固定値のクラス属性を作ります。すると、その値が使用可能な値となります: ```Python hl_lines="1 6 7 8 9" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// info | "情報" @@ -160,7 +160,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー 次に、作成したenumクラスである`ModelName`を使用した型アノテーションをもつ*パスパラメータ*を作成します: ```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` ### ドキュメントの確認 @@ -178,7 +178,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー これは、作成した列挙型 `ModelName` の*列挙型メンバ*と比較できます: ```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` #### *列挙値*の取得 @@ -186,7 +186,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー `model_name.value` 、もしくは一般に、 `your_enum_member.value` を使用して実際の値 (この場合は `str`) を取得できます。 ```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// tip | "豆知識" @@ -202,7 +202,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー それらはクライアントに返される前に適切な値 (この場合は文字列) に変換されます。 ```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` クライアントは以下の様なJSONレスポンスを得ます: @@ -243,7 +243,7 @@ Starletteのオプションを直接使用することで、以下のURLの様 したがって、以下の様に使用できます: ```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} +{!../../docs_src/path_params/tutorial004.py!} ``` /// tip | "豆知識" diff --git a/docs/ja/docs/tutorial/query-params-str-validations.md b/docs/ja/docs/tutorial/query-params-str-validations.md index ada048844..9e54a6f55 100644 --- a/docs/ja/docs/tutorial/query-params-str-validations.md +++ b/docs/ja/docs/tutorial/query-params-str-validations.md @@ -5,7 +5,7 @@ 以下のアプリケーションを例にしてみましょう: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial001.py!} +{!../../docs_src/query_params_str_validations/tutorial001.py!} ``` クエリパラメータ `q` は `Optional[str]` 型で、`None` を許容する `str` 型を意味しており、デフォルトは `None` です。そのため、FastAPIはそれが必須ではないと理解します。 @@ -27,7 +27,7 @@ FastAPIは、 `q` はデフォルト値が `=None` であるため、必須で そのために、まずは`fastapi`から`Query`をインポートします: ```Python hl_lines="3" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` ## デフォルト値として`Query`を使用 @@ -35,7 +35,7 @@ FastAPIは、 `q` はデフォルト値が `=None` であるため、必須で パラメータのデフォルト値として使用し、パラメータ`max_length`を50に設定します: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` デフォルト値`None`を`Query(default=None)`に置き換える必要があるので、`Query`の最初の引数はデフォルト値を定義するのと同じです。 @@ -87,7 +87,7 @@ q: Union[str, None] = Query(default=None, max_length=50) パラメータ`min_length`も追加することができます: ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial003.py!} +{!../../docs_src/query_params_str_validations/tutorial003.py!} ``` ## 正規表現の追加 @@ -95,7 +95,7 @@ q: Union[str, None] = Query(default=None, max_length=50) パラメータが一致するべき正規表現を定義することができます: ```Python hl_lines="11" -{!../../../docs_src/query_params_str_validations/tutorial004.py!} +{!../../docs_src/query_params_str_validations/tutorial004.py!} ``` この特定の正規表現は受け取ったパラメータの値をチェックします: @@ -115,7 +115,7 @@ q: Union[str, None] = Query(default=None, max_length=50) クエリパラメータ`q`の`min_length`を`3`とし、デフォルト値を`fixedquery`としてみましょう: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} +{!../../docs_src/query_params_str_validations/tutorial005.py!} ``` /// note | "備考" @@ -147,7 +147,7 @@ q: Union[str, None] = Query(default=None, min_length=3) そのため、`Query`を使用して必須の値を宣言する必要がある場合は、第一引数に`...`を使用することができます: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} +{!../../docs_src/query_params_str_validations/tutorial006.py!} ``` /// info | "情報" @@ -165,7 +165,7 @@ q: Union[str, None] = Query(default=None, min_length=3) 例えば、URL内に複数回出現するクエリパラメータ`q`を宣言するには以下のように書きます: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial011.py!} +{!../../docs_src/query_params_str_validations/tutorial011.py!} ``` そしてURLは以下です: @@ -202,7 +202,7 @@ http://localhost:8000/items/?q=foo&q=bar また、値が指定されていない場合はデフォルトの`list`を定義することもできます。 ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial012.py!} +{!../../docs_src/query_params_str_validations/tutorial012.py!} ``` 以下のURLを開くと: @@ -227,7 +227,7 @@ http://localhost:8000/items/ `List[str]`の代わりに直接`list`を使うこともできます: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} +{!../../docs_src/query_params_str_validations/tutorial013.py!} ``` /// note | "備考" @@ -255,13 +255,13 @@ http://localhost:8000/items/ `title`を追加できます: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial007.py!} +{!../../docs_src/query_params_str_validations/tutorial007.py!} ``` `description`を追加できます: ```Python hl_lines="13" -{!../../../docs_src/query_params_str_validations/tutorial008.py!} +{!../../docs_src/query_params_str_validations/tutorial008.py!} ``` ## エイリアスパラメータ @@ -283,7 +283,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems それならば、`alias`を宣言することができます。エイリアスはパラメータの値を見つけるのに使用されます: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial009.py!} +{!../../docs_src/query_params_str_validations/tutorial009.py!} ``` ## 非推奨パラメータ @@ -295,7 +295,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems その場合、`Query`にパラメータ`deprecated=True`を渡します: ```Python hl_lines="18" -{!../../../docs_src/query_params_str_validations/tutorial010.py!} +{!../../docs_src/query_params_str_validations/tutorial010.py!} ``` ドキュメントは以下のようになります: diff --git a/docs/ja/docs/tutorial/query-params.md b/docs/ja/docs/tutorial/query-params.md index c0eb2d096..6d41d3742 100644 --- a/docs/ja/docs/tutorial/query-params.md +++ b/docs/ja/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ パスパラメータではない関数パラメータを宣言すると、それらは自動的に "クエリ" パラメータとして解釈されます。 ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` クエリはURL内で `?` の後に続くキーとバリューの組で、 `&` で区切られています。 @@ -64,7 +64,7 @@ http://127.0.0.1:8000/items/?skip=20 同様に、デフォルト値を `None` とすることで、オプショナルなクエリパラメータを宣言できます: ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial002.py!} +{!../../docs_src/query_params/tutorial002.py!} ``` この場合、関数パラメータ `q` はオプショナルとなり、デフォルトでは `None` になります。 @@ -80,7 +80,7 @@ http://127.0.0.1:8000/items/?skip=20 `bool` 型も宣言できます。これは以下の様に変換されます: ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial003.py!} +{!../../docs_src/query_params/tutorial003.py!} ``` この場合、以下にアクセスすると: @@ -124,7 +124,7 @@ http://127.0.0.1:8000/items/foo?short=yes 名前で判別されます: ```Python hl_lines="8 10" -{!../../../docs_src/query_params/tutorial004.py!} +{!../../docs_src/query_params/tutorial004.py!} ``` ## 必須のクエリパラメータ @@ -136,7 +136,7 @@ http://127.0.0.1:8000/items/foo?short=yes しかしクエリパラメータを必須にしたい場合は、ただデフォルト値を宣言しなければよいです: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` ここで、クエリパラメータ `needy` は `str` 型の必須のクエリパラメータです @@ -182,7 +182,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy そして当然、あるパラメータを必須に、別のパラメータにデフォルト値を設定し、また別のパラメータをオプショナルにできます: ```Python hl_lines="10" -{!../../../docs_src/query_params/tutorial006.py!} +{!../../docs_src/query_params/tutorial006.py!} ``` この場合、3つのクエリパラメータがあります。: diff --git a/docs/ja/docs/tutorial/request-forms-and-files.md b/docs/ja/docs/tutorial/request-forms-and-files.md index d8effc219..e03b9166d 100644 --- a/docs/ja/docs/tutorial/request-forms-and-files.md +++ b/docs/ja/docs/tutorial/request-forms-and-files.md @@ -13,7 +13,7 @@ ## `File`と`Form`のインポート ```Python hl_lines="1" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` ## `File`と`Form`のパラメータの定義 @@ -21,7 +21,7 @@ ファイルやフォームのパラメータは`Body`や`Query`の場合と同じように作成します: ```Python hl_lines="8" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` ファイルとフォームフィールドがフォームデータとしてアップロードされ、ファイルとフォームフィールドを受け取ります。 diff --git a/docs/ja/docs/tutorial/request-forms.md b/docs/ja/docs/tutorial/request-forms.md index d04dc810b..eb453c04a 100644 --- a/docs/ja/docs/tutorial/request-forms.md +++ b/docs/ja/docs/tutorial/request-forms.md @@ -15,7 +15,7 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用し `fastapi`から`Form`をインポートします: ```Python hl_lines="1" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` ## `Form`のパラメータの定義 @@ -23,7 +23,7 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用し `Body`や`Query`の場合と同じようにフォームパラメータを作成します: ```Python hl_lines="7" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` 例えば、OAuth2仕様が使用できる方法の1つ(「パスワードフロー」と呼ばれる)では、フォームフィールドとして`username`と`password`を送信する必要があります。 diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md index 7bb5e2825..973f893de 100644 --- a/docs/ja/docs/tutorial/response-model.md +++ b/docs/ja/docs/tutorial/response-model.md @@ -9,7 +9,7 @@ * など。 ```Python hl_lines="17" -{!../../../docs_src/response_model/tutorial001.py!} +{!../../docs_src/response_model/tutorial001.py!} ``` /// note | "備考" @@ -42,13 +42,13 @@ FastAPIは`response_model`を使って以下のことをします: ここでは`UserIn`モデルを宣言しています。それには平文のパスワードが含まれています: ```Python hl_lines="9 11" -{!../../../docs_src/response_model/tutorial002.py!} +{!../../docs_src/response_model/tutorial002.py!} ``` そして、このモデルを使用して入力を宣言し、同じモデルを使って出力を宣言しています: ```Python hl_lines="17 18" -{!../../../docs_src/response_model/tutorial002.py!} +{!../../docs_src/response_model/tutorial002.py!} ``` これで、ブラウザがパスワードを使ってユーザーを作成する際に、APIがレスポンスで同じパスワードを返すようになりました。 @@ -68,19 +68,19 @@ FastAPIは`response_model`を使って以下のことをします: 代わりに、平文のパスワードを持つ入力モデルと、パスワードを持たない出力モデルを作成することができます: ```Python hl_lines="9 11 16" -{!../../../docs_src/response_model/tutorial003.py!} +{!../../docs_src/response_model/tutorial003.py!} ``` ここでは、*path operation関数*がパスワードを含む同じ入力ユーザーを返しているにもかかわらず: ```Python hl_lines="24" -{!../../../docs_src/response_model/tutorial003.py!} +{!../../docs_src/response_model/tutorial003.py!} ``` ...`response_model`を`UserOut`と宣言したことで、パスワードが含まれていません: ```Python hl_lines="22" -{!../../../docs_src/response_model/tutorial003.py!} +{!../../docs_src/response_model/tutorial003.py!} ``` そのため、**FastAPI** は出力モデルで宣言されていない全てのデータをフィルタリングしてくれます(Pydanticを使用)。 @@ -100,7 +100,7 @@ FastAPIは`response_model`を使って以下のことをします: レスポンスモデルにはデフォルト値を設定することができます: ```Python hl_lines="11 13 14" -{!../../../docs_src/response_model/tutorial004.py!} +{!../../docs_src/response_model/tutorial004.py!} ``` * `description: str = None`は`None`がデフォルト値です。 @@ -116,7 +116,7 @@ FastAPIは`response_model`を使って以下のことをします: *path operation デコレータ*に`response_model_exclude_unset=True`パラメータを設定することができます: ```Python hl_lines="24" -{!../../../docs_src/response_model/tutorial004.py!} +{!../../docs_src/response_model/tutorial004.py!} ``` そして、これらのデフォルト値はレスポンスに含まれず、実際に設定された値のみが含まれます。 @@ -206,7 +206,7 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d /// ```Python hl_lines="31 37" -{!../../../docs_src/response_model/tutorial005.py!} +{!../../docs_src/response_model/tutorial005.py!} ``` /// tip | "豆知識" @@ -222,7 +222,7 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d もし`set`を使用することを忘れて、代わりに`list`や`tuple`を使用しても、FastAPIはそれを`set`に変換して正しく動作します: ```Python hl_lines="31 37" -{!../../../docs_src/response_model/tutorial006.py!} +{!../../docs_src/response_model/tutorial006.py!} ``` ## まとめ diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md index 945767894..90b290887 100644 --- a/docs/ja/docs/tutorial/response-status-code.md +++ b/docs/ja/docs/tutorial/response-status-code.md @@ -9,7 +9,7 @@ * など。 ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` /// note | "備考" @@ -77,7 +77,7 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス 先ほどの例をもう一度見てみましょう: ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` `201`は「作成完了」のためのステータスコードです。 @@ -87,7 +87,7 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス `fastapi.status`の便利な変数を利用することができます。 ```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} +{!../../docs_src/response_status_code/tutorial002.py!} ``` それらは便利です。それらは同じ番号を保持しており、その方法ではエディタの自動補完を使用してそれらを見つけることができます。 diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md index a3cd5eb54..baf1bbedd 100644 --- a/docs/ja/docs/tutorial/schema-extra-example.md +++ b/docs/ja/docs/tutorial/schema-extra-example.md @@ -11,7 +11,7 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 Pydanticのドキュメント: スキーマのカスタマイズで説明されているように、`Config`と`schema_extra`を使ってPydanticモデルの例を宣言することができます: ```Python hl_lines="15 16 17 18 19 20 21 22 23" -{!../../../docs_src/schema_extra_example/tutorial001.py!} +{!../../docs_src/schema_extra_example/tutorial001.py!} ``` その追加情報はそのまま出力され、JSON Schemaに追加されます。 @@ -21,7 +21,7 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 後述する`Field`、`Path`、`Query`、`Body`などでは、任意の引数を関数に渡すことでJSON Schemaの追加情報を宣言することもできます: ```Python hl_lines="4 10 11 12 13" -{!../../../docs_src/schema_extra_example/tutorial002.py!} +{!../../docs_src/schema_extra_example/tutorial002.py!} ``` /// warning | "注意" @@ -37,7 +37,7 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 例えば、`Body`にボディリクエストの`example`を渡すことができます: ```Python hl_lines="21 22 23 24 25 26" -{!../../../docs_src/schema_extra_example/tutorial003.py!} +{!../../docs_src/schema_extra_example/tutorial003.py!} ``` ## ドキュメントのUIの例 diff --git a/docs/ja/docs/tutorial/security/first-steps.md b/docs/ja/docs/tutorial/security/first-steps.md index c78a3755e..51f7bf829 100644 --- a/docs/ja/docs/tutorial/security/first-steps.md +++ b/docs/ja/docs/tutorial/security/first-steps.md @@ -21,7 +21,7 @@ `main.py`に、下記の例をコピーします: ```Python -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` ## 実行 @@ -129,7 +129,7 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー `OAuth2PasswordBearer` クラスのインスタンスを作成する時に、パラメーター`tokenUrl`を渡します。このパラメーターには、クライアント (ユーザーのブラウザで動作するフロントエンド) がトークンを取得するために`ユーザー名`と`パスワード`を送信するURLを指定します。 ```Python hl_lines="6" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` /// tip | "豆知識" @@ -169,7 +169,7 @@ oauth2_scheme(some, parameters) これで`oauth2_scheme`を`Depends`で依存関係に渡すことができます。 ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` この依存関係は、*path operation function*のパラメーター`token`に代入される`str`を提供します。 diff --git a/docs/ja/docs/tutorial/security/get-current-user.md b/docs/ja/docs/tutorial/security/get-current-user.md index 250f66b81..0edbd983f 100644 --- a/docs/ja/docs/tutorial/security/get-current-user.md +++ b/docs/ja/docs/tutorial/security/get-current-user.md @@ -3,7 +3,7 @@ 一つ前の章では、(依存性注入システムに基づいた)セキュリティシステムは、 *path operation関数* に `str` として `token` を与えていました: ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` しかし、それはまだそんなに有用ではありません。 @@ -17,7 +17,7 @@ ボディを宣言するのにPydanticを使用するのと同じやり方で、Pydanticを別のどんなところでも使うことができます: ```Python hl_lines="5 12-16" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` ## 依存関係 `get_current_user` を作成 @@ -31,7 +31,7 @@ 以前直接 *path operation* の中でしていたのと同じように、新しい依存関係である `get_current_user` は `str` として `token` を受け取るようになります: ```Python hl_lines="25" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` ## ユーザーの取得 @@ -39,7 +39,7 @@ `get_current_user` は作成した(偽物の)ユーティリティ関数を使って、 `str` としてトークンを受け取り、先ほどのPydanticの `User` モデルを返却します: ```Python hl_lines="19-22 26-27" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` ## 現在のユーザーの注入 @@ -47,7 +47,7 @@ ですので、 `get_current_user` に対して同様に *path operation* の中で `Depends` を利用できます。 ```Python hl_lines="31" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` Pydanticモデルの `User` として、 `current_user` の型を宣言することに注意してください。 @@ -104,7 +104,7 @@ Pydanticモデルの `User` として、 `current_user` の型を宣言するこ さらに、こうした何千もの *path operations* は、たった3行で表現できるのです: ```Python hl_lines="30-32" -{!../../../docs_src/security/tutorial002.py!} +{!../../docs_src/security/tutorial002.py!} ``` ## まとめ diff --git a/docs/ja/docs/tutorial/security/oauth2-jwt.md b/docs/ja/docs/tutorial/security/oauth2-jwt.md index 4f6aebd4c..b2f511610 100644 --- a/docs/ja/docs/tutorial/security/oauth2-jwt.md +++ b/docs/ja/docs/tutorial/security/oauth2-jwt.md @@ -119,7 +119,7 @@ PassLibのcontextには、検証だけが許された非推奨の古いハッシ さらに、ユーザーを認証して返す関数も作成します。 ```Python hl_lines="7 48 55-56 59-60 69-75" -{!../../../docs_src/security/tutorial004.py!} +{!../../docs_src/security/tutorial004.py!} ``` /// note | "備考" @@ -157,7 +157,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し 新しいアクセストークンを生成するユーティリティ関数を作成します。 ```Python hl_lines="6 12-14 28-30 78-86" -{!../../../docs_src/security/tutorial004.py!} +{!../../docs_src/security/tutorial004.py!} ``` ## 依存関係の更新 @@ -169,7 +169,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し トークンが無効な場合は、すぐにHTTPエラーを返します。 ```Python hl_lines="89-106" -{!../../../docs_src/security/tutorial004.py!} +{!../../docs_src/security/tutorial004.py!} ``` ## `/token` パスオペレーションの更新 @@ -179,7 +179,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し JWTアクセストークンを作成し、それを返します。 ```Python hl_lines="115-130" -{!../../../docs_src/security/tutorial004.py!} +{!../../docs_src/security/tutorial004.py!} ``` ### JWTの"subject" `sub` についての技術的な詳細 diff --git a/docs/ja/docs/tutorial/static-files.md b/docs/ja/docs/tutorial/static-files.md index c9d95bc34..e6002a1fb 100644 --- a/docs/ja/docs/tutorial/static-files.md +++ b/docs/ja/docs/tutorial/static-files.md @@ -8,7 +8,7 @@ * `StaticFiles()` インスタンスを生成し、特定のパスに「マウント」。 ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` /// note | "技術詳細" diff --git a/docs/ja/docs/tutorial/testing.md b/docs/ja/docs/tutorial/testing.md index 3ed03ebea..6c5e712e8 100644 --- a/docs/ja/docs/tutorial/testing.md +++ b/docs/ja/docs/tutorial/testing.md @@ -19,7 +19,7 @@ チェックしたい Python の標準的な式と共に、シンプルに `assert` 文を記述します。 ```Python hl_lines="2 12 15-18" -{!../../../docs_src/app_testing/tutorial001.py!} +{!../../docs_src/app_testing/tutorial001.py!} ``` /// tip | "豆知識" @@ -57,7 +57,7 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ **FastAPI** アプリに `main.py` ファイルがあるとします: ```Python -{!../../../docs_src/app_testing/main.py!} +{!../../docs_src/app_testing/main.py!} ``` ### テストファイル @@ -65,7 +65,7 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ 次に、テストを含む `test_main.py` ファイルを作成し、`main` モジュール (`main.py`) から `app` をインポートします: ```Python -{!../../../docs_src/app_testing/test_main.py!} +{!../../docs_src/app_testing/test_main.py!} ``` ## テスト: 例の拡張 @@ -86,7 +86,7 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ //// tab | Python 3.10+ ```Python -{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_py310/main.py!} ``` //// @@ -94,7 +94,7 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ //// tab | Python 3.6+ ```Python -{!> ../../../docs_src/app_testing/app_b/main.py!} +{!> ../../docs_src/app_testing/app_b/main.py!} ``` //// @@ -104,7 +104,7 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ 次に、先程のものに拡張版のテストを加えた、`test_main_b.py` を作成します。 ```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} +{!> ../../docs_src/app_testing/app_b/test_main.py!} ``` リクエストに情報を渡せるクライアントが必要で、その方法がわからない場合はいつでも、`httpx` での実現方法を検索 (Google) できます。 diff --git a/docs/ko/docs/advanced/events.md b/docs/ko/docs/advanced/events.md index e155f41f1..94867c198 100644 --- a/docs/ko/docs/advanced/events.md +++ b/docs/ko/docs/advanced/events.md @@ -15,7 +15,7 @@ 응용 프로그램을 시작하기 전에 실행하려는 함수를 "startup" 이벤트로 선언합니다: ```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} +{!../../docs_src/events/tutorial001.py!} ``` 이 경우 `startup` 이벤트 핸들러 함수는 단순히 몇 가지 값으로 구성된 `dict` 형식의 "데이터베이스"를 초기화합니다. @@ -29,7 +29,7 @@ 응용 프로그램이 종료될 때 실행하려는 함수를 추가하려면 `"shutdown"` 이벤트로 선언합니다: ```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} +{!../../docs_src/events/tutorial002.py!} ``` 이 예제에서 `shutdown` 이벤트 핸들러 함수는 `"Application shutdown"`이라는 텍스트가 적힌 `log.txt` 파일을 추가할 것입니다. diff --git a/docs/ko/docs/python-types.md b/docs/ko/docs/python-types.md index 5c458e48d..6d7346189 100644 --- a/docs/ko/docs/python-types.md +++ b/docs/ko/docs/python-types.md @@ -23,7 +23,7 @@ 간단한 예제부터 시작해봅시다: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` 이 프로그램을 실행한 결과값: @@ -39,7 +39,7 @@ John Doe * 두 단어를 중간에 공백을 두고 연결합니다. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### 코드 수정 @@ -83,7 +83,7 @@ John Doe 이게 "타입 힌트"입니다: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` 타입힌트는 다음과 같이 기본 값을 선언하는 것과는 다릅니다: @@ -113,7 +113,7 @@ John Doe 아래 함수를 보면, 이미 타입 힌트가 적용되어 있는 걸 볼 수 있습니다: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` 편집기가 변수의 타입을 알고 있기 때문에, 자동완성 뿐 아니라 에러도 확인할 수 있습니다: @@ -123,7 +123,7 @@ John Doe 이제 고쳐야하는 걸 알기 때문에, `age`를 `str(age)`과 같이 문자열로 바꾸게 됩니다: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## 타입 선언 @@ -144,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### 타입 매개변수를 활용한 Generic(제네릭) 타입 @@ -162,7 +162,7 @@ John Doe `typing`에서 `List`(대문자 `L`)를 import 합니다. ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` 콜론(`:`) 문법을 이용하여 변수를 선언합니다. @@ -172,7 +172,7 @@ John Doe 이때 배열은 내부 타입을 포함하는 타입이기 때문에 대괄호 안에 넣어줍니다. ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` /// tip | "팁" @@ -200,7 +200,7 @@ John Doe `tuple`과 `set`도 동일하게 선언할 수 있습니다. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` 이 뜻은 아래와 같습니다: @@ -217,7 +217,7 @@ John Doe 두 번째 매개변수는 `dict`의 값(value)입니다. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` 이 뜻은 아래와 같습니다: @@ -231,7 +231,7 @@ John Doe `str`과 같이 타입을 선언할 때 `Optional`을 쓸 수도 있는데, "선택적(Optional)"이기때문에 `None`도 될 수 있습니다: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` `Optional[str]`을 `str` 대신 쓰게 되면, 특정 값이 실제로는 `None`이 될 수도 있는데 항상 `str`이라고 가정하는 상황에서 에디터가 에러를 찾게 도와줄 수 있습니다. @@ -256,13 +256,13 @@ John Doe 이름(name)을 가진 `Person` 클래스가 있다고 해봅시다. ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` 그렇게 하면 변수를 `Person`이라고 선언할 수 있게 됩니다. ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` 그리고 역시나 모든 에디터 도움을 받게 되겠죠. @@ -284,7 +284,7 @@ John Doe Pydantic 공식 문서 예시: ```Python -{!../../../docs_src/python_types/tutorial011.py!} +{!../../docs_src/python_types/tutorial011.py!} ``` /// info | "정보" diff --git a/docs/ko/docs/tutorial/background-tasks.md b/docs/ko/docs/tutorial/background-tasks.md index 880a1c198..376c52524 100644 --- a/docs/ko/docs/tutorial/background-tasks.md +++ b/docs/ko/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을 먼저 아래와 같이 `BackgroundTasks`를 임포트하고, `BackgroundTasks`를 _경로 작동 함수_ 에서 매개변수로 가져오고 정의합니다. ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** 는 `BackgroundTasks` 개체를 생성하고, 매개 변수로 전달합니다. @@ -34,7 +34,7 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을 그리고 이 작업은 `async`와 `await`를 사용하지 않으므로 일반 `def` 함수로 선언합니다. ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## 백그라운드 작업 추가 @@ -42,7 +42,7 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을 _경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _백그라운드 작업_ 개체에 전달합니다. ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` 함수는 다음과 같은 인자를 받습니다 : @@ -60,7 +60,7 @@ _경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _ //// tab | Python 3.6 and above ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002.py!} +{!> ../../docs_src/background_tasks/tutorial002.py!} ``` //// @@ -68,7 +68,7 @@ _경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _ //// tab | Python 3.10 and above ```Python hl_lines="11 13 20 23" -{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +{!> ../../docs_src/background_tasks/tutorial002_py310.py!} ``` //// diff --git a/docs/ko/docs/tutorial/body-fields.md b/docs/ko/docs/tutorial/body-fields.md index b74722e26..a13159c27 100644 --- a/docs/ko/docs/tutorial/body-fields.md +++ b/docs/ko/docs/tutorial/body-fields.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="2" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ /// ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// @@ -71,7 +71,7 @@ //// tab | Python 3.10+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -79,7 +79,7 @@ //// tab | Python 3.9+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -87,7 +87,7 @@ //// tab | Python 3.8+ ```Python hl_lines="12-15" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -101,7 +101,7 @@ /// ```Python hl_lines="9-12" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -115,7 +115,7 @@ /// ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// diff --git a/docs/ko/docs/tutorial/body-multiple-params.md b/docs/ko/docs/tutorial/body-multiple-params.md index 023575e1b..0a0f34585 100644 --- a/docs/ko/docs/tutorial/body-multiple-params.md +++ b/docs/ko/docs/tutorial/body-multiple-params.md @@ -11,7 +11,7 @@ 또한, 기본 값을 `None`으로 설정해 본문 매개변수를 선택사항으로 선언할 수 있습니다. ```Python hl_lines="19-21" -{!../../../docs_src/body_multiple_params/tutorial001.py!} +{!../../docs_src/body_multiple_params/tutorial001.py!} ``` /// note | "참고" @@ -36,7 +36,7 @@ 하지만, 다중 본문 매개변수 역시 선언할 수 있습니다. 예. `item`과 `user`: ```Python hl_lines="22" -{!../../../docs_src/body_multiple_params/tutorial002.py!} +{!../../docs_src/body_multiple_params/tutorial002.py!} ``` 이 경우에, **FastAPI**는 이 함수 안에 한 개 이상의 본문 매개변수(Pydantic 모델인 두 매개변수)가 있다고 알 것입니다. @@ -80,7 +80,7 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 ```Python hl_lines="23" -{!../../../docs_src/body_multiple_params/tutorial003.py!} +{!../../docs_src/body_multiple_params/tutorial003.py!} ``` 이 경우에는 **FastAPI**는 본문을 이와 같이 예측할 것입니다: @@ -111,7 +111,7 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 기본적으로 단일 값은 쿼리 매개변수로 해석되므로, 명시적으로 `Query`를 추가할 필요가 없고, 아래처럼 할 수 있습니다: ```Python hl_lines="27" -{!../../../docs_src/body_multiple_params/tutorial004.py!} +{!../../docs_src/body_multiple_params/tutorial004.py!} ``` 이렇게: @@ -135,7 +135,7 @@ Pydantic 모델 `Item`의 `item`을 본문 매개변수로 오직 한개만 갖 하지만, 만약 모델 내용에 `item `키를 가진 JSON으로 예측하길 원한다면, 추가적인 본문 매개변수를 선언한 것처럼 `Body`의 특별한 매개변수인 `embed`를 사용할 수 있습니다: ```Python hl_lines="17" -{!../../../docs_src/body_multiple_params/tutorial005.py!} +{!../../docs_src/body_multiple_params/tutorial005.py!} ``` 아래 처럼: diff --git a/docs/ko/docs/tutorial/body-nested-models.md b/docs/ko/docs/tutorial/body-nested-models.md index 4d785f64b..12fb4e0cc 100644 --- a/docs/ko/docs/tutorial/body-nested-models.md +++ b/docs/ko/docs/tutorial/body-nested-models.md @@ -6,7 +6,7 @@ 어트리뷰트를 서브타입으로 정의할 수 있습니다. 예를 들어 파이썬 `list`는: ```Python hl_lines="14" -{!../../../docs_src/body_nested_models/tutorial001.py!} +{!../../docs_src/body_nested_models/tutorial001.py!} ``` 이는 `tags`를 항목 리스트로 만듭니다. 각 항목의 타입을 선언하지 않더라도요. @@ -20,7 +20,7 @@ 먼저, 파이썬 표준 `typing` 모듈에서 `List`를 임포트합니다: ```Python hl_lines="1" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!../../docs_src/body_nested_models/tutorial002.py!} ``` ### 타입 매개변수로 `List` 선언 @@ -43,7 +43,7 @@ my_list: List[str] 마찬가지로 예제에서 `tags`를 구체적으로 "문자열의 리스트"로 만들 수 있습니다: ```Python hl_lines="14" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!../../docs_src/body_nested_models/tutorial002.py!} ``` ## 집합 타입 @@ -55,7 +55,7 @@ my_list: List[str] 그렇다면 `Set`을 임포트 하고 `tags`를 `str`의 `set`으로 선언할 수 있습니다: ```Python hl_lines="1 14" -{!../../../docs_src/body_nested_models/tutorial003.py!} +{!../../docs_src/body_nested_models/tutorial003.py!} ``` 덕분에 중복 데이터가 있는 요청을 수신하더라도 고유한 항목들의 집합으로 변환됩니다. @@ -79,7 +79,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 예를 들어, `Image` 모델을 선언할 수 있습니다: ```Python hl_lines="9-11" -{!../../../docs_src/body_nested_models/tutorial004.py!} +{!../../docs_src/body_nested_models/tutorial004.py!} ``` ### 서브모듈을 타입으로 사용 @@ -87,7 +87,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 그리고 어트리뷰트의 타입으로 사용할 수 있습니다: ```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial004.py!} +{!../../docs_src/body_nested_models/tutorial004.py!} ``` 이는 **FastAPI**가 다음과 유사한 본문을 기대한다는 것을 의미합니다: @@ -122,7 +122,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 예를 들어 `Image` 모델 안에 `url` 필드를 `str` 대신 Pydantic의 `HttpUrl`로 선언할 수 있습니다: ```Python hl_lines="4 10" -{!../../../docs_src/body_nested_models/tutorial005.py!} +{!../../docs_src/body_nested_models/tutorial005.py!} ``` 이 문자열이 유효한 URL인지 검사하고 JSON 스키마/OpenAPI로 문서화 됩니다. @@ -132,7 +132,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. `list`, `set` 등의 서브타입으로 Pydantic 모델을 사용할 수도 있습니다: ```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial006.py!} +{!../../docs_src/body_nested_models/tutorial006.py!} ``` 아래와 같은 JSON 본문으로 예상(변환, 검증, 문서화 등을)합니다: @@ -172,7 +172,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 단독으로 깊게 중첩된 모델을 정의할 수 있습니다: ```Python hl_lines="9 14 20 23 27" -{!../../../docs_src/body_nested_models/tutorial007.py!} +{!../../docs_src/body_nested_models/tutorial007.py!} ``` /// info | "정보" @@ -192,7 +192,7 @@ images: List[Image] 이를 아래처럼: ```Python hl_lines="15" -{!../../../docs_src/body_nested_models/tutorial008.py!} +{!../../docs_src/body_nested_models/tutorial008.py!} ``` ## 어디서나 편집기 지원 @@ -224,7 +224,7 @@ Pydantic 모델 대신에 `dict`를 직접 사용하여 작업할 경우, 이러 이 경우, `float` 값을 가진 `int` 키가 있는 모든 `dict`를 받아들입니다: ```Python hl_lines="15" -{!../../../docs_src/body_nested_models/tutorial009.py!} +{!../../docs_src/body_nested_models/tutorial009.py!} ``` /// tip | "팁" diff --git a/docs/ko/docs/tutorial/body.md b/docs/ko/docs/tutorial/body.md index 337218eb4..8df8d556e 100644 --- a/docs/ko/docs/tutorial/body.md +++ b/docs/ko/docs/tutorial/body.md @@ -25,7 +25,7 @@ //// tab | Python 3.10+ ```Python hl_lines="2" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -33,7 +33,7 @@ //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -47,7 +47,7 @@ //// tab | Python 3.10+ ```Python hl_lines="5-9" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -55,7 +55,7 @@ //// tab | Python 3.8+ ```Python hl_lines="7-11" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -89,7 +89,7 @@ //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -97,7 +97,7 @@ //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -170,7 +170,7 @@ //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/body/tutorial002_py310.py!} +{!> ../../docs_src/body/tutorial002_py310.py!} ``` //// @@ -178,7 +178,7 @@ //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/body/tutorial002.py!} +{!> ../../docs_src/body/tutorial002.py!} ``` //// @@ -192,7 +192,7 @@ //// tab | Python 3.10+ ```Python hl_lines="15-16" -{!> ../../../docs_src/body/tutorial003_py310.py!} +{!> ../../docs_src/body/tutorial003_py310.py!} ``` //// @@ -200,7 +200,7 @@ //// tab | Python 3.8+ ```Python hl_lines="17-18" -{!> ../../../docs_src/body/tutorial003.py!} +{!> ../../docs_src/body/tutorial003.py!} ``` //// @@ -214,7 +214,7 @@ //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial004_py310.py!} +{!> ../../docs_src/body/tutorial004_py310.py!} ``` //// @@ -222,7 +222,7 @@ //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial004.py!} +{!> ../../docs_src/body/tutorial004.py!} ``` //// diff --git a/docs/ko/docs/tutorial/cookie-params.md b/docs/ko/docs/tutorial/cookie-params.md index 5f129b63f..1e21e069d 100644 --- a/docs/ko/docs/tutorial/cookie-params.md +++ b/docs/ko/docs/tutorial/cookie-params.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ /// ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -67,7 +67,7 @@ //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -75,7 +75,7 @@ //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -97,7 +97,7 @@ /// ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -111,7 +111,7 @@ /// ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// diff --git a/docs/ko/docs/tutorial/cors.md b/docs/ko/docs/tutorial/cors.md index 312fdee1b..65357ae3f 100644 --- a/docs/ko/docs/tutorial/cors.md +++ b/docs/ko/docs/tutorial/cors.md @@ -47,7 +47,7 @@ * 특정한 HTTP 헤더 또는 와일드카드 `"*"` 를 사용한 모든 HTTP 헤더. ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` `CORSMiddleware` 에서 사용하는 기본 매개변수는 제한적이므로, 브라우저가 교차-도메인 상황에서 특정한 출처, 메소드, 헤더 등을 사용할 수 있도록 하려면 이들을 명시적으로 허용해야 합니다. diff --git a/docs/ko/docs/tutorial/debugging.md b/docs/ko/docs/tutorial/debugging.md index cb45e5169..27e8f9abf 100644 --- a/docs/ko/docs/tutorial/debugging.md +++ b/docs/ko/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ FastAPI 애플리케이션에서 `uvicorn`을 직접 임포트하여 실행합니다 ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### `__name__ == "__main__"` 에 대하여 diff --git a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md index 259fe4b6d..7430efbb4 100644 --- a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md @@ -9,7 +9,7 @@ //// tab | 파이썬 3.6 이상 ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | 파이썬 3.10 이상 ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -84,7 +84,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 //// tab | 파이썬 3.6 이상 ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -92,7 +92,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 //// tab | 파이썬 3.10 이상 ```Python hl_lines="9-13" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -102,7 +102,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 //// tab | 파이썬 3.6 이상 ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -110,7 +110,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 //// tab | 파이썬 3.10 이상 ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -120,7 +120,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 //// tab | 파이썬 3.6 이상 ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -128,7 +128,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 //// tab | 파이썬 3.10 이상 ```Python hl_lines="6" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -150,7 +150,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 //// tab | 파이썬 3.6 이상 ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -158,7 +158,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 //// tab | 파이썬 3.10 이상 ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -203,7 +203,7 @@ commons = Depends(CommonQueryParams) //// tab | 파이썬 3.6 이상 ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003.py!} +{!> ../../docs_src/dependencies/tutorial003.py!} ``` //// @@ -211,7 +211,7 @@ commons = Depends(CommonQueryParams) //// tab | 파이썬 3.10 이상 ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_py310.py!} ``` //// @@ -251,7 +251,7 @@ commons: CommonQueryParams = Depends() //// tab | 파이썬 3.6 이상 ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004.py!} +{!> ../../docs_src/dependencies/tutorial004.py!} ``` //// @@ -259,7 +259,7 @@ commons: CommonQueryParams = Depends() //// tab | 파이썬 3.10 이상 ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_py310.py!} ``` //// diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index bc8af488d..e71ba8546 100644 --- a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -75,7 +75,7 @@ //// tab | Python 3.9+ ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ //// tab | Python 3.8+ ```Python hl_lines="7 12" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -97,7 +97,7 @@ /// ```Python hl_lines="6 11" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -109,7 +109,7 @@ //// tab | Python 3.9+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -117,7 +117,7 @@ //// tab | Python 3.8+ ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -131,7 +131,7 @@ /// ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -145,7 +145,7 @@ //// tab | Python 3.9+ ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -153,7 +153,7 @@ //// tab | Python 3.8+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -167,7 +167,7 @@ /// ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// diff --git a/docs/ko/docs/tutorial/dependencies/global-dependencies.md b/docs/ko/docs/tutorial/dependencies/global-dependencies.md index 2ce2cf4f2..dd6586c3e 100644 --- a/docs/ko/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/global-dependencies.md @@ -9,7 +9,7 @@ //// tab | Python 3.9+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.8+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial012_an.py!} +{!> ../../docs_src/dependencies/tutorial012_an.py!} ``` //// @@ -31,7 +31,7 @@ /// ```Python hl_lines="15" -{!> ../../../docs_src/dependencies/tutorial012.py!} +{!> ../../docs_src/dependencies/tutorial012.py!} ``` //// diff --git a/docs/ko/docs/tutorial/dependencies/index.md b/docs/ko/docs/tutorial/dependencies/index.md index 361989e2b..f7b2f1788 100644 --- a/docs/ko/docs/tutorial/dependencies/index.md +++ b/docs/ko/docs/tutorial/dependencies/index.md @@ -34,7 +34,7 @@ //// tab | Python 3.10+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -42,7 +42,7 @@ //// tab | Python 3.9+ ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -50,7 +50,7 @@ //// tab | Python 3.8+ ```Python hl_lines="9-12" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -64,7 +64,7 @@ /// ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -78,7 +78,7 @@ /// ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -116,7 +116,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -124,7 +124,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -132,7 +132,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -146,7 +146,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 /// ```Python hl_lines="1" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -160,7 +160,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 /// ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -172,7 +172,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 //// tab | Python 3.10+ ```Python hl_lines="13 18" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -180,7 +180,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 //// tab | Python 3.9+ ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -188,7 +188,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 //// tab | Python 3.8+ ```Python hl_lines="16 21" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -202,7 +202,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 /// ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -216,7 +216,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 /// ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -279,7 +279,7 @@ commons: Annotated[dict, Depends(common_parameters)] //// tab | Python 3.10+ ```Python hl_lines="12 16 21" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} ``` //// @@ -287,7 +287,7 @@ commons: Annotated[dict, Depends(common_parameters)] //// tab | Python 3.9+ ```Python hl_lines="14 18 23" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} ``` //// @@ -295,7 +295,7 @@ commons: Annotated[dict, Depends(common_parameters)] //// tab | Python 3.8+ ```Python hl_lines="15 19 24" -{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an.py!} ``` //// diff --git a/docs/ko/docs/tutorial/encoder.md b/docs/ko/docs/tutorial/encoder.md index b8e87449c..732566d6d 100644 --- a/docs/ko/docs/tutorial/encoder.md +++ b/docs/ko/docs/tutorial/encoder.md @@ -21,7 +21,7 @@ JSON 호환 가능 데이터만 수신하는 `fake_db` 데이터베이스가 존 Pydantic 모델과 같은 객체를 받고 JSON 호환 가능한 버전으로 반환합니다: ```Python hl_lines="5 22" -{!../../../docs_src/encoder/tutorial001.py!} +{!../../docs_src/encoder/tutorial001.py!} ``` 이 예시는 Pydantic 모델을 `dict`로, `datetime` 형식을 `str`로 변환합니다. diff --git a/docs/ko/docs/tutorial/extra-data-types.md b/docs/ko/docs/tutorial/extra-data-types.md index df3c7a06e..8baaa64fc 100644 --- a/docs/ko/docs/tutorial/extra-data-types.md +++ b/docs/ko/docs/tutorial/extra-data-types.md @@ -58,7 +58,7 @@ //// tab | Python 3.10+ ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} ``` //// @@ -66,7 +66,7 @@ //// tab | Python 3.9+ ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` //// @@ -74,7 +74,7 @@ //// tab | Python 3.8+ ```Python hl_lines="1 3 13-17" -{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} ``` //// @@ -88,7 +88,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1 2 11-15" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -102,7 +102,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1 2 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// @@ -112,7 +112,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.10+ ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} ``` //// @@ -120,7 +120,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.9+ ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` //// @@ -128,7 +128,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.8+ ```Python hl_lines="19-20" -{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} ``` //// @@ -142,7 +142,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="17-18" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -156,7 +156,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// diff --git a/docs/ko/docs/tutorial/first-steps.md b/docs/ko/docs/tutorial/first-steps.md index 52e53fd89..c2c48fb3e 100644 --- a/docs/ko/docs/tutorial/first-steps.md +++ b/docs/ko/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ 가장 단순한 FastAPI 파일은 다음과 같이 보일 것입니다: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 위 코드를 `main.py`에 복사합니다. @@ -134,7 +134,7 @@ API와 통신하는 클라이언트(프론트엔드, 모바일, IoT 애플리케 ### 1 단계: `FastAPI` 임포트 ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI`는 당신의 API를 위한 모든 기능을 제공하는 파이썬 클래스입니다. @@ -150,7 +150,7 @@ API와 통신하는 클라이언트(프론트엔드, 모바일, IoT 애플리케 ### 2 단계: `FastAPI` "인스턴스" 생성 ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 여기에서 `app` 변수는 `FastAPI` 클래스의 "인스턴스"가 됩니다. @@ -172,7 +172,7 @@ $ uvicorn main:app --reload 아래처럼 앱을 만든다면: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` 이를 `main.py` 파일에 넣고, `uvicorn`을 아래처럼 호출해야 합니다: @@ -251,7 +251,7 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 #### *경로 작동 데코레이터* 정의 ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `@app.get("/")`은 **FastAPI**에게 바로 아래에 있는 함수가 다음으로 이동하는 요청을 처리한다는 것을 알려줍니다. @@ -307,7 +307,7 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 * **함수**: 는 "데코레이터" 아래에 있는 함수입니다 (`@app.get("/")` 아래). ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` 이것은 파이썬 함수입니다. @@ -321,7 +321,7 @@ URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **Fa `async def`을 이용하는 대신 일반 함수로 정의할 수 있습니다: ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` /// note | "참고" @@ -333,7 +333,7 @@ URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **Fa ### 5 단계: 콘텐츠 반환 ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `dict`, `list`, 단일값을 가진 `str`, `int` 등을 반환할 수 있습니다. diff --git a/docs/ko/docs/tutorial/header-params.md b/docs/ko/docs/tutorial/header-params.md index d403b9175..26e198869 100644 --- a/docs/ko/docs/tutorial/header-params.md +++ b/docs/ko/docs/tutorial/header-params.md @@ -7,7 +7,7 @@ 먼저 `Header`를 임포트합니다: ```Python hl_lines="3" -{!../../../docs_src/header_params/tutorial001.py!} +{!../../docs_src/header_params/tutorial001.py!} ``` ## `Header` 매개변수 선언 @@ -17,7 +17,7 @@ 첫 번째 값은 기본값이며, 추가 검증이나 어노테이션 매개변수 모두 전달할 수 있습니다: ```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial001.py!} +{!../../docs_src/header_params/tutorial001.py!} ``` /// note | "기술 세부사항" @@ -51,7 +51,7 @@ 만약 언더스코어를 하이픈으로 자동 변환을 비활성화해야 할 어떤 이유가 있다면, `Header`의 `convert_underscores` 매개변수를 `False`로 설정하십시오: ```Python hl_lines="10" -{!../../../docs_src/header_params/tutorial002.py!} +{!../../docs_src/header_params/tutorial002.py!} ``` /// warning | "경고" @@ -71,7 +71,7 @@ 예를 들어, 두 번 이상 나타날 수 있는 `X-Token`헤더를 선언하려면, 다음과 같이 작성합니다: ```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial003.py!} +{!../../docs_src/header_params/tutorial003.py!} ``` 다음과 같은 두 개의 HTTP 헤더를 전송하여 해당 *경로* 와 통신할 경우: diff --git a/docs/ko/docs/tutorial/middleware.md b/docs/ko/docs/tutorial/middleware.md index 84f67bd26..f36f11a27 100644 --- a/docs/ko/docs/tutorial/middleware.md +++ b/docs/ko/docs/tutorial/middleware.md @@ -32,7 +32,7 @@ * `response`를 반환하기 전에 추가로 `response`를 수정할 수 있습니다. ```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` /// tip | "팁" @@ -60,7 +60,7 @@ 예를 들어, 요청을 수행하고 응답을 생성하는데 까지 걸린 시간 값을 가지고 있는 `X-Process-Time` 같은 사용자 정의 헤더를 추가할 수 있습니다. ```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` ## 다른 미들웨어 diff --git a/docs/ko/docs/tutorial/path-operation-configuration.md b/docs/ko/docs/tutorial/path-operation-configuration.md index b6608a14d..6ebe613a8 100644 --- a/docs/ko/docs/tutorial/path-operation-configuration.md +++ b/docs/ko/docs/tutorial/path-operation-configuration.md @@ -17,7 +17,7 @@ 하지만 각 코드의 의미를 모른다면, `status`에 있는 단축 상수들을 사용할수 있습니다: ```Python hl_lines="3 17" -{!../../../docs_src/path_operation_configuration/tutorial001.py!} +{!../../docs_src/path_operation_configuration/tutorial001.py!} ``` 각 상태 코드들은 응답에 사용되며, OpenAPI 스키마에 추가됩니다. @@ -35,7 +35,7 @@ (보통 단일 `str`인) `str`로 구성된 `list`와 함께 매개변수 `tags`를 전달하여, `경로 작동`에 태그를 추가할 수 있습니다: ```Python hl_lines="17 22 27" -{!../../../docs_src/path_operation_configuration/tutorial002.py!} +{!../../docs_src/path_operation_configuration/tutorial002.py!} ``` 전달된 태그들은 OpenAPI의 스키마에 추가되며, 자동 문서 인터페이스에서 사용됩니다: @@ -47,7 +47,7 @@ `summary`와 `description`을 추가할 수 있습니다: ```Python hl_lines="20-21" -{!../../../docs_src/path_operation_configuration/tutorial003.py!} +{!../../docs_src/path_operation_configuration/tutorial003.py!} ``` ## 독스트링으로 만든 기술 @@ -57,7 +57,7 @@ 마크다운 문법으로 독스트링을 작성할 수 있습니다, 작성된 마크다운 형식의 독스트링은 (마크다운의 들여쓰기를 고려하여) 올바르게 화면에 출력됩니다. ```Python hl_lines="19-27" -{!../../../docs_src/path_operation_configuration/tutorial004.py!} +{!../../docs_src/path_operation_configuration/tutorial004.py!} ``` 이는 대화형 문서에서 사용됩니다: @@ -69,7 +69,7 @@ `response_description` 매개변수로 응답에 관한 설명을 명시할 수 있습니다: ```Python hl_lines="21" -{!../../../docs_src/path_operation_configuration/tutorial005.py!} +{!../../docs_src/path_operation_configuration/tutorial005.py!} ``` /// info | "정보" @@ -93,7 +93,7 @@ OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 단일 *경로 작동*을 없애지 않고 지원중단을 해야한다면, `deprecated` 매개변수를 전달하면 됩니다. ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` 대화형 문서에 지원중단이라고 표시됩니다. diff --git a/docs/ko/docs/tutorial/path-params-numeric-validations.md b/docs/ko/docs/tutorial/path-params-numeric-validations.md index 6d3215c24..caab2d453 100644 --- a/docs/ko/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ko/docs/tutorial/path-params-numeric-validations.md @@ -7,7 +7,7 @@ 먼저 `fastapi`에서 `Path`를 임포트합니다: ```Python hl_lines="3" -{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` ## 메타데이터 선언 @@ -17,7 +17,7 @@ 예를 들어, `title` 메타데이터 값을 경로 매개변수 `item_id`에 선언하려면 다음과 같이 입력할 수 있습니다: ```Python hl_lines="10" -{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` /// note | "참고" @@ -47,7 +47,7 @@ 따라서 함수를 다음과 같이 선언 할 수 있습니다: ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` ## 필요한 경우 매개변수 정렬하기, 트릭 @@ -59,7 +59,7 @@ 파이썬은 `*`으로 아무런 행동도 하지 않지만, 따르는 매개변수들은 kwargs로도 알려진 키워드 인자(키-값 쌍)여야 함을 인지합니다. 기본값을 가지고 있지 않더라도 그렇습니다. ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ## 숫자 검증: 크거나 같음 @@ -69,7 +69,7 @@ 여기서 `ge=1`인 경우, `item_id`는 `1`보다 "크거나(`g`reater) 같은(`e`qual)" 정수형 숫자여야 합니다. ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` ## 숫자 검증: 크거나 같음 및 작거나 같음 @@ -80,7 +80,7 @@ * `le`: 작거나 같은(`l`ess than or `e`qual) ```Python hl_lines="9" -{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` ## 숫자 검증: 부동소수, 크거나 및 작거나 @@ -94,7 +94,7 @@ lt 역시 마찬가지입니다. ```Python hl_lines="11" -{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` ## 요약 diff --git a/docs/ko/docs/tutorial/path-params.md b/docs/ko/docs/tutorial/path-params.md index 67a2d899d..09a27a7b3 100644 --- a/docs/ko/docs/tutorial/path-params.md +++ b/docs/ko/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ 파이썬의 포맷 문자열 리터럴에서 사용되는 문법을 이용하여 경로 "매개변수" 또는 "변수"를 선언할 수 있습니다: ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` 경로 매개변수 `item_id`의 값은 함수의 `item_id` 인자로 전달됩니다. @@ -19,7 +19,7 @@ 파이썬 표준 타입 어노테이션을 사용하여 함수에 있는 경로 매개변수의 타입을 선언할 수 있습니다: ```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} +{!../../docs_src/path_params/tutorial002.py!} ``` 위의 예시에서, `item_id`는 `int`로 선언되었습니다. @@ -122,7 +122,7 @@ *경로 작동*은 순차적으로 실행되기 때문에 `/users/{user_id}` 이전에 `/users/me`를 먼저 선언해야 합니다: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} +{!../../docs_src/path_params/tutorial003.py!} ``` 그렇지 않으면 `/users/{user_id}`는 `/users/me` 요청 또한 매개변수 `user_id`의 값이 `"me"`인 것으로 "생각하게" 됩니다. @@ -140,7 +140,7 @@ 가능한 값들에 해당하는 고정된 값의 클래스 어트리뷰트들을 만듭니다: ```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// info | "정보" @@ -160,7 +160,7 @@ 생성한 열거형 클래스(`ModelName`)를 사용하는 타입 어노테이션으로 *경로 매개변수*를 만듭니다: ```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` ### 문서 확인 @@ -178,7 +178,7 @@ 열거형 `ModelName`의 *열거형 멤버*를 비교할 수 있습니다: ```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` #### *열거형 값* 가져오기 @@ -186,7 +186,7 @@ `model_name.value` 또는 일반적으로 `your_enum_member.value`를 이용하여 실제 값(위 예시의 경우 `str`)을 가져올 수 있습니다: ```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// tip | "팁" @@ -202,7 +202,7 @@ 클라이언트에 반환하기 전에 해당 값(이 경우 문자열)으로 변환됩니다: ```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` 클라이언트는 아래의 JSON 응답을 얻습니다: @@ -243,7 +243,7 @@ Starlette의 옵션을 직접 이용하여 다음과 같은 URL을 사용함으 따라서 다음과 같이 사용할 수 있습니다: ```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} +{!../../docs_src/path_params/tutorial004.py!} ``` /// tip | "팁" diff --git a/docs/ko/docs/tutorial/query-params-str-validations.md b/docs/ko/docs/tutorial/query-params-str-validations.md index 11193950b..e44f6dd16 100644 --- a/docs/ko/docs/tutorial/query-params-str-validations.md +++ b/docs/ko/docs/tutorial/query-params-str-validations.md @@ -5,7 +5,7 @@ 이 응용 프로그램을 예로 들어보겠습니다: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial001.py!} +{!../../docs_src/query_params_str_validations/tutorial001.py!} ``` 쿼리 매개변수 `q`는 `Optional[str]` 자료형입니다. 즉, `str` 자료형이지만 `None` 역시 될 수 있음을 뜻하고, 실제로 기본값은 `None`이기 때문에 FastAPI는 이 매개변수가 필수가 아니라는 것을 압니다. @@ -27,7 +27,7 @@ FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압 이를 위해 먼저 `fastapi`에서 `Query`를 임포트합니다: ```Python hl_lines="3" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` ## 기본값으로 `Query` 사용 @@ -35,7 +35,7 @@ FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압 이제 `Query`를 매개변수의 기본값으로 사용하여 `max_length` 매개변수를 50으로 설정합니다: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} +{!../../docs_src/query_params_str_validations/tutorial002.py!} ``` 기본값 `None`을 `Query(None)`으로 바꿔야 하므로, `Query`의 첫 번째 매개변수는 기본값을 정의하는 것과 같은 목적으로 사용됩니다. @@ -87,7 +87,7 @@ q: str = Query(None, max_length=50) 매개변수 `min_length` 또한 추가할 수 있습니다: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial003.py!} +{!../../docs_src/query_params_str_validations/tutorial003.py!} ``` ## 정규식 추가 @@ -95,7 +95,7 @@ q: str = Query(None, max_length=50) 매개변수와 일치해야 하는 정규표현식을 정의할 수 있습니다: ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial004.py!} +{!../../docs_src/query_params_str_validations/tutorial004.py!} ``` 이 특정 정규표현식은 전달 받은 매개변수 값을 검사합니다: @@ -115,7 +115,7 @@ q: str = Query(None, max_length=50) `min_length`가 `3`이고, 기본값이 `"fixedquery"`인 쿼리 매개변수 `q`를 선언해봅시다: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} +{!../../docs_src/query_params_str_validations/tutorial005.py!} ``` /// note | "참고" @@ -147,7 +147,7 @@ q: Optional[str] = Query(None, min_length=3) 그래서 `Query`를 필수값으로 만들어야 할 때면, 첫 번째 인자로 `...`를 사용할 수 있습니다: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} +{!../../docs_src/query_params_str_validations/tutorial006.py!} ``` /// info | "정보" @@ -165,7 +165,7 @@ q: Optional[str] = Query(None, min_length=3) 예를 들어, URL에서 여러번 나오는 `q` 쿼리 매개변수를 선언하려면 다음과 같이 작성할 수 있습니다: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial011.py!} +{!../../docs_src/query_params_str_validations/tutorial011.py!} ``` 아래와 같은 URL을 사용합니다: @@ -202,7 +202,7 @@ http://localhost:8000/items/?q=foo&q=bar 그리고 제공된 값이 없으면 기본 `list` 값을 정의할 수도 있습니다: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial012.py!} +{!../../docs_src/query_params_str_validations/tutorial012.py!} ``` 아래로 이동한다면: @@ -227,7 +227,7 @@ http://localhost:8000/items/ `List[str]` 대신 `list`를 직접 사용할 수도 있습니다: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} +{!../../docs_src/query_params_str_validations/tutorial013.py!} ``` /// note | "참고" @@ -255,13 +255,13 @@ http://localhost:8000/items/ `title`을 추가할 수 있습니다: ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial007.py!} +{!../../docs_src/query_params_str_validations/tutorial007.py!} ``` 그리고 `description`도 추가할 수 있습니다: ```Python hl_lines="13" -{!../../../docs_src/query_params_str_validations/tutorial008.py!} +{!../../docs_src/query_params_str_validations/tutorial008.py!} ``` ## 별칭 매개변수 @@ -283,7 +283,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 이럴 경우 `alias`를 선언할 수 있으며, 해당 별칭은 매개변수 값을 찾는 데 사용됩니다: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial009.py!} +{!../../docs_src/query_params_str_validations/tutorial009.py!} ``` ## 매개변수 사용하지 않게 하기 @@ -295,7 +295,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 그렇다면 `deprecated=True` 매개변수를 `Query`로 전달합니다: ```Python hl_lines="18" -{!../../../docs_src/query_params_str_validations/tutorial010.py!} +{!../../docs_src/query_params_str_validations/tutorial010.py!} ``` 문서가 아래와 같이 보일겁니다: diff --git a/docs/ko/docs/tutorial/query-params.md b/docs/ko/docs/tutorial/query-params.md index e71444c18..b2a946c09 100644 --- a/docs/ko/docs/tutorial/query-params.md +++ b/docs/ko/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ 경로 매개변수의 일부가 아닌 다른 함수 매개변수를 선언하면 "쿼리" 매개변수로 자동 해석합니다. ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` 쿼리는 URL에서 `?` 후에 나오고 `&`으로 구분되는 키-값 쌍의 집합입니다. @@ -64,7 +64,7 @@ http://127.0.0.1:8000/items/?skip=20 같은 방법으로 기본값을 `None`으로 설정하여 선택적 매개변수를 선언할 수 있습니다: ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial002.py!} +{!../../docs_src/query_params/tutorial002.py!} ``` 이 경우 함수 매개변수 `q`는 선택적이며 기본값으로 `None` 값이 됩니다. @@ -88,7 +88,7 @@ FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다. `bool` 형으로 선언할 수도 있고, 아래처럼 변환됩니다: ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial003.py!} +{!../../docs_src/query_params/tutorial003.py!} ``` 이 경우, 아래로 이동하면: @@ -133,7 +133,7 @@ http://127.0.0.1:8000/items/foo?short=yes 매개변수들은 이름으로 감지됩니다: ```Python hl_lines="8 10" -{!../../../docs_src/query_params/tutorial004.py!} +{!../../docs_src/query_params/tutorial004.py!} ``` ## 필수 쿼리 매개변수 @@ -145,7 +145,7 @@ http://127.0.0.1:8000/items/foo?short=yes 그러나 쿼리 매개변수를 필수로 만들려면 단순히 기본값을 선언하지 않으면 됩니다: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` 여기 쿼리 매개변수 `needy`는 `str`형인 필수 쿼리 매개변수입니다. @@ -191,7 +191,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy 그리고 물론, 일부 매개변수는 필수로, 다른 일부는 기본값을, 또 다른 일부는 선택적으로 선언할 수 있습니다: ```Python hl_lines="10" -{!../../../docs_src/query_params/tutorial006.py!} +{!../../docs_src/query_params/tutorial006.py!} ``` 위 예시에서는 3가지 쿼리 매개변수가 있습니다: diff --git a/docs/ko/docs/tutorial/request-files.md b/docs/ko/docs/tutorial/request-files.md index b7781ef5e..40579dd51 100644 --- a/docs/ko/docs/tutorial/request-files.md +++ b/docs/ko/docs/tutorial/request-files.md @@ -17,7 +17,7 @@ `fastapi` 에서 `File` 과 `UploadFile` 을 임포트 합니다: ```Python hl_lines="1" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` ## `File` 매개변수 정의 @@ -25,7 +25,7 @@ `Body` 및 `Form` 과 동일한 방식으로 파일의 매개변수를 생성합니다: ```Python hl_lines="7" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` /// info | "정보" @@ -55,7 +55,7 @@ File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본 `File` 매개변수를 `UploadFile` 타입으로 정의합니다: ```Python hl_lines="12" -{!../../../docs_src/request_files/tutorial001.py!} +{!../../docs_src/request_files/tutorial001.py!} ``` `UploadFile` 을 사용하는 것은 `bytes` 과 비교해 다음과 같은 장점이 있습니다: @@ -143,7 +143,7 @@ HTML의 폼들(`
`)이 서버에 데이터를 전송하는 방식은 이 기능을 사용하기 위해 , `bytes` 의 `List` 또는 `UploadFile` 를 선언하기 바랍니다: ```Python hl_lines="10 15" -{!../../../docs_src/request_files/tutorial002.py!} +{!../../docs_src/request_files/tutorial002.py!} ``` 선언한대로, `bytes` 의 `list` 또는 `UploadFile` 들을 전송받을 것입니다. diff --git a/docs/ko/docs/tutorial/request-forms-and-files.md b/docs/ko/docs/tutorial/request-forms-and-files.md index 0867414ea..24501fe34 100644 --- a/docs/ko/docs/tutorial/request-forms-and-files.md +++ b/docs/ko/docs/tutorial/request-forms-and-files.md @@ -13,7 +13,7 @@ ## `File` 및 `Form` 업로드 ```Python hl_lines="1" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` ## `File` 및 `Form` 매개변수 정의 @@ -21,7 +21,7 @@ `Body` 및 `Query`와 동일한 방식으로 파일과 폼의 매개변수를 생성합니다: ```Python hl_lines="8" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` 파일과 폼 필드는 폼 데이터 형식으로 업로드되어 파일과 폼 필드로 전달됩니다. diff --git a/docs/ko/docs/tutorial/response-model.md b/docs/ko/docs/tutorial/response-model.md index fc74a60b3..74034e34d 100644 --- a/docs/ko/docs/tutorial/response-model.md +++ b/docs/ko/docs/tutorial/response-model.md @@ -9,7 +9,7 @@ * 기타. ```Python hl_lines="17" -{!../../../docs_src/response_model/tutorial001.py!} +{!../../docs_src/response_model/tutorial001.py!} ``` /// note | "참고" @@ -42,13 +42,13 @@ FastAPI는 이 `response_model`를 사용하여: 여기서 우리는 평문 비밀번호를 포함하는 `UserIn` 모델을 선언합니다: ```Python hl_lines="9 11" -{!../../../docs_src/response_model/tutorial002.py!} +{!../../docs_src/response_model/tutorial002.py!} ``` 그리고 이 모델을 사용하여 입력을 선언하고 같은 모델로 출력을 선언합니다: ```Python hl_lines="17-18" -{!../../../docs_src/response_model/tutorial002.py!} +{!../../docs_src/response_model/tutorial002.py!} ``` 이제 브라우저가 비밀번호로 사용자를 만들 때마다 API는 응답으로 동일한 비밀번호를 반환합니다. @@ -68,19 +68,19 @@ FastAPI는 이 `response_model`를 사용하여: 대신 평문 비밀번호로 입력 모델을 만들고 해당 비밀번호 없이 출력 모델을 만들 수 있습니다: ```Python hl_lines="9 11 16" -{!../../../docs_src/response_model/tutorial003.py!} +{!../../docs_src/response_model/tutorial003.py!} ``` 여기서 *경로 작동 함수*가 비밀번호를 포함하는 동일한 입력 사용자를 반환할지라도: ```Python hl_lines="24" -{!../../../docs_src/response_model/tutorial003.py!} +{!../../docs_src/response_model/tutorial003.py!} ``` ...`response_model`을 `UserOut` 모델로 선언했기 때문에 비밀번호를 포함하지 않습니다: ```Python hl_lines="22" -{!../../../docs_src/response_model/tutorial003.py!} +{!../../docs_src/response_model/tutorial003.py!} ``` 따라서 **FastAPI**는 출력 모델에서 선언하지 않은 모든 데이터를 (Pydantic을 사용하여) 필터링합니다. @@ -100,7 +100,7 @@ FastAPI는 이 `response_model`를 사용하여: 응답 모델은 아래와 같이 기본값을 가질 수 있습니다: ```Python hl_lines="11 13-14" -{!../../../docs_src/response_model/tutorial004.py!} +{!../../docs_src/response_model/tutorial004.py!} ``` * `description: Optional[str] = None`은 기본값으로 `None`을 갖습니다. @@ -116,7 +116,7 @@ FastAPI는 이 `response_model`를 사용하여: *경로 작동 데코레이터* 매개변수를 `response_model_exclude_unset=True`로 설정 할 수 있습니다: ```Python hl_lines="24" -{!../../../docs_src/response_model/tutorial004.py!} +{!../../docs_src/response_model/tutorial004.py!} ``` 이러한 기본값은 응답에 포함되지 않고 실제로 설정된 값만 포함됩니다. @@ -208,7 +208,7 @@ Pydantic 모델이 하나만 있고 출력에서 ​​일부 데이터를 제 /// ```Python hl_lines="31 37" -{!../../../docs_src/response_model/tutorial005.py!} +{!../../docs_src/response_model/tutorial005.py!} ``` /// tip | "팁" @@ -224,7 +224,7 @@ Pydantic 모델이 하나만 있고 출력에서 ​​일부 데이터를 제 `list` 또는 `tuple` 대신 `set`을 사용하는 법을 잊었더라도, FastAPI는 `set`으로 변환하고 정상적으로 작동합니다: ```Python hl_lines="31 37" -{!../../../docs_src/response_model/tutorial006.py!} +{!../../docs_src/response_model/tutorial006.py!} ``` ## 요약 diff --git a/docs/ko/docs/tutorial/response-status-code.md b/docs/ko/docs/tutorial/response-status-code.md index 48cb49cbf..57eef6ba1 100644 --- a/docs/ko/docs/tutorial/response-status-code.md +++ b/docs/ko/docs/tutorial/response-status-code.md @@ -9,7 +9,7 @@ * 기타 ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` /// note | "참고" @@ -77,7 +77,7 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 상기 예시 참고: ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` `201` 은 "생성됨"를 의미하는 상태 코드입니다. @@ -87,7 +87,7 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 `fastapi.status` 의 편의 변수를 사용할 수 있습니다. ```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} +{!../../docs_src/response_status_code/tutorial002.py!} ``` 이것은 단순히 작업을 편리하게 하기 위한 것으로, HTTP 상태 코드와 동일한 번호를 갖고있지만, 이를 사용하면 편집기의 자동완성 기능을 사용할 수 있습니다: diff --git a/docs/ko/docs/tutorial/schema-extra-example.md b/docs/ko/docs/tutorial/schema-extra-example.md index 7b5ccdd32..71052b334 100644 --- a/docs/ko/docs/tutorial/schema-extra-example.md +++ b/docs/ko/docs/tutorial/schema-extra-example.md @@ -11,7 +11,7 @@ //// tab | Python 3.10+ Pydantic v2 ```Python hl_lines="13-24" -{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} ``` //// @@ -19,7 +19,7 @@ //// tab | Python 3.10+ Pydantic v1 ```Python hl_lines="13-23" -{!> ../../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} ``` //// @@ -27,7 +27,7 @@ //// tab | Python 3.8+ Pydantic v2 ```Python hl_lines="15-26" -{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +{!> ../../docs_src/schema_extra_example/tutorial001.py!} ``` //// @@ -35,7 +35,7 @@ //// tab | Python 3.8+ Pydantic v1 ```Python hl_lines="15-25" -{!> ../../../docs_src/schema_extra_example/tutorial001_pv1.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_pv1.py!} ``` //// @@ -83,7 +83,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.10+ ```Python hl_lines="2 8-11" -{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} ``` //// @@ -91,7 +91,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.8+ ```Python hl_lines="4 10-13" -{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +{!> ../../docs_src/schema_extra_example/tutorial002.py!} ``` //// @@ -117,7 +117,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.10+ ```Python hl_lines="22-29" -{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} ``` //// @@ -125,7 +125,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.9+ ```Python hl_lines="22-29" -{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} ``` //// @@ -133,7 +133,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.8+ ```Python hl_lines="23-30" -{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} ``` //// @@ -147,7 +147,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 /// ```Python hl_lines="18-25" -{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} ``` //// @@ -161,7 +161,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 /// ```Python hl_lines="20-27" -{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +{!> ../../docs_src/schema_extra_example/tutorial003.py!} ``` //// @@ -179,7 +179,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.10+ ```Python hl_lines="23-38" -{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!} ``` //// @@ -187,7 +187,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.9+ ```Python hl_lines="23-38" -{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!} ``` //// @@ -195,7 +195,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.8+ ```Python hl_lines="24-39" -{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an.py!} ``` //// @@ -209,7 +209,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 /// ```Python hl_lines="19-34" -{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} ``` //// @@ -223,7 +223,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 /// ```Python hl_lines="21-36" -{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +{!> ../../docs_src/schema_extra_example/tutorial004.py!} ``` //// @@ -270,7 +270,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.10+ ```Python hl_lines="23-49" -{!> ../../../docs_src/schema_extra_example/tutorial005_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_an_py310.py!} ``` //// @@ -278,7 +278,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.9+ ```Python hl_lines="23-49" -{!> ../../../docs_src/schema_extra_example/tutorial005_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_an_py39.py!} ``` //// @@ -286,7 +286,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 //// tab | Python 3.8+ ```Python hl_lines="24-50" -{!> ../../../docs_src/schema_extra_example/tutorial005_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_an.py!} ``` //// @@ -300,7 +300,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 /// ```Python hl_lines="19-45" -{!> ../../../docs_src/schema_extra_example/tutorial005_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial005_py310.py!} ``` //// @@ -314,7 +314,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 /// ```Python hl_lines="21-47" -{!> ../../../docs_src/schema_extra_example/tutorial005.py!} +{!> ../../docs_src/schema_extra_example/tutorial005.py!} ``` //// diff --git a/docs/ko/docs/tutorial/security/get-current-user.md b/docs/ko/docs/tutorial/security/get-current-user.md index 9bf3d4ee1..56f5792a7 100644 --- a/docs/ko/docs/tutorial/security/get-current-user.md +++ b/docs/ko/docs/tutorial/security/get-current-user.md @@ -3,7 +3,7 @@ 이전 장에서 (의존성 주입 시스템을 기반으로 한)보안 시스템은 *경로 작동 함수*에서 `str`로 `token`을 제공했습니다: ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` 그러나 아직도 유용하지 않습니다. @@ -19,7 +19,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 //// tab | 파이썬 3.7 이상 ```Python hl_lines="5 12-16" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -27,7 +27,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 //// tab | 파이썬 3.10 이상 ```Python hl_lines="3 10-14" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -45,7 +45,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 //// tab | 파이썬 3.7 이상 ```Python hl_lines="25" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -53,7 +53,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 //// tab | 파이썬 3.10 이상 ```Python hl_lines="23" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -65,7 +65,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 //// tab | 파이썬 3.7 이상 ```Python hl_lines="19-22 26-27" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -73,7 +73,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 //// tab | 파이썬 3.10 이상 ```Python hl_lines="17-20 24-25" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -85,7 +85,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 //// tab | 파이썬 3.7 이상 ```Python hl_lines="31" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -93,7 +93,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 //// tab | 파이썬 3.10 이상 ```Python hl_lines="29" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// @@ -153,7 +153,7 @@ Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알 //// tab | 파이썬 3.7 이상 ```Python hl_lines="30-32" -{!> ../../../docs_src/security/tutorial002.py!} +{!> ../../docs_src/security/tutorial002.py!} ``` //// @@ -161,7 +161,7 @@ Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알 //// tab | 파이썬 3.10 이상 ```Python hl_lines="28-30" -{!> ../../../docs_src/security/tutorial002_py310.py!} +{!> ../../docs_src/security/tutorial002_py310.py!} ``` //// diff --git a/docs/ko/docs/tutorial/security/simple-oauth2.md b/docs/ko/docs/tutorial/security/simple-oauth2.md index 9593f96f5..fd18c1d47 100644 --- a/docs/ko/docs/tutorial/security/simple-oauth2.md +++ b/docs/ko/docs/tutorial/security/simple-oauth2.md @@ -55,7 +55,7 @@ OAuth2의 경우 문자열일 뿐입니다. //// tab | 파이썬 3.7 이상 ```Python hl_lines="4 76" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -63,7 +63,7 @@ OAuth2의 경우 문자열일 뿐입니다. //// tab | 파이썬 3.10 이상 ```Python hl_lines="2 74" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -117,7 +117,7 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` //// tab | 파이썬 3.7 이상 ```Python hl_lines="3 77-79" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -125,7 +125,7 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` //// tab | 파이썬 3.10 이상 ```Python hl_lines="1 75-77" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -157,7 +157,7 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` //// tab | P파이썬 3.7 이상 ```Python hl_lines="80-83" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -165,7 +165,7 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` //// tab | 파이썬 3.10 이상 ```Python hl_lines="78-81" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -213,7 +213,7 @@ UserInDB( //// tab | 파이썬 3.7 이상 ```Python hl_lines="85" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -221,7 +221,7 @@ UserInDB( //// tab | 파이썬 3.10 이상 ```Python hl_lines="83" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// @@ -253,7 +253,7 @@ UserInDB( //// tab | 파이썬 3.7 이상 ```Python hl_lines="58-66 69-72 90" -{!> ../../../docs_src/security/tutorial003.py!} +{!> ../../docs_src/security/tutorial003.py!} ``` //// @@ -261,7 +261,7 @@ UserInDB( //// tab | 파이썬 3.10 이상 ```Python hl_lines="55-64 67-70 88" -{!> ../../../docs_src/security/tutorial003_py310.py!} +{!> ../../docs_src/security/tutorial003_py310.py!} ``` //// diff --git a/docs/ko/docs/tutorial/static-files.md b/docs/ko/docs/tutorial/static-files.md index 360aaaa6b..90a60d193 100644 --- a/docs/ko/docs/tutorial/static-files.md +++ b/docs/ko/docs/tutorial/static-files.md @@ -8,7 +8,7 @@ * 특정 경로에 `StaticFiles()` 인스턴스를 "마운트" 합니다. ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` /// note | "기술적 세부사항" diff --git a/docs/nl/docs/python-types.md b/docs/nl/docs/python-types.md index a5562b795..00052037c 100644 --- a/docs/nl/docs/python-types.md +++ b/docs/nl/docs/python-types.md @@ -23,7 +23,7 @@ Als je een Python expert bent en alles al weet over type hints, sla dan dit hoof Laten we beginnen met een eenvoudig voorbeeld: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Het aanroepen van dit programma leidt tot het volgende resultaat: @@ -40,7 +40,7 @@ De functie voert het volgende uit: * Voeg samen met een spatie in het midden. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Bewerk het @@ -84,7 +84,7 @@ Dat is alles. Dat zijn de "type hints": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` Dit is niet hetzelfde als het declareren van standaardwaarden zoals bij: @@ -114,7 +114,7 @@ Nu kun je de opties bekijken en er doorheen scrollen totdat je de optie vindt di Bekijk deze functie, deze heeft al type hints: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Omdat de editor de types van de variabelen kent, krijgt u niet alleen aanvulling, maar ook controles op fouten: @@ -124,7 +124,7 @@ Omdat de editor de types van de variabelen kent, krijgt u niet alleen aanvulling Nu weet je hoe je het moet oplossen, converteer `age` naar een string met `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Types declareren @@ -145,7 +145,7 @@ Je kunt bijvoorbeeld het volgende gebruiken: * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Generieke types met typeparameters @@ -183,7 +183,7 @@ Als type, vul `list` in. Doordat de list een type is dat enkele interne types bevat, zet je ze tussen vierkante haakjes: ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006_py39.py!} +{!> ../../docs_src/python_types/tutorial006_py39.py!} ``` //// @@ -193,7 +193,7 @@ Doordat de list een type is dat enkele interne types bevat, zet je ze tussen vie Van `typing`, importeer `List` (met een hoofdletter `L`): ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` Declareer de variabele met dezelfde dubbele punt (`:`) syntax. @@ -203,7 +203,7 @@ Zet als type de `List` die je hebt geïmporteerd uit `typing`. Doordat de list een type is dat enkele interne types bevat, zet je ze tussen vierkante haakjes: ```Python hl_lines="4" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` //// @@ -241,7 +241,7 @@ Je kunt hetzelfde doen om `tuple`s en `set`s te declareren: //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial007_py39.py!} +{!> ../../docs_src/python_types/tutorial007_py39.py!} ``` //// @@ -249,7 +249,7 @@ Je kunt hetzelfde doen om `tuple`s en `set`s te declareren: //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial007.py!} +{!> ../../docs_src/python_types/tutorial007.py!} ``` //// @@ -270,7 +270,7 @@ De tweede typeparameter is voor de waarden (values) van het `dict`: //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008_py39.py!} +{!> ../../docs_src/python_types/tutorial008_py39.py!} ``` //// @@ -278,7 +278,7 @@ De tweede typeparameter is voor de waarden (values) van het `dict`: //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008.py!} +{!> ../../docs_src/python_types/tutorial008.py!} ``` //// @@ -300,7 +300,7 @@ In Python 3.10 is er ook een **nieuwe syntax** waarin je de mogelijke types kunt //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +{!> ../../docs_src/python_types/tutorial008b_py310.py!} ``` //// @@ -308,7 +308,7 @@ In Python 3.10 is er ook een **nieuwe syntax** waarin je de mogelijke types kunt //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008b.py!} +{!> ../../docs_src/python_types/tutorial008b.py!} ``` //// @@ -322,7 +322,7 @@ Je kunt declareren dat een waarde een type kan hebben, zoals `str`, maar dat het In Python 3.6 en hoger (inclusief Python 3.10) kun je het declareren door `Optional` te importeren en te gebruiken vanuit de `typing`-module. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Door `Optional[str]` te gebruiken in plaats van alleen `str`, kan de editor je helpen fouten te detecteren waarbij je ervan uit zou kunnen gaan dat een waarde altijd een `str` is, terwijl het in werkelijkheid ook `None` zou kunnen zijn. @@ -334,7 +334,7 @@ Dit betekent ook dat je in Python 3.10 `EenType | None` kunt gebruiken: //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial009_py310.py!} +{!> ../../docs_src/python_types/tutorial009_py310.py!} ``` //// @@ -342,7 +342,7 @@ Dit betekent ook dat je in Python 3.10 `EenType | None` kunt gebruiken: //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009.py!} +{!> ../../docs_src/python_types/tutorial009.py!} ``` //// @@ -350,7 +350,7 @@ Dit betekent ook dat je in Python 3.10 `EenType | None` kunt gebruiken: //// tab | Python 3.8+ alternative ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009b.py!} +{!> ../../docs_src/python_types/tutorial009b.py!} ``` //// @@ -371,7 +371,7 @@ Het gaat alleen om de woorden en naamgeving. Maar die naamgeving kan invloed heb Laten we als voorbeeld deze functie nemen: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c.py!} +{!../../docs_src/python_types/tutorial009c.py!} ``` De parameter `name` is gedefinieerd als `Optional[str]`, maar is **niet optioneel**, je kunt de functie niet aanroepen zonder de parameter: @@ -389,7 +389,7 @@ say_hi(name=None) # Dit werkt, None is geldig 🎉 Het goede nieuws is dat als je eenmaal Python 3.10 gebruikt, je je daar geen zorgen meer over hoeft te maken, omdat je dan gewoon `|` kunt gebruiken om unions van types te definiëren: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c_py310.py!} +{!../../docs_src/python_types/tutorial009c_py310.py!} ``` Dan hoef je je geen zorgen te maken over namen als `Optional` en `Union`. 😎 @@ -453,13 +453,13 @@ Je kunt een klasse ook declareren als het type van een variabele. Stel dat je een klasse `Person` hebt, met een naam: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Vervolgens kun je een variabele van het type `Persoon` declareren: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Dan krijg je ook nog eens volledige editorondersteuning: @@ -487,7 +487,7 @@ Een voorbeeld uit de officiële Pydantic-documentatie: //// tab | Python 3.10+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py310.py!} +{!> ../../docs_src/python_types/tutorial011_py310.py!} ``` //// @@ -495,7 +495,7 @@ Een voorbeeld uit de officiële Pydantic-documentatie: //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py39.py!} +{!> ../../docs_src/python_types/tutorial011_py39.py!} ``` //// @@ -503,7 +503,7 @@ Een voorbeeld uit de officiële Pydantic-documentatie: //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/python_types/tutorial011.py!} +{!> ../../docs_src/python_types/tutorial011.py!} ``` //// @@ -533,7 +533,7 @@ Python heeft ook een functie waarmee je **extra ../../../docs_src/python_types/tutorial013_py39.py!} +{!> ../../docs_src/python_types/tutorial013_py39.py!} ``` //// @@ -545,7 +545,7 @@ In versies lager dan Python 3.9 importeer je `Annotated` vanuit `typing_extensio Het wordt al geïnstalleerd met **FastAPI**. ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial013.py!} +{!> ../../docs_src/python_types/tutorial013.py!} ``` //// diff --git a/docs/pl/docs/tutorial/first-steps.md b/docs/pl/docs/tutorial/first-steps.md index 8f1b9b922..99c425f12 100644 --- a/docs/pl/docs/tutorial/first-steps.md +++ b/docs/pl/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ Najprostszy plik FastAPI może wyglądać tak: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Skopiuj to do pliku `main.py`. @@ -134,7 +134,7 @@ Możesz go również użyć do automatycznego generowania kodu dla klientów, kt ### Krok 1: zaimportuj `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` jest klasą, która zapewnia wszystkie funkcjonalności Twojego API. @@ -150,7 +150,7 @@ Oznacza to, że możesz korzystać ze wszystkich funkcjonalności ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_an_py310.py!} ``` //// @@ -25,7 +25,7 @@ Para conseguir isso, importe `JSONResponse` e retorne o seu conteúdo diretament //// tab | Python 3.9+ ```Python hl_lines="4 25" -{!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_an_py39.py!} ``` //// @@ -33,7 +33,7 @@ Para conseguir isso, importe `JSONResponse` e retorne o seu conteúdo diretament //// tab | Python 3.8+ ```Python hl_lines="4 26" -{!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_an.py!} ``` //// @@ -47,7 +47,7 @@ Faça uso da versão `Annotated` quando possível. /// ```Python hl_lines="2 23" -{!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} +{!> ../../docs_src/additional_status_codes/tutorial001_py310.py!} ``` //// @@ -61,7 +61,7 @@ Faça uso da versão `Annotated` quando possível. /// ```Python hl_lines="4 25" -{!> ../../../docs_src/additional_status_codes/tutorial001.py!} +{!> ../../docs_src/additional_status_codes/tutorial001.py!} ``` //// diff --git a/docs/pt/docs/advanced/advanced-dependencies.md b/docs/pt/docs/advanced/advanced-dependencies.md index 5a7b921b2..a656390a4 100644 --- a/docs/pt/docs/advanced/advanced-dependencies.md +++ b/docs/pt/docs/advanced/advanced-dependencies.md @@ -21,7 +21,7 @@ Para fazer isso, nós declaramos o método `__call__`: //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -29,7 +29,7 @@ Para fazer isso, nós declaramos o método `__call__`: //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -43,7 +43,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// @@ -57,7 +57,7 @@ E agora, nós podemos utilizar o `__init__` para declarar os parâmetros da inst //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -65,7 +65,7 @@ E agora, nós podemos utilizar o `__init__` para declarar os parâmetros da inst //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -79,7 +79,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// @@ -93,7 +93,7 @@ Nós poderíamos criar uma instância desta classe com: //// tab | Python 3.9+ ```Python hl_lines="18" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -101,7 +101,7 @@ Nós poderíamos criar uma instância desta classe com: //// tab | Python 3.8+ ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -115,7 +115,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// @@ -137,7 +137,7 @@ checker(q="somequery") //// tab | Python 3.9+ ```Python hl_lines="22" -{!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} ``` //// @@ -145,7 +145,7 @@ checker(q="somequery") //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/dependencies/tutorial011_an.py!} +{!> ../../docs_src/dependencies/tutorial011_an.py!} ``` //// @@ -159,7 +159,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial011.py!} +{!> ../../docs_src/dependencies/tutorial011.py!} ``` //// diff --git a/docs/pt/docs/advanced/async-tests.md b/docs/pt/docs/advanced/async-tests.md index 7cac26262..c81d6124b 100644 --- a/docs/pt/docs/advanced/async-tests.md +++ b/docs/pt/docs/advanced/async-tests.md @@ -33,13 +33,13 @@ Para um exemplos simples, vamos considerar uma estrutura de arquivos semelhante O arquivo `main.py` teria: ```Python -{!../../../docs_src/async_tests/main.py!} +{!../../docs_src/async_tests/main.py!} ``` O arquivo `test_main.py` teria os testes para para o arquivo `main.py`, ele poderia ficar assim: ```Python -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` ## Executá-lo @@ -61,7 +61,7 @@ $ pytest O marcador `@pytest.mark.anyio` informa ao pytest que esta função de teste deve ser invocada de maneira assíncrona: ```Python hl_lines="7" -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` /// tip | "Dica" @@ -73,7 +73,7 @@ Note que a função de teste é `async def` agora, no lugar de apenas `def` como Então podemos criar um `AsyncClient` com a aplicação, e enviar requisições assíncronas para ela utilizando `await`. ```Python hl_lines="9-12" -{!../../../docs_src/async_tests/test_main.py!} +{!../../docs_src/async_tests/test_main.py!} ``` Isso é equivalente a: diff --git a/docs/pt/docs/advanced/behind-a-proxy.md b/docs/pt/docs/advanced/behind-a-proxy.md index 2dfc5ca25..3c65b5a0a 100644 --- a/docs/pt/docs/advanced/behind-a-proxy.md +++ b/docs/pt/docs/advanced/behind-a-proxy.md @@ -19,7 +19,7 @@ Nesse caso, o caminho original `/app` seria servido em `/api/v1/app`. Embora todo o seu código esteja escrito assumindo que existe apenas `/app`. ```Python hl_lines="6" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} +{!../../docs_src/behind_a_proxy/tutorial001.py!} ``` E o proxy estaria **"removendo"** o **prefixo do caminho** dinamicamente antes de transmitir a solicitação para o servidor da aplicação (provavelmente Uvicorn via CLI do FastAPI), mantendo sua aplicação convencida de que está sendo servida em `/app`, para que você não precise atualizar todo o seu código para incluir o prefixo `/api/v1`. @@ -99,7 +99,7 @@ Você pode obter o `root_path` atual usado pela sua aplicação para cada solici Aqui estamos incluindo ele na mensagem apenas para fins de demonstração. ```Python hl_lines="8" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} +{!../../docs_src/behind_a_proxy/tutorial001.py!} ``` Então, se você iniciar o Uvicorn com: @@ -128,7 +128,7 @@ A resposta seria algo como: Alternativamente, se você não tiver uma maneira de fornecer uma opção de linha de comando como `--root-path` ou equivalente, você pode definir o parâmetro `--root-path` ao criar sua aplicação FastAPI: ```Python hl_lines="3" -{!../../../docs_src/behind_a_proxy/tutorial002.py!} +{!../../docs_src/behind_a_proxy/tutorial002.py!} ``` Passar o `root_path`h para `FastAPI` seria o equivalente a passar a opção de linha de comando `--root-path` para Uvicorn ou Hypercorn. @@ -310,7 +310,7 @@ Se você passar uma lista personalizada de `servers` e houver um `root_path` (po Por exemplo: ```Python hl_lines="4-7" -{!../../../docs_src/behind_a_proxy/tutorial003.py!} +{!../../docs_src/behind_a_proxy/tutorial003.py!} ``` Gerará um OpenAPI schema como: @@ -359,7 +359,7 @@ A interface de documentação interagirá com o servidor que você selecionar. Se você não quiser que o **FastAPI** inclua um servidor automático usando o `root_path`, você pode usar o parâmetro `root_path_in_servers=False`: ```Python hl_lines="9" -{!../../../docs_src/behind_a_proxy/tutorial004.py!} +{!../../docs_src/behind_a_proxy/tutorial004.py!} ``` e então ele não será incluído no OpenAPI schema. diff --git a/docs/pt/docs/advanced/events.md b/docs/pt/docs/advanced/events.md index 5f722763e..02f5b6d2b 100644 --- a/docs/pt/docs/advanced/events.md +++ b/docs/pt/docs/advanced/events.md @@ -32,7 +32,7 @@ Vamos iniciar com um exemplo e ver isso detalhadamente. Nós criamos uma função assíncrona chamada `lifespan()` com `yield` como este: ```Python hl_lines="16 19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` Aqui nós estamos simulando a *inicialização* custosa do carregamento do modelo colocando a (falsa) função de modelo no dicionário com modelos de _machine learning_ antes do `yield`. Este código será executado **antes** da aplicação **começar a receber requisições**, durante a *inicialização*. @@ -52,7 +52,7 @@ Talvez você precise inicializar uma nova versão, ou apenas cansou de executá- A primeira coisa a notar, é que estamos definindo uma função assíncrona com `yield`. Isso é muito semelhante à Dependências com `yield`. ```Python hl_lines="14-19" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` A primeira parte da função, antes do `yield`, será executada **antes** da aplicação inicializar. @@ -66,7 +66,7 @@ Se você verificar, a função está decorada com um `@asynccontextmanager`. Que converte a função em algo chamado de "**Gerenciador de Contexto Assíncrono**". ```Python hl_lines="1 13" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` Um **gerenciador de contexto** em Python é algo que você pode usar em uma declaração `with`, por exemplo, `open()` pode ser usado como um gerenciador de contexto: @@ -90,7 +90,7 @@ No nosso exemplo de código acima, nós não usamos ele diretamente, mas nós pa O parâmetro `lifespan` da aplicação `FastAPI` usa um **Gerenciador de Contexto Assíncrono**, então nós podemos passar nosso novo gerenciador de contexto assíncrono do `lifespan` para ele. ```Python hl_lines="22" -{!../../../docs_src/events/tutorial003.py!} +{!../../docs_src/events/tutorial003.py!} ``` ## Eventos alternativos (deprecados) @@ -114,7 +114,7 @@ Essas funções podem ser declaradas com `async def` ou `def` normal. Para adicionar uma função que deve rodar antes da aplicação iniciar, declare-a com o evento `"startup"`: ```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} +{!../../docs_src/events/tutorial001.py!} ``` Nesse caso, a função de manipulação de evento `startup` irá inicializar os itens do "banco de dados" (só um `dict`) com alguns valores. @@ -128,7 +128,7 @@ E sua aplicação não irá começar a receber requisições até que todos os m Para adicionar uma função que deve ser executada quando a aplicação estiver encerrando, declare ela com o evento `"shutdown"`: ```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} +{!../../docs_src/events/tutorial002.py!} ``` Aqui, a função de manipulação de evento `shutdown` irá escrever uma linha de texto `"Application shutdown"` no arquivo `log.txt`. diff --git a/docs/pt/docs/advanced/openapi-webhooks.md b/docs/pt/docs/advanced/openapi-webhooks.md index 2ccd0e819..5a0226c74 100644 --- a/docs/pt/docs/advanced/openapi-webhooks.md +++ b/docs/pt/docs/advanced/openapi-webhooks.md @@ -33,7 +33,7 @@ Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do Fast Quando você cria uma aplicação com o **FastAPI**, existe um atributo chamado `webhooks`, que você utilizar para defini-los da mesma maneira que você definiria as suas **operações de rotas**, utilizando por exemplo `@app.webhooks.post()`. ```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_webhooks/tutorial001.py!} +{!../../docs_src/openapi_webhooks/tutorial001.py!} ``` Os webhooks que você define aparecerão no esquema do **OpenAPI** e na **página de documentação** gerada automaticamente. diff --git a/docs/pt/docs/advanced/response-change-status-code.md b/docs/pt/docs/advanced/response-change-status-code.md index 99695c831..2ac5eca18 100644 --- a/docs/pt/docs/advanced/response-change-status-code.md +++ b/docs/pt/docs/advanced/response-change-status-code.md @@ -21,7 +21,7 @@ Você pode declarar um parâmetro do tipo `Response` em sua *função de operaç E então você pode definir o `status_code` neste objeto de retorno temporal. ```Python hl_lines="1 9 12" -{!../../../docs_src/response_change_status_code/tutorial001.py!} +{!../../docs_src/response_change_status_code/tutorial001.py!} ``` E então você pode retornar qualquer objeto que você precise, como você faria normalmente (um `dict`, um modelo de banco de dados, etc.). diff --git a/docs/pt/docs/advanced/response-directly.md b/docs/pt/docs/advanced/response-directly.md index fc571d39b..fd2a0eef1 100644 --- a/docs/pt/docs/advanced/response-directly.md +++ b/docs/pt/docs/advanced/response-directly.md @@ -35,7 +35,7 @@ Por exemplo, você não pode colocar um modelo do Pydantic em uma `JSONResponse` Para esses casos, você pode usar o `jsonable_encoder` para converter seus dados antes de repassá-los para a resposta: ```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` /// note | Detalhes Técnicos @@ -57,7 +57,7 @@ Vamos dizer quer retornar uma resposta ../../../docs_src/security/tutorial006_an_py39.py!} +{!> ../../docs_src/security/tutorial006_an_py39.py!} ``` //// @@ -31,7 +31,7 @@ Então, quando você digitar o usuário e senha, o navegador os envia automatica //// tab | Python 3.8+ ```Python hl_lines="2 7 11" -{!> ../../../docs_src/security/tutorial006_an.py!} +{!> ../../docs_src/security/tutorial006_an.py!} ``` //// @@ -45,7 +45,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="2 6 10" -{!> ../../../docs_src/security/tutorial006.py!} +{!> ../../docs_src/security/tutorial006.py!} ``` //// @@ -71,7 +71,7 @@ Então nós podemos utilizar o `secrets.compare_digest()` para garantir que o `c //// tab | Python 3.9+ ```Python hl_lines="1 12-24" -{!> ../../../docs_src/security/tutorial007_an_py39.py!} +{!> ../../docs_src/security/tutorial007_an_py39.py!} ``` //// @@ -79,7 +79,7 @@ Então nós podemos utilizar o `secrets.compare_digest()` para garantir que o `c //// tab | Python 3.8+ ```Python hl_lines="1 12-24" -{!> ../../../docs_src/security/tutorial007_an.py!} +{!> ../../docs_src/security/tutorial007_an.py!} ``` //// @@ -93,7 +93,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="1 11-21" -{!> ../../../docs_src/security/tutorial007.py!} +{!> ../../docs_src/security/tutorial007.py!} ``` //// @@ -164,7 +164,7 @@ Após detectar que as credenciais estão incorretas, retorne um `HTTPException` //// tab | Python 3.9+ ```Python hl_lines="26-30" -{!> ../../../docs_src/security/tutorial007_an_py39.py!} +{!> ../../docs_src/security/tutorial007_an_py39.py!} ``` //// @@ -172,7 +172,7 @@ Após detectar que as credenciais estão incorretas, retorne um `HTTPException` //// tab | Python 3.8+ ```Python hl_lines="26-30" -{!> ../../../docs_src/security/tutorial007_an.py!} +{!> ../../docs_src/security/tutorial007_an.py!} ``` //// @@ -186,7 +186,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="23-27" -{!> ../../../docs_src/security/tutorial007.py!} +{!> ../../docs_src/security/tutorial007.py!} ``` //// diff --git a/docs/pt/docs/advanced/security/oauth2-scopes.md b/docs/pt/docs/advanced/security/oauth2-scopes.md index 4ad7c807e..fa4594c89 100644 --- a/docs/pt/docs/advanced/security/oauth2-scopes.md +++ b/docs/pt/docs/advanced/security/oauth2-scopes.md @@ -65,7 +65,7 @@ Primeiro, vamos olhar rapidamente as partes que mudam dos exemplos do **Tutorial //// tab | Python 3.10+ ```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -73,7 +73,7 @@ Primeiro, vamos olhar rapidamente as partes que mudam dos exemplos do **Tutorial //// tab | Python 3.9+ ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -81,7 +81,7 @@ Primeiro, vamos olhar rapidamente as partes que mudam dos exemplos do **Tutorial //// tab | Python 3.8+ ```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -95,7 +95,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -109,7 +109,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -123,7 +123,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -139,7 +139,7 @@ O parâmetro `scopes` recebe um `dict` contendo cada escopo como chave e a descr //// tab | Python 3.10+ ```Python hl_lines="63-66" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -147,7 +147,7 @@ O parâmetro `scopes` recebe um `dict` contendo cada escopo como chave e a descr //// tab | Python 3.9+ ```Python hl_lines="63-66" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -155,7 +155,7 @@ O parâmetro `scopes` recebe um `dict` contendo cada escopo como chave e a descr //// tab | Python 3.8+ ```Python hl_lines="64-67" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -169,7 +169,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="62-65" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -183,7 +183,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="63-66" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -197,7 +197,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="63-66" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -229,7 +229,7 @@ Porém em sua aplicação, por segurança, você deve garantir que você apenas //// tab | Python 3.10+ ```Python hl_lines="156" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -237,7 +237,7 @@ Porém em sua aplicação, por segurança, você deve garantir que você apenas //// tab | Python 3.9+ ```Python hl_lines="156" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -245,7 +245,7 @@ Porém em sua aplicação, por segurança, você deve garantir que você apenas //// tab | Python 3.8+ ```Python hl_lines="157" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -259,7 +259,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="155" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -273,7 +273,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="156" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -287,7 +287,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="156" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -319,7 +319,7 @@ Nós estamos fazendo isso aqui para demonstrar como o **FastAPI** lida com escop //// tab | Python 3.10+ ```Python hl_lines="5 140 171" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -327,7 +327,7 @@ Nós estamos fazendo isso aqui para demonstrar como o **FastAPI** lida com escop //// tab | Python 3.9+ ```Python hl_lines="5 140 171" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -335,7 +335,7 @@ Nós estamos fazendo isso aqui para demonstrar como o **FastAPI** lida com escop //// tab | Python 3.8+ ```Python hl_lines="5 141 172" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -349,7 +349,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="4 139 168" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -363,7 +363,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="5 140 169" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -377,7 +377,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="5 140 169" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -409,7 +409,7 @@ A classe `SecurityScopes` é semelhante à classe `Request` (`Request` foi utili //// tab | Python 3.10+ ```Python hl_lines="9 106" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -417,7 +417,7 @@ A classe `SecurityScopes` é semelhante à classe `Request` (`Request` foi utili //// tab | Python 3.9+ ```Python hl_lines="9 106" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -425,7 +425,7 @@ A classe `SecurityScopes` é semelhante à classe `Request` (`Request` foi utili //// tab | Python 3.8+ ```Python hl_lines="9 107" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -439,7 +439,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="8 105" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -453,7 +453,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="9 106" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -467,7 +467,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="9 106" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -487,7 +487,7 @@ Nesta exceção, nós incluímos os escopos necessários (se houver algum) como //// tab | Python 3.10+ ```Python hl_lines="106 108-116" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -495,7 +495,7 @@ Nesta exceção, nós incluímos os escopos necessários (se houver algum) como //// tab | Python 3.9+ ```Python hl_lines="106 108-116" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -503,7 +503,7 @@ Nesta exceção, nós incluímos os escopos necessários (se houver algum) como //// tab | Python 3.8+ ```Python hl_lines="107 109-117" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -517,7 +517,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="105 107-115" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -531,7 +531,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="106 108-116" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -545,7 +545,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="106 108-116" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -567,7 +567,7 @@ Nós também verificamos que nós temos um usuário com o "*username*", e caso c //// tab | Python 3.10+ ```Python hl_lines="47 117-128" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -575,7 +575,7 @@ Nós também verificamos que nós temos um usuário com o "*username*", e caso c //// tab | Python 3.9+ ```Python hl_lines="47 117-128" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -583,7 +583,7 @@ Nós também verificamos que nós temos um usuário com o "*username*", e caso c //// tab | Python 3.8+ ```Python hl_lines="48 118-129" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -597,7 +597,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="46 116-127" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -611,7 +611,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="47 117-128" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -625,7 +625,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="47 117-128" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// @@ -639,7 +639,7 @@ Para isso, nós utilizamos `security_scopes.scopes`, que contém uma `list` com //// tab | Python 3.10+ ```Python hl_lines="129-135" -{!> ../../../docs_src/security/tutorial005_an_py310.py!} +{!> ../../docs_src/security/tutorial005_an_py310.py!} ``` //// @@ -647,7 +647,7 @@ Para isso, nós utilizamos `security_scopes.scopes`, que contém uma `list` com //// tab | Python 3.9+ ```Python hl_lines="129-135" -{!> ../../../docs_src/security/tutorial005_an_py39.py!} +{!> ../../docs_src/security/tutorial005_an_py39.py!} ``` //// @@ -655,7 +655,7 @@ Para isso, nós utilizamos `security_scopes.scopes`, que contém uma `list` com //// tab | Python 3.8+ ```Python hl_lines="130-136" -{!> ../../../docs_src/security/tutorial005_an.py!} +{!> ../../docs_src/security/tutorial005_an.py!} ``` //// @@ -669,7 +669,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="128-134" -{!> ../../../docs_src/security/tutorial005_py310.py!} +{!> ../../docs_src/security/tutorial005_py310.py!} ``` //// @@ -683,7 +683,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="129-135" -{!> ../../../docs_src/security/tutorial005_py39.py!} +{!> ../../docs_src/security/tutorial005_py39.py!} ``` //// @@ -697,7 +697,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="129-135" -{!> ../../../docs_src/security/tutorial005.py!} +{!> ../../docs_src/security/tutorial005.py!} ``` //// diff --git a/docs/pt/docs/advanced/settings.md b/docs/pt/docs/advanced/settings.md index db2b4c9cc..d32b70ed4 100644 --- a/docs/pt/docs/advanced/settings.md +++ b/docs/pt/docs/advanced/settings.md @@ -181,7 +181,7 @@ Você pode utilizar todas as ferramentas e funcionalidades de validação que s //// tab | Pydantic v2 ```Python hl_lines="2 5-8 11" -{!> ../../../docs_src/settings/tutorial001.py!} +{!> ../../docs_src/settings/tutorial001.py!} ``` //// @@ -195,7 +195,7 @@ Na versão 1 do Pydantic você importaria `BaseSettings` diretamente do módulo /// ```Python hl_lines="2 5-8 11" -{!> ../../../docs_src/settings/tutorial001_pv1.py!} +{!> ../../docs_src/settings/tutorial001_pv1.py!} ``` //// @@ -215,7 +215,7 @@ Depois ele irá converter e validar os dados. Assim, quando você utilizar aquel Depois, Você pode utilizar o novo objeto `settings` na sua aplicação: ```Python hl_lines="18-20" -{!../../../docs_src/settings/tutorial001.py!} +{!../../docs_src/settings/tutorial001.py!} ``` ### Executando o servidor @@ -251,13 +251,13 @@ Você também pode incluir essas configurações em um arquivo de um módulo sep Por exemplo, você pode adicionar um arquivo `config.py` com: ```Python -{!../../../docs_src/settings/app01/config.py!} +{!../../docs_src/settings/app01/config.py!} ``` E utilizar essa configuração em `main.py`: ```Python hl_lines="3 11-13" -{!../../../docs_src/settings/app01/main.py!} +{!../../docs_src/settings/app01/main.py!} ``` /// dica @@ -277,7 +277,7 @@ Isso é especialmente útil durante os testes, já que é bastante simples sobre Baseando-se no exemplo anterior, seu arquivo `config.py` seria parecido com isso: ```Python hl_lines="10" -{!../../../docs_src/settings/app02/config.py!} +{!../../docs_src/settings/app02/config.py!} ``` Perceba que dessa vez não criamos uma instância padrão `settings = Settings()`. @@ -289,7 +289,7 @@ Agora criamos a dependência que retorna um novo objeto `config.Settings()`. //// tab | Python 3.9+ ```Python hl_lines="6 12-13" -{!> ../../../docs_src/settings/app02_an_py39/main.py!} +{!> ../../docs_src/settings/app02_an_py39/main.py!} ``` //// @@ -297,7 +297,7 @@ Agora criamos a dependência que retorna um novo objeto `config.Settings()`. //// tab | Python 3.8+ ```Python hl_lines="6 12-13" -{!> ../../../docs_src/settings/app02_an/main.py!} +{!> ../../docs_src/settings/app02_an/main.py!} ``` //// @@ -311,7 +311,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="5 11-12" -{!> ../../../docs_src/settings/app02/main.py!} +{!> ../../docs_src/settings/app02/main.py!} ``` //// @@ -329,7 +329,7 @@ E então podemos declarar essas configurações como uma dependência na funçã //// tab | Python 3.9+ ```Python hl_lines="17 19-21" -{!> ../../../docs_src/settings/app02_an_py39/main.py!} +{!> ../../docs_src/settings/app02_an_py39/main.py!} ``` //// @@ -337,7 +337,7 @@ E então podemos declarar essas configurações como uma dependência na funçã //// tab | Python 3.8+ ```Python hl_lines="17 19-21" -{!> ../../../docs_src/settings/app02_an/main.py!} +{!> ../../docs_src/settings/app02_an/main.py!} ``` //// @@ -351,7 +351,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="16 18-20" -{!> ../../../docs_src/settings/app02/main.py!} +{!> ../../docs_src/settings/app02/main.py!} ``` //// @@ -361,7 +361,7 @@ Utilize a versão com `Annotated` se possível. Então seria muito fácil fornecer uma configuração diferente durante a execução dos testes sobrescrevendo a dependência de `get_settings`: ```Python hl_lines="9-10 13 21" -{!../../../docs_src/settings/app02/test_main.py!} +{!../../docs_src/settings/app02/test_main.py!} ``` Na sobrescrita da dependência, definimos um novo valor para `admin_email` quando instanciamos um novo objeto `Settings`, e então retornamos esse novo objeto. @@ -406,7 +406,7 @@ E então adicionar o seguinte código em `config.py`: //// tab | Pydantic v2 ```Python hl_lines="9" -{!> ../../../docs_src/settings/app03_an/config.py!} +{!> ../../docs_src/settings/app03_an/config.py!} ``` /// dica @@ -420,7 +420,7 @@ O atributo `model_config` é usado apenas para configuração do Pydantic. Você //// tab | Pydantic v1 ```Python hl_lines="9-10" -{!> ../../../docs_src/settings/app03_an/config_pv1.py!} +{!> ../../docs_src/settings/app03_an/config_pv1.py!} ``` /// dica @@ -465,7 +465,7 @@ Mas como estamos utilizando o decorador `@lru_cache` acima, o objeto `Settings` //// tab | Python 3.9+ ```Python hl_lines="1 11" -{!> ../../../docs_src/settings/app03_an_py39/main.py!} +{!> ../../docs_src/settings/app03_an_py39/main.py!} ``` //// @@ -473,7 +473,7 @@ Mas como estamos utilizando o decorador `@lru_cache` acima, o objeto `Settings` //// tab | Python 3.8+ ```Python hl_lines="1 11" -{!> ../../../docs_src/settings/app03_an/main.py!} +{!> ../../docs_src/settings/app03_an/main.py!} ``` //// @@ -487,7 +487,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="1 10" -{!> ../../../docs_src/settings/app03/main.py!} +{!> ../../docs_src/settings/app03/main.py!} ``` //// diff --git a/docs/pt/docs/advanced/sub-applications.md b/docs/pt/docs/advanced/sub-applications.md index 8149edc5a..7f0381cc2 100644 --- a/docs/pt/docs/advanced/sub-applications.md +++ b/docs/pt/docs/advanced/sub-applications.md @@ -11,7 +11,7 @@ Se você precisar ter duas aplicações FastAPI independentes, cada uma com seu Primeiro, crie a aplicação principal, de nível superior, **FastAPI**, e suas *operações de rota*: ```Python hl_lines="3 6-8" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Sub-aplicação @@ -21,7 +21,7 @@ Em seguida, crie sua sub-aplicação e suas *operações de rota*. Essa sub-aplicação é apenas outra aplicação FastAPI padrão, mas esta é a que será "montada": ```Python hl_lines="11 14-16" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Monte a sub-aplicação @@ -31,7 +31,7 @@ Na sua aplicação de nível superior, `app`, monte a sub-aplicação, `subapi`. Neste caso, ela será montada no caminho `/subapi`: ```Python hl_lines="11 19" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### Verifique a documentação automática da API diff --git a/docs/pt/docs/advanced/templates.md b/docs/pt/docs/advanced/templates.md index 6d231b3c2..88a5b940e 100644 --- a/docs/pt/docs/advanced/templates.md +++ b/docs/pt/docs/advanced/templates.md @@ -26,7 +26,7 @@ $ pip install jinja2 * Use o `template` que você criou para renderizar e retornar uma `TemplateResponse`, passe o nome do template, o request object, e um "context" dict com pares chave-valor a serem usados dentro do template do Jinja2. ```Python hl_lines="4 11 15-18" -{!../../../docs_src/templates/tutorial001.py!} +{!../../docs_src/templates/tutorial001.py!} ``` /// note @@ -56,7 +56,7 @@ Você também poderia usar `from starlette.templating import Jinja2Templates`. Então você pode escrever um template em `templates/item.html`, por exemplo: ```jinja hl_lines="7" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` ### Interpolação de Valores no Template @@ -110,13 +110,13 @@ Por exemplo, com um ID de `42`, isso renderizará: Você também pode usar `url_for()` dentro do template e usá-lo, por examplo, com o `StaticFiles` que você montou com o `name="static"`. ```jinja hl_lines="4" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` Neste exemplo, ele seria vinculado a um arquivo CSS em `static/styles.css` com: ```CSS hl_lines="4" -{!../../../docs_src/templates/static/styles.css!} +{!../../docs_src/templates/static/styles.css!} ``` E como você está usando `StaticFiles`, este arquivo CSS será automaticamente servido pela sua aplicação FastAPI na URL `/static/styles.css`. diff --git a/docs/pt/docs/advanced/testing-dependencies.md b/docs/pt/docs/advanced/testing-dependencies.md index 747dd7d06..f978350a5 100644 --- a/docs/pt/docs/advanced/testing-dependencies.md +++ b/docs/pt/docs/advanced/testing-dependencies.md @@ -31,7 +31,7 @@ E então o **FastAPI** chamará a sobreposição no lugar da dependência origin //// tab | Python 3.10+ ```Python hl_lines="26-27 30" -{!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} +{!> ../../docs_src/dependency_testing/tutorial001_an_py310.py!} ``` //// @@ -39,7 +39,7 @@ E então o **FastAPI** chamará a sobreposição no lugar da dependência origin //// tab | Python 3.9+ ```Python hl_lines="28-29 32" -{!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} +{!> ../../docs_src/dependency_testing/tutorial001_an_py39.py!} ``` //// @@ -47,7 +47,7 @@ E então o **FastAPI** chamará a sobreposição no lugar da dependência origin //// tab | Python 3.8+ ```Python hl_lines="29-30 33" -{!> ../../../docs_src/dependency_testing/tutorial001_an.py!} +{!> ../../docs_src/dependency_testing/tutorial001_an.py!} ``` //// @@ -61,7 +61,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="24-25 28" -{!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} +{!> ../../docs_src/dependency_testing/tutorial001_py310.py!} ``` //// @@ -75,7 +75,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="28-29 32" -{!> ../../../docs_src/dependency_testing/tutorial001.py!} +{!> ../../docs_src/dependency_testing/tutorial001.py!} ``` //// diff --git a/docs/pt/docs/advanced/testing-events.md b/docs/pt/docs/advanced/testing-events.md index 392fb741c..b6796e835 100644 --- a/docs/pt/docs/advanced/testing-events.md +++ b/docs/pt/docs/advanced/testing-events.md @@ -3,5 +3,5 @@ Quando você precisa que os seus manipuladores de eventos (`startup` e `shutdown`) sejam executados em seus testes, você pode utilizar o `TestClient` usando a instrução `with`: ```Python hl_lines="9-12 20-24" -{!../../../docs_src/app_testing/tutorial003.py!} +{!../../docs_src/app_testing/tutorial003.py!} ``` diff --git a/docs/pt/docs/advanced/testing-websockets.md b/docs/pt/docs/advanced/testing-websockets.md index f458a05d4..daa610df6 100644 --- a/docs/pt/docs/advanced/testing-websockets.md +++ b/docs/pt/docs/advanced/testing-websockets.md @@ -5,7 +5,7 @@ Você pode usar o mesmo `TestClient` para testar WebSockets. Para isso, você utiliza o `TestClient` dentro de uma instrução `with`, conectando com o WebSocket: ```Python hl_lines="27-31" -{!../../../docs_src/app_testing/tutorial002.py!} +{!../../docs_src/app_testing/tutorial002.py!} ``` /// note | "Nota" diff --git a/docs/pt/docs/advanced/using-request-directly.md b/docs/pt/docs/advanced/using-request-directly.md index 3dd0a8aef..c2114c214 100644 --- a/docs/pt/docs/advanced/using-request-directly.md +++ b/docs/pt/docs/advanced/using-request-directly.md @@ -30,7 +30,7 @@ Vamos imaginar que você deseja obter o endereço de IP/host do cliente dentro d Para isso você precisa acessar a requisição diretamente. ```Python hl_lines="1 7-8" -{!../../../docs_src/using_request_directly/tutorial001.py!} +{!../../docs_src/using_request_directly/tutorial001.py!} ``` Ao declarar o parâmetro com o tipo sendo um `Request` em sua *função de operação de rota*, o **FastAPI** saberá como passar o `Request` neste parâmetro. diff --git a/docs/pt/docs/advanced/wsgi.md b/docs/pt/docs/advanced/wsgi.md index 2c7ac1ffe..e6d08c8db 100644 --- a/docs/pt/docs/advanced/wsgi.md +++ b/docs/pt/docs/advanced/wsgi.md @@ -13,7 +13,7 @@ Em seguinda, encapsular a aplicação WSGI (e.g. Flask) com o middleware. E então **"montar"** em um caminho de rota. ```Python hl_lines="2-3 23" -{!../../../docs_src/wsgi/tutorial001.py!} +{!../../docs_src/wsgi/tutorial001.py!} ``` ## Conferindo diff --git a/docs/pt/docs/how-to/conditional-openapi.md b/docs/pt/docs/how-to/conditional-openapi.md index cfa652fa5..675b812e6 100644 --- a/docs/pt/docs/how-to/conditional-openapi.md +++ b/docs/pt/docs/how-to/conditional-openapi.md @@ -30,7 +30,7 @@ Você pode usar facilmente as mesmas configurações do Pydantic para configurar Por exemplo: ```Python hl_lines="6 11" -{!../../../docs_src/conditional_openapi/tutorial001.py!} +{!../../docs_src/conditional_openapi/tutorial001.py!} ``` Aqui declaramos a configuração `openapi_url` com o mesmo padrão de `"/openapi.json"`. diff --git a/docs/pt/docs/how-to/configure-swagger-ui.md b/docs/pt/docs/how-to/configure-swagger-ui.md index ceb8c634e..58bb1557c 100644 --- a/docs/pt/docs/how-to/configure-swagger-ui.md +++ b/docs/pt/docs/how-to/configure-swagger-ui.md @@ -19,7 +19,7 @@ Sem alterar as configurações, o destaque de sintaxe é habilitado por padrão: Mas você pode desabilitá-lo definindo `syntaxHighlight` como `False`: ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial001.py!} +{!../../docs_src/configure_swagger_ui/tutorial001.py!} ``` ...e então o Swagger UI não mostrará mais o destaque de sintaxe: @@ -31,7 +31,7 @@ Mas você pode desabilitá-lo definindo `syntaxHighlight` como `False`: Da mesma forma que você pode definir o tema de destaque de sintaxe com a chave `"syntaxHighlight.theme"` (observe que há um ponto no meio): ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial002.py!} +{!../../docs_src/configure_swagger_ui/tutorial002.py!} ``` Essa configuração alteraria o tema de cores de destaque de sintaxe: @@ -45,7 +45,7 @@ O FastAPI inclui alguns parâmetros de configuração padrão apropriados para a Inclui estas configurações padrão: ```Python -{!../../../fastapi/openapi/docs.py[ln:7-23]!} +{!../../fastapi/openapi/docs.py[ln:7-23]!} ``` Você pode substituir qualquer um deles definindo um valor diferente no argumento `swagger_ui_parameters`. @@ -53,7 +53,7 @@ Você pode substituir qualquer um deles definindo um valor diferente no argument Por exemplo, para desabilitar `deepLinking` você pode passar essas configurações para `swagger_ui_parameters`: ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial003.py!} +{!../../docs_src/configure_swagger_ui/tutorial003.py!} ``` ## Outros parâmetros da UI do Swagger diff --git a/docs/pt/docs/how-to/graphql.md b/docs/pt/docs/how-to/graphql.md index 0b711aa5e..2cfd790c5 100644 --- a/docs/pt/docs/how-to/graphql.md +++ b/docs/pt/docs/how-to/graphql.md @@ -36,7 +36,7 @@ Dependendo do seu caso de uso, você pode preferir usar uma biblioteca diferente Aqui está uma pequena prévia de como você poderia integrar Strawberry com FastAPI: ```Python hl_lines="3 22 25-26" -{!../../../docs_src/graphql/tutorial001.py!} +{!../../docs_src/graphql/tutorial001.py!} ``` Você pode aprender mais sobre Strawberry na documentação do Strawberry. diff --git a/docs/pt/docs/python-types.md b/docs/pt/docs/python-types.md index 86630cd2a..05faa860c 100644 --- a/docs/pt/docs/python-types.md +++ b/docs/pt/docs/python-types.md @@ -23,7 +23,7 @@ Se você é um especialista em Python e já sabe tudo sobre type hints, pule par Vamos começar com um exemplo simples: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` A chamada deste programa gera: @@ -39,7 +39,7 @@ A função faz o seguinte: * Concatena com um espaço no meio. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Edite-o @@ -83,7 +83,7 @@ para: Esses são os "type hints": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` Isso não é o mesmo que declarar valores padrão como seria com: @@ -113,7 +113,7 @@ Com isso, você pode rolar, vendo as opções, até encontrar o que "toca uma ca Marque esta função, ela já possui type hints: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Como o editor conhece os tipos de variáveis, você não apenas obtém a conclusão, mas também as verificações de erro: @@ -123,7 +123,7 @@ Como o editor conhece os tipos de variáveis, você não apenas obtém a conclus Agora você sabe que precisa corrigí-lo, converta `age` em uma string com `str (age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Tipos de declaração @@ -144,7 +144,7 @@ Você pode usar, por exemplo: * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Tipos genéricos com parâmetros de tipo @@ -162,7 +162,7 @@ Por exemplo, vamos definir uma variável para ser uma `lista` de `str`. Em `typing`, importe `List` (com um `L` maiúsculo): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` Declare a variável com a mesma sintaxe de dois pontos (`:`). @@ -172,7 +172,7 @@ Como o tipo, coloque a `List`. Como a lista é um tipo que contém alguns tipos internos, você os coloca entre colchetes: ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` /// tip | "Dica" @@ -200,7 +200,7 @@ E, ainda assim, o editor sabe que é um `str` e fornece suporte para isso. Você faria o mesmo para declarar `tuple`s e `set`s: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` Isso significa que: @@ -217,7 +217,7 @@ O primeiro parâmetro de tipo é para as chaves do `dict`. O segundo parâmetro de tipo é para os valores do `dict`: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` Isso significa que: @@ -231,7 +231,7 @@ Isso significa que: Você também pode usar o `Opcional` para declarar que uma variável tem um tipo, como `str`, mas que é "opcional", o que significa que também pode ser `None`: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` O uso de `Opcional [str]` em vez de apenas `str` permitirá que o editor o ajude a detectar erros, onde você pode estar assumindo que um valor é sempre um `str`, quando na verdade também pode ser `None`. @@ -256,13 +256,13 @@ Você também pode declarar uma classe como o tipo de uma variável. Digamos que você tenha uma classe `Person`, com um nome: ```Python hl_lines="1 2 3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Então você pode declarar que uma variável é do tipo `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` E então, novamente, você recebe todo o suporte do editor: @@ -284,7 +284,7 @@ E você recebe todo o suporte do editor com esse objeto resultante. Retirado dos documentos oficiais dos Pydantic: ```Python -{!../../../docs_src/python_types/tutorial011.py!} +{!../../docs_src/python_types/tutorial011.py!} ``` /// info | "Informação" diff --git a/docs/pt/docs/tutorial/background-tasks.md b/docs/pt/docs/tutorial/background-tasks.md index 625fa2b11..2b5f82464 100644 --- a/docs/pt/docs/tutorial/background-tasks.md +++ b/docs/pt/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ Isso inclui, por exemplo: Primeiro, importe `BackgroundTasks` e defina um parâmetro em sua _função de operação de caminho_ com uma declaração de tipo de `BackgroundTasks`: ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` O **FastAPI** criará o objeto do tipo `BackgroundTasks` para você e o passará como esse parâmetro. @@ -34,7 +34,7 @@ Nesse caso, a função de tarefa gravará em um arquivo (simulando o envio de um E como a operação de gravação não usa `async` e `await`, definimos a função com `def` normal: ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## Adicionar a tarefa em segundo plano @@ -42,7 +42,7 @@ E como a operação de gravação não usa `async` e `await`, definimos a funç Dentro de sua _função de operação de caminho_, passe sua função de tarefa para o objeto _tarefas em segundo plano_ com o método `.add_task()`: ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` recebe como argumentos: @@ -58,7 +58,7 @@ Usar `BackgroundTasks` também funciona com o sistema de injeção de dependênc O **FastAPI** sabe o que fazer em cada caso e como reutilizar o mesmo objeto, de forma que todas as tarefas em segundo plano sejam mescladas e executadas em segundo plano posteriormente: ```Python hl_lines="13 15 22 25" -{!../../../docs_src/background_tasks/tutorial002.py!} +{!../../docs_src/background_tasks/tutorial002.py!} ``` Neste exemplo, as mensagens serão gravadas no arquivo `log.txt` _após_ o envio da resposta. diff --git a/docs/pt/docs/tutorial/bigger-applications.md b/docs/pt/docs/tutorial/bigger-applications.md index 7137bf865..fcc30961f 100644 --- a/docs/pt/docs/tutorial/bigger-applications.md +++ b/docs/pt/docs/tutorial/bigger-applications.md @@ -86,7 +86,7 @@ Você pode criar as *operações de rotas* para esse módulo usando o `APIRouter você o importa e cria uma "instância" da mesma maneira que faria com a classe `FastAPI`: ```Python hl_lines="1 3" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` ### *Operações de Rota* com `APIRouter` @@ -96,7 +96,7 @@ E então você o utiliza para declarar suas *operações de rota*. Utilize-o da mesma maneira que utilizaria a classe `FastAPI`: ```Python hl_lines="6 11 16" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` Você pode pensar em `APIRouter` como uma classe "mini `FastAPI`". @@ -124,7 +124,7 @@ Agora usaremos uma dependência simples para ler um cabeçalho `X-Token` persona //// tab | Python 3.9+ ```Python hl_lines="3 6-8" title="app/dependencies.py" -{!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!} ``` //// @@ -132,7 +132,7 @@ Agora usaremos uma dependência simples para ler um cabeçalho `X-Token` persona //// tab | Python 3.8+ ```Python hl_lines="1 5-7" title="app/dependencies.py" -{!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} +{!> ../../docs_src/bigger_applications/app_an/dependencies.py!} ``` //// @@ -146,7 +146,7 @@ Prefira usar a versão `Annotated` se possível. /// ```Python hl_lines="1 4-6" title="app/dependencies.py" -{!> ../../../docs_src/bigger_applications/app/dependencies.py!} +{!> ../../docs_src/bigger_applications/app/dependencies.py!} ``` //// @@ -182,7 +182,7 @@ Sabemos que todas as *operações de rota* neste módulo têm o mesmo: Então, em vez de adicionar tudo isso a cada *operação de rota*, podemos adicioná-lo ao `APIRouter`. ```Python hl_lines="5-10 16 21" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` Como o caminho de cada *operação de rota* deve começar com `/`, como em: @@ -243,7 +243,7 @@ E precisamos obter a função de dependência do módulo `app.dependencies`, o a Então usamos uma importação relativa com `..` para as dependências: ```Python hl_lines="3" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` #### Como funcionam as importações relativas @@ -316,7 +316,7 @@ Não estamos adicionando o prefixo `/items` nem `tags=["items"]` a cada *operaç Mas ainda podemos adicionar _mais_ `tags` que serão aplicadas a uma *operação de rota* específica, e também algumas `respostas` extras específicas para essa *operação de rota*: ```Python hl_lines="30-31" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` /// tip | "Dica" @@ -344,7 +344,7 @@ Você importa e cria uma classe `FastAPI` normalmente. E podemos até declarar [dependências globais](dependencies/global-dependencies.md){.internal-link target=_blank} que serão combinadas com as dependências para cada `APIRouter`: ```Python hl_lines="1 3 7" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### Importe o `APIRouter` @@ -352,7 +352,7 @@ E podemos até declarar [dependências globais](dependencies/global-dependencies Agora importamos os outros submódulos que possuem `APIRouter`s: ```Python hl_lines="4-5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` Como os arquivos `app/routers/users.py` e `app/routers/items.py` são submódulos que fazem parte do mesmo pacote Python `app`, podemos usar um único ponto `.` para importá-los usando "importações relativas". @@ -417,7 +417,7 @@ o `router` de `users` sobrescreveria o de `items` e não poderíamos usá-los ao Então, para poder usar ambos no mesmo arquivo, importamos os submódulos diretamente: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### Incluir o `APIRouter`s para `usuários` e `itens` @@ -425,7 +425,7 @@ Então, para poder usar ambos no mesmo arquivo, importamos os submódulos direta Agora, vamos incluir os `roteadores` dos submódulos `usuários` e `itens`: ```Python hl_lines="10-11" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` /// info | "Informação" @@ -467,7 +467,7 @@ Ele contém um `APIRouter` com algumas *operações de rota* de administração Para este exemplo, será super simples. Mas digamos que, como ele é compartilhado com outros projetos na organização, não podemos modificá-lo e adicionar um `prefix`, `dependencies`, `tags`, etc. diretamente ao `APIRouter`: ```Python hl_lines="3" title="app/internal/admin.py" -{!../../../docs_src/bigger_applications/app/internal/admin.py!} +{!../../docs_src/bigger_applications/app/internal/admin.py!} ``` Mas ainda queremos definir um `prefixo` personalizado ao incluir o `APIRouter` para que todas as suas *operações de rota* comecem com `/admin`, queremos protegê-lo com as `dependências` que já temos para este projeto e queremos incluir `tags` e `responses`. @@ -475,7 +475,7 @@ Mas ainda queremos definir um `prefixo` personalizado ao incluir o `APIRouter` p Podemos declarar tudo isso sem precisar modificar o `APIRouter` original passando esses parâmetros para `app.include_router()`: ```Python hl_lines="14-17" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` Dessa forma, o `APIRouter` original permanecerá inalterado, para que possamos compartilhar o mesmo arquivo `app/internal/admin.py` com outros projetos na organização. @@ -498,7 +498,7 @@ Também podemos adicionar *operações de rota* diretamente ao aplicativo `FastA Aqui fazemos isso... só para mostrar que podemos 🤷: ```Python hl_lines="21-23" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` e funcionará corretamente, junto com todas as outras *operações de rota* adicionadas com `app.include_router()`. diff --git a/docs/pt/docs/tutorial/body-fields.md b/docs/pt/docs/tutorial/body-fields.md index cce37cd55..ab9377fdb 100644 --- a/docs/pt/docs/tutorial/body-fields.md +++ b/docs/pt/docs/tutorial/body-fields.md @@ -7,7 +7,7 @@ Da mesma forma que você pode declarar validações adicionais e metadados nos p Primeiro, você tem que importá-lo: ```Python hl_lines="4" -{!../../../docs_src/body_fields/tutorial001.py!} +{!../../docs_src/body_fields/tutorial001.py!} ``` /// warning | "Aviso" @@ -21,7 +21,7 @@ Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como Você pode então utilizar `Field` com atributos do modelo: ```Python hl_lines="11-14" -{!../../../docs_src/body_fields/tutorial001.py!} +{!../../docs_src/body_fields/tutorial001.py!} ``` `Field` funciona da mesma forma que `Query`, `Path` e `Body`, ele possui todos os mesmos parâmetros, etc. diff --git a/docs/pt/docs/tutorial/body-multiple-params.md b/docs/pt/docs/tutorial/body-multiple-params.md index d36dd60b3..400813a7b 100644 --- a/docs/pt/docs/tutorial/body-multiple-params.md +++ b/docs/pt/docs/tutorial/body-multiple-params.md @@ -11,7 +11,7 @@ E você também pode declarar parâmetros de corpo como opcionais, definindo o v //// tab | Python 3.10+ ```Python hl_lines="17-19" -{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} ``` //// @@ -19,7 +19,7 @@ E você também pode declarar parâmetros de corpo como opcionais, definindo o v //// tab | Python 3.8+ ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +{!> ../../docs_src/body_multiple_params/tutorial001.py!} ``` //// @@ -48,7 +48,7 @@ Mas você pode também declarar múltiplos parâmetros de corpo, por exemplo, `i //// tab | Python 3.10+ ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} ``` //// @@ -56,7 +56,7 @@ Mas você pode também declarar múltiplos parâmetros de corpo, por exemplo, `i //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +{!> ../../docs_src/body_multiple_params/tutorial002.py!} ``` //// @@ -103,7 +103,7 @@ Mas você pode instruir o **FastAPI** para tratá-lo como outra chave do corpo u //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +{!> ../../docs_src/body_multiple_params/tutorial003.py!} ``` //// @@ -111,7 +111,7 @@ Mas você pode instruir o **FastAPI** para tratá-lo como outra chave do corpo u //// tab | Python 3.10+ ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} ``` //// @@ -157,7 +157,7 @@ Por exemplo: //// tab | Python 3.10+ ```Python hl_lines="26" -{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` //// @@ -165,7 +165,7 @@ Por exemplo: //// tab | Python 3.8+ ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +{!> ../../docs_src/body_multiple_params/tutorial004.py!} ``` //// @@ -193,7 +193,7 @@ como em: //// tab | Python 3.10+ ```Python hl_lines="15" -{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} ``` //// @@ -201,7 +201,7 @@ como em: //// tab | Python 3.8+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +{!> ../../docs_src/body_multiple_params/tutorial005.py!} ``` //// diff --git a/docs/pt/docs/tutorial/body-nested-models.md b/docs/pt/docs/tutorial/body-nested-models.md index 7d933b27f..3aa79d563 100644 --- a/docs/pt/docs/tutorial/body-nested-models.md +++ b/docs/pt/docs/tutorial/body-nested-models.md @@ -7,7 +7,7 @@ Com o **FastAPI**, você pode definir, validar, documentar e usar modelos profun Você pode definir um atributo como um subtipo. Por exemplo, uma `list` do Python: ```Python hl_lines="14" -{!../../../docs_src/body_nested_models/tutorial001.py!} +{!../../docs_src/body_nested_models/tutorial001.py!} ``` Isso fará com que tags seja uma lista de itens mesmo sem declarar o tipo dos elementos desta lista. @@ -21,7 +21,7 @@ Mas o Python tem uma maneira específica de declarar listas com tipos internos o Primeiramente, importe `List` do módulo `typing` que já vem por padrão no Python: ```Python hl_lines="1" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!../../docs_src/body_nested_models/tutorial002.py!} ``` ### Declare a `List` com um parâmetro de tipo @@ -45,7 +45,7 @@ Portanto, em nosso exemplo, podemos fazer com que `tags` sejam especificamente u ```Python hl_lines="14" -{!../../../docs_src/body_nested_models/tutorial002.py!} +{!../../docs_src/body_nested_models/tutorial002.py!} ``` ## Tipo "set" @@ -59,7 +59,7 @@ Então podemos importar `Set` e declarar `tags` como um `set` de `str`s: ```Python hl_lines="1 14" -{!../../../docs_src/body_nested_models/tutorial003.py!} +{!../../docs_src/body_nested_models/tutorial003.py!} ``` Com isso, mesmo que você receba uma requisição contendo dados duplicados, ela será convertida em um conjunto de itens exclusivos. @@ -83,7 +83,7 @@ Tudo isso, aninhado arbitrariamente. Por exemplo, nós podemos definir um modelo `Image`: ```Python hl_lines="9-11" -{!../../../docs_src/body_nested_models/tutorial004.py!} +{!../../docs_src/body_nested_models/tutorial004.py!} ``` ### Use o sub-modelo como um tipo @@ -91,7 +91,7 @@ Por exemplo, nós podemos definir um modelo `Image`: E então podemos usa-lo como o tipo de um atributo: ```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial004.py!} +{!../../docs_src/body_nested_models/tutorial004.py!} ``` Isso significa que o **FastAPI** vai esperar um corpo similar à: @@ -126,7 +126,7 @@ Para ver todas as opções possíveis, cheque a documentação para os ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ Primeiro importe `Cookie`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Primeiro importe `Cookie`: //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -68,7 +68,7 @@ Você pode definir o valor padrão, assim como todas as validações extras ou p //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -76,7 +76,7 @@ Você pode definir o valor padrão, assim como todas as validações extras ou p //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -84,7 +84,7 @@ Você pode definir o valor padrão, assim como todas as validações extras ou p //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -98,7 +98,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -112,7 +112,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// diff --git a/docs/pt/docs/tutorial/cors.md b/docs/pt/docs/tutorial/cors.md index e5e2f8c27..16c4e9bf5 100644 --- a/docs/pt/docs/tutorial/cors.md +++ b/docs/pt/docs/tutorial/cors.md @@ -47,7 +47,7 @@ Você também pode especificar se o seu backend permite: * Cabeçalhos HTTP específicos ou todos eles com o curinga `"*"`. ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` Os parâmetros padrão usados ​​pela implementação `CORSMiddleware` são restritivos por padrão, então você precisará habilitar explicitamente as origens, métodos ou cabeçalhos específicos para que os navegadores tenham permissão para usá-los em um contexto de domínios diferentes. diff --git a/docs/pt/docs/tutorial/debugging.md b/docs/pt/docs/tutorial/debugging.md index 54582fcbc..6bac7eb85 100644 --- a/docs/pt/docs/tutorial/debugging.md +++ b/docs/pt/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ Você pode conectar o depurador no seu editor, por exemplo, com o Visual Studio Em seu aplicativo FastAPI, importe e execute `uvicorn` diretamente: ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### Sobre `__name__ == "__main__"` diff --git a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md index 420503b87..179bfefb5 100644 --- a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md @@ -9,7 +9,7 @@ No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injet //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injet //// tab | Python 3.9+ ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injet //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -122,7 +122,7 @@ Então, podemos mudar o "injetável" na dependência `common_parameters` acima p //// tab | Python 3.10+ ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -130,7 +130,7 @@ Então, podemos mudar o "injetável" na dependência `common_parameters` acima p //// tab | Python 3.9+ ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -138,7 +138,7 @@ Então, podemos mudar o "injetável" na dependência `common_parameters` acima p //// tab | Python 3.8+ ```Python hl_lines="12-16" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -152,7 +152,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="9-13" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -166,7 +166,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -176,7 +176,7 @@ Observe o método `__init__` usado para criar uma instância da classe: //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -184,7 +184,7 @@ Observe o método `__init__` usado para criar uma instância da classe: //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -192,7 +192,7 @@ Observe o método `__init__` usado para criar uma instância da classe: //// tab | Python 3.8+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -206,7 +206,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -220,7 +220,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -230,7 +230,7 @@ Utilize a versão com `Annotated` se possível. //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -238,7 +238,7 @@ Utilize a versão com `Annotated` se possível. //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -246,7 +246,7 @@ Utilize a versão com `Annotated` se possível. //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -260,7 +260,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="6" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -274,7 +274,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -296,7 +296,7 @@ Agora você pode declarar sua dependência utilizando essa classe. //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -304,7 +304,7 @@ Agora você pode declarar sua dependência utilizando essa classe. //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -312,7 +312,7 @@ Agora você pode declarar sua dependência utilizando essa classe. //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -326,7 +326,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -340,7 +340,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -440,7 +440,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_an_py310.py!} ``` //// @@ -448,7 +448,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial003_an_py39.py!} ``` //// @@ -456,7 +456,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial003_an.py!} +{!> ../../docs_src/dependencies/tutorial003_an.py!} ``` //// @@ -470,7 +470,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_py310.py!} ``` //// @@ -484,7 +484,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003.py!} +{!> ../../docs_src/dependencies/tutorial003.py!} ``` //// @@ -578,7 +578,7 @@ O mesmo exemplo ficaria então dessa forma: //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_an_py310.py!} ``` //// @@ -586,7 +586,7 @@ O mesmo exemplo ficaria então dessa forma: //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial004_an_py39.py!} ``` //// @@ -594,7 +594,7 @@ O mesmo exemplo ficaria então dessa forma: //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial004_an.py!} +{!> ../../docs_src/dependencies/tutorial004_an.py!} ``` //// @@ -608,7 +608,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_py310.py!} ``` //// @@ -622,7 +622,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004.py!} +{!> ../../docs_src/dependencies/tutorial004.py!} ``` //// diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 4a7a29390..7d7086945 100644 --- a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -17,7 +17,7 @@ Ele deve ser uma lista de `Depends()`: //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Ele deve ser uma lista de `Depends()`: //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -39,7 +39,7 @@ Utilize a versão com `Annotated` se possível /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -75,7 +75,7 @@ Dependências podem declarar requisitos de requisições (como cabeçalhos) ou o //// tab | Python 3.9+ ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ Dependências podem declarar requisitos de requisições (como cabeçalhos) ou o //// tab | Python 3.8+ ```Python hl_lines="7 12" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -97,7 +97,7 @@ Utilize a versão com `Annotated` se possível /// ```Python hl_lines="6 11" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -109,7 +109,7 @@ Essas dependências podem levantar exceções, da mesma forma que dependências //// tab | Python 3.9+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -117,7 +117,7 @@ Essas dependências podem levantar exceções, da mesma forma que dependências //// tab | Python 3.8+ ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -131,7 +131,7 @@ Utilize a versão com `Annotated` se possível /// ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -145,7 +145,7 @@ Então, você pode reutilizar uma dependência comum (que retorna um valor) que //// tab | Python 3.9+ ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -153,7 +153,7 @@ Então, você pode reutilizar uma dependência comum (que retorna um valor) que //// tab | Python 3.8+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -169,7 +169,7 @@ Então, você pode reutilizar uma dependência comum (que retorna um valor) que Utilize a versão com `Annotated` se possível ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md index 16c2cf899..d90bebe39 100644 --- a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md @@ -30,19 +30,19 @@ Por exemplo, você poderia utilizar isso para criar uma sessão do banco de dado Apenas o código anterior a declaração com `yield` e o código contendo essa declaração são executados antes de criar uma resposta. ```Python hl_lines="2-4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` O valor gerado (yielded) é o que é injetado nas *operações de rota* e outras dependências. ```Python hl_lines="4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` O código após o `yield` é executado após a resposta ser entregue: ```Python hl_lines="5-6" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` /// tip | "Dica" @@ -64,7 +64,7 @@ Então, você pode procurar por essa exceção específica dentro da dependênci Da mesma forma, você pode utilizar `finally` para garantir que os passos de saída são executados, com ou sem exceções. ```python hl_lines="3 5" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` ## Subdependências com `yield` @@ -78,7 +78,7 @@ Por exemplo, `dependency_c` pode depender de `dependency_b`, e `dependency_b` de //// tab | python 3.9+ ```python hl_lines="6 14 22" -{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} ``` //// @@ -86,7 +86,7 @@ Por exemplo, `dependency_c` pode depender de `dependency_b`, e `dependency_b` de //// tab | python 3.8+ ```python hl_lines="5 13 21" -{!> ../../../docs_src/dependencies/tutorial008_an.py!} +{!> ../../docs_src/dependencies/tutorial008_an.py!} ``` //// @@ -100,7 +100,7 @@ Utilize a versão com `Annotated` se possível. /// ```python hl_lines="4 12 20" -{!> ../../../docs_src/dependencies/tutorial008.py!} +{!> ../../docs_src/dependencies/tutorial008.py!} ``` //// @@ -114,7 +114,7 @@ E, por outro lado, `dependency_b` precisa que o valor de `dependency_a` (nomeada //// tab | python 3.9+ ```python hl_lines="18-19 26-27" -{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} ``` //// @@ -122,7 +122,7 @@ E, por outro lado, `dependency_b` precisa que o valor de `dependency_a` (nomeada //// tab | python 3.8+ ```python hl_lines="17-18 25-26" -{!> ../../../docs_src/dependencies/tutorial008_an.py!} +{!> ../../docs_src/dependencies/tutorial008_an.py!} ``` //// @@ -136,7 +136,7 @@ Utilize a versão com `Annotated` se possível. /// ```python hl_lines="16-17 24-25" -{!> ../../../docs_src/dependencies/tutorial008.py!} +{!> ../../docs_src/dependencies/tutorial008.py!} ``` //// @@ -174,7 +174,7 @@ Mas ela existe para ser utilizada caso você precise. 🤓 //// tab | python 3.9+ ```python hl_lines="18-22 31" -{!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008b_an_py39.py!} ``` //// @@ -182,7 +182,7 @@ Mas ela existe para ser utilizada caso você precise. 🤓 //// tab | python 3.8+ ```python hl_lines="17-21 30" -{!> ../../../docs_src/dependencies/tutorial008b_an.py!} +{!> ../../docs_src/dependencies/tutorial008b_an.py!} ``` //// @@ -196,7 +196,7 @@ Utilize a versão com `Annotated` se possível. /// ```python hl_lines="16-20 29" -{!> ../../../docs_src/dependencies/tutorial008b.py!} +{!> ../../docs_src/dependencies/tutorial008b.py!} ``` //// @@ -210,7 +210,7 @@ Se você capturar uma exceção com `except` em uma dependência que utilize `yi //// tab | Python 3.9+ ```Python hl_lines="15-16" -{!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008c_an_py39.py!} ``` //// @@ -218,7 +218,7 @@ Se você capturar uma exceção com `except` em uma dependência que utilize `yi //// tab | Python 3.8+ ```Python hl_lines="14-15" -{!> ../../../docs_src/dependencies/tutorial008c_an.py!} +{!> ../../docs_src/dependencies/tutorial008c_an.py!} ``` //// @@ -232,7 +232,7 @@ utilize a versão com `Annotated` se possível. /// ```Python hl_lines="13-14" -{!> ../../../docs_src/dependencies/tutorial008c.py!} +{!> ../../docs_src/dependencies/tutorial008c.py!} ``` //// @@ -248,7 +248,7 @@ Você pode relançar a mesma exceção utilizando `raise`: //// tab | Python 3.9+ ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial008d_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008d_an_py39.py!} ``` //// @@ -256,7 +256,7 @@ Você pode relançar a mesma exceção utilizando `raise`: //// tab | Python 3.8+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial008d_an.py!} +{!> ../../docs_src/dependencies/tutorial008d_an.py!} ``` //// @@ -270,7 +270,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="15" -{!> ../../../docs_src/dependencies/tutorial008d.py!} +{!> ../../docs_src/dependencies/tutorial008d.py!} ``` //// @@ -403,7 +403,7 @@ Em python, você pode criar Gerenciadores de Contexto ao ../../../docs_src/dependencies/tutorial012_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} ``` //// @@ -17,7 +17,7 @@ Nesse caso, elas serão aplicadas a todas as *operações de rota* da aplicaçã //// tab | Python 3.8+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial012_an.py!} +{!> ../../docs_src/dependencies/tutorial012_an.py!} ``` //// @@ -31,7 +31,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="15" -{!> ../../../docs_src/dependencies/tutorial012.py!} +{!> ../../docs_src/dependencies/tutorial012.py!} ``` //// diff --git a/docs/pt/docs/tutorial/dependencies/index.md b/docs/pt/docs/tutorial/dependencies/index.md index f7b32966c..2a63e7ab8 100644 --- a/docs/pt/docs/tutorial/dependencies/index.md +++ b/docs/pt/docs/tutorial/dependencies/index.md @@ -34,7 +34,7 @@ Ela é apenas uma função que pode receber os mesmos parâmetros de uma *funç //// tab | Python 3.10+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -42,7 +42,7 @@ Ela é apenas uma função que pode receber os mesmos parâmetros de uma *funç //// tab | Python 3.9+ ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -50,7 +50,7 @@ Ela é apenas uma função que pode receber os mesmos parâmetros de uma *funç //// tab | Python 3.8+ ```Python hl_lines="9-12" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -64,7 +64,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -78,7 +78,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -116,7 +116,7 @@ Certifique-se de [Atualizar a versão do FastAPI](../../deployment/versions.md#a //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -124,7 +124,7 @@ Certifique-se de [Atualizar a versão do FastAPI](../../deployment/versions.md#a //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -132,7 +132,7 @@ Certifique-se de [Atualizar a versão do FastAPI](../../deployment/versions.md#a //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -146,7 +146,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="1" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -160,7 +160,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -172,7 +172,7 @@ Da mesma forma que você utiliza `Body`, `Query`, etc. Como parâmetros de sua * //// tab | Python 3.10+ ```Python hl_lines="13 18" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -180,7 +180,7 @@ Da mesma forma que você utiliza `Body`, `Query`, etc. Como parâmetros de sua * //// tab | Python 3.9+ ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -188,7 +188,7 @@ Da mesma forma que você utiliza `Body`, `Query`, etc. Como parâmetros de sua * //// tab | Python 3.8+ ```Python hl_lines="16 21" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -202,7 +202,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -216,7 +216,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -279,7 +279,7 @@ Mas como estamos utilizando `Annotated`, podemos guardar esse valor `Annotated` //// tab | Python 3.10+ ```Python hl_lines="12 16 21" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} ``` //// @@ -287,7 +287,7 @@ Mas como estamos utilizando `Annotated`, podemos guardar esse valor `Annotated` //// tab | Python 3.9+ ```Python hl_lines="14 18 23" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} ``` //// @@ -295,7 +295,7 @@ Mas como estamos utilizando `Annotated`, podemos guardar esse valor `Annotated` //// tab | Python 3.8+ ```Python hl_lines="15 19 24" -{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an.py!} ``` //// diff --git a/docs/pt/docs/tutorial/dependencies/sub-dependencies.md b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md index 279bf3339..b890fe793 100644 --- a/docs/pt/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md @@ -13,7 +13,7 @@ Você pode criar uma primeira dependência (injetável) dessa forma: //// tab | Python 3.10+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -21,7 +21,7 @@ Você pode criar uma primeira dependência (injetável) dessa forma: //// tab | Python 3.9+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -29,7 +29,7 @@ Você pode criar uma primeira dependência (injetável) dessa forma: //// tab | Python 3.8+ ```Python hl_lines="9-10" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -43,7 +43,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -57,7 +57,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -73,7 +73,7 @@ Então, você pode criar uma outra função para uma dependência (um "injetáve //// tab | Python 3.10+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -81,7 +81,7 @@ Então, você pode criar uma outra função para uma dependência (um "injetáve //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -89,7 +89,7 @@ Então, você pode criar uma outra função para uma dependência (um "injetáve //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -103,7 +103,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -117,7 +117,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -136,7 +136,7 @@ Então podemos utilizar a dependência com: //// tab | Python 3.10+ ```Python hl_lines="23" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -144,7 +144,7 @@ Então podemos utilizar a dependência com: //// tab | Python 3.9+ ```Python hl_lines="23" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -152,7 +152,7 @@ Então podemos utilizar a dependência com: //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -166,7 +166,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -180,7 +180,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="22" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// diff --git a/docs/pt/docs/tutorial/encoder.md b/docs/pt/docs/tutorial/encoder.md index c104098ee..c8ce77e74 100644 --- a/docs/pt/docs/tutorial/encoder.md +++ b/docs/pt/docs/tutorial/encoder.md @@ -23,7 +23,7 @@ A função recebe um objeto, como um modelo Pydantic e retorna uma versão compa //// tab | Python 3.10+ ```Python hl_lines="4 21" -{!> ../../../docs_src/encoder/tutorial001_py310.py!} +{!> ../../docs_src/encoder/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ A função recebe um objeto, como um modelo Pydantic e retorna uma versão compa //// tab | Python 3.8+ ```Python hl_lines="5 22" -{!> ../../../docs_src/encoder/tutorial001.py!} +{!> ../../docs_src/encoder/tutorial001.py!} ``` //// diff --git a/docs/pt/docs/tutorial/extra-data-types.md b/docs/pt/docs/tutorial/extra-data-types.md index 5d50d8942..78f7ac694 100644 --- a/docs/pt/docs/tutorial/extra-data-types.md +++ b/docs/pt/docs/tutorial/extra-data-types.md @@ -56,11 +56,11 @@ Aqui estão alguns dos tipos de dados adicionais que você pode usar: Aqui está um exemplo de *operação de rota* com parâmetros utilizando-se de alguns dos tipos acima. ```Python hl_lines="1 3 12-16" -{!../../../docs_src/extra_data_types/tutorial001.py!} +{!../../docs_src/extra_data_types/tutorial001.py!} ``` Note que os parâmetros dentro da função tem seu tipo de dados natural, e você pode, por exemplo, realizar manipulações normais de data, como: ```Python hl_lines="18-19" -{!../../../docs_src/extra_data_types/tutorial001.py!} +{!../../docs_src/extra_data_types/tutorial001.py!} ``` diff --git a/docs/pt/docs/tutorial/extra-models.md b/docs/pt/docs/tutorial/extra-models.md index 564aeadca..03227f2bb 100644 --- a/docs/pt/docs/tutorial/extra-models.md +++ b/docs/pt/docs/tutorial/extra-models.md @@ -23,7 +23,7 @@ Aqui está uma ideia geral de como os modelos poderiam parecer com seus campos d //// tab | Python 3.8 and above ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../../docs_src/extra_models/tutorial001.py!} +{!> ../../docs_src/extra_models/tutorial001.py!} ``` //// @@ -31,7 +31,7 @@ Aqui está uma ideia geral de como os modelos poderiam parecer com seus campos d //// tab | Python 3.10 and above ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +{!> ../../docs_src/extra_models/tutorial001_py310.py!} ``` //// @@ -171,7 +171,7 @@ Dessa forma, podemos declarar apenas as diferenças entre os modelos (com `passw //// tab | Python 3.8 and above ```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../../docs_src/extra_models/tutorial002.py!} +{!> ../../docs_src/extra_models/tutorial002.py!} ``` //// @@ -179,7 +179,7 @@ Dessa forma, podemos declarar apenas as diferenças entre os modelos (com `passw //// tab | Python 3.10 and above ```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +{!> ../../docs_src/extra_models/tutorial002_py310.py!} ``` //// @@ -201,7 +201,7 @@ Ao definir um ../../../docs_src/extra_models/tutorial003.py!} +{!> ../../docs_src/extra_models/tutorial003.py!} ``` //// @@ -209,7 +209,7 @@ Ao definir um ../../../docs_src/extra_models/tutorial003_py310.py!} +{!> ../../docs_src/extra_models/tutorial003_py310.py!} ``` //// @@ -237,7 +237,7 @@ Para isso, use o padrão Python `typing.List` (ou simplesmente `list` no Python //// tab | Python 3.8 and above ```Python hl_lines="1 20" -{!> ../../../docs_src/extra_models/tutorial004.py!} +{!> ../../docs_src/extra_models/tutorial004.py!} ``` //// @@ -245,7 +245,7 @@ Para isso, use o padrão Python `typing.List` (ou simplesmente `list` no Python //// tab | Python 3.9 and above ```Python hl_lines="18" -{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +{!> ../../docs_src/extra_models/tutorial004_py39.py!} ``` //// @@ -261,7 +261,7 @@ Neste caso, você pode usar `typing.Dict` (ou simplesmente dict no Python 3.9 e //// tab | Python 3.8 and above ```Python hl_lines="1 8" -{!> ../../../docs_src/extra_models/tutorial005.py!} +{!> ../../docs_src/extra_models/tutorial005.py!} ``` //// @@ -269,7 +269,7 @@ Neste caso, você pode usar `typing.Dict` (ou simplesmente dict no Python 3.9 e //// tab | Python 3.9 and above ```Python hl_lines="6" -{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +{!> ../../docs_src/extra_models/tutorial005_py39.py!} ``` //// diff --git a/docs/pt/docs/tutorial/first-steps.md b/docs/pt/docs/tutorial/first-steps.md index 4c2a8a8e3..4990b5984 100644 --- a/docs/pt/docs/tutorial/first-steps.md +++ b/docs/pt/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ O arquivo FastAPI mais simples pode se parecer com: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Copie o conteúdo para um arquivo `main.py`. @@ -134,7 +134,7 @@ Você também pode usá-lo para gerar código automaticamente para clientes que ### Passo 1: importe `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` é uma classe Python que fornece todas as funcionalidades para sua API. @@ -150,7 +150,7 @@ Você pode usar todas as funcionalidades do ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ Primeiro importe `Header`: //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -31,7 +31,7 @@ O primeiro valor é o valor padrão, você pode passar todas as validações adi //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -39,7 +39,7 @@ O primeiro valor é o valor padrão, você pode passar todas as validações adi //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -77,7 +77,7 @@ Se por algum motivo você precisar desabilitar a conversão automática de subli //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/header_params/tutorial002_py310.py!} +{!> ../../docs_src/header_params/tutorial002_py310.py!} ``` //// @@ -85,7 +85,7 @@ Se por algum motivo você precisar desabilitar a conversão automática de subli //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial002.py!} +{!> ../../docs_src/header_params/tutorial002.py!} ``` //// @@ -109,7 +109,7 @@ Por exemplo, para declarar um cabeçalho de `X-Token` que pode aparecer mais de //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial003_py310.py!} +{!> ../../docs_src/header_params/tutorial003_py310.py!} ``` //// @@ -117,7 +117,7 @@ Por exemplo, para declarar um cabeçalho de `X-Token` que pode aparecer mais de //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_py39.py!} +{!> ../../docs_src/header_params/tutorial003_py39.py!} ``` //// @@ -125,7 +125,7 @@ Por exemplo, para declarar um cabeçalho de `X-Token` que pode aparecer mais de //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003.py!} +{!> ../../docs_src/header_params/tutorial003.py!} ``` //// diff --git a/docs/pt/docs/tutorial/middleware.md b/docs/pt/docs/tutorial/middleware.md index 1760246ee..35c61d5fc 100644 --- a/docs/pt/docs/tutorial/middleware.md +++ b/docs/pt/docs/tutorial/middleware.md @@ -32,7 +32,7 @@ A função middleware recebe: * Você pode então modificar ainda mais o `response` antes de retorná-lo. ```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` /// tip | "Dica" @@ -60,7 +60,7 @@ E também depois que a `response` é gerada, antes de retorná-la. Por exemplo, você pode adicionar um cabeçalho personalizado `X-Process-Time` contendo o tempo em segundos que levou para processar a solicitação e gerar uma resposta: ```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} +{!../../docs_src/middleware/tutorial001.py!} ``` ## Outros middlewares diff --git a/docs/pt/docs/tutorial/path-operation-configuration.md b/docs/pt/docs/tutorial/path-operation-configuration.md index c57813780..48753d725 100644 --- a/docs/pt/docs/tutorial/path-operation-configuration.md +++ b/docs/pt/docs/tutorial/path-operation-configuration.md @@ -19,7 +19,7 @@ Mas se você não se lembrar o que cada código numérico significa, pode usar a //// tab | Python 3.8 and above ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001.py!} ``` //// @@ -27,7 +27,7 @@ Mas se você não se lembrar o que cada código numérico significa, pode usar a //// tab | Python 3.9 and above ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} ``` //// @@ -35,7 +35,7 @@ Mas se você não se lembrar o que cada código numérico significa, pode usar a //// tab | Python 3.10 and above ```Python hl_lines="1 15" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} ``` //// @@ -57,7 +57,7 @@ Você pode adicionar tags para sua *operação de rota*, passe o parâmetro `tag //// tab | Python 3.8 and above ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002.py!} ``` //// @@ -65,7 +65,7 @@ Você pode adicionar tags para sua *operação de rota*, passe o parâmetro `tag //// tab | Python 3.9 and above ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} ``` //// @@ -73,7 +73,7 @@ Você pode adicionar tags para sua *operação de rota*, passe o parâmetro `tag //// tab | Python 3.10 and above ```Python hl_lines="15 20 25" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} ``` //// @@ -91,7 +91,7 @@ Nestes casos, pode fazer sentido armazenar as tags em um `Enum`. **FastAPI** suporta isso da mesma maneira que com strings simples: ```Python hl_lines="1 8-10 13 18" -{!../../../docs_src/path_operation_configuration/tutorial002b.py!} +{!../../docs_src/path_operation_configuration/tutorial002b.py!} ``` ## Resumo e descrição @@ -101,7 +101,7 @@ Você pode adicionar um `summary` e uma `description`: //// tab | Python 3.8 and above ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003.py!} ``` //// @@ -109,7 +109,7 @@ Você pode adicionar um `summary` e uma `description`: //// tab | Python 3.9 and above ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} ``` //// @@ -117,7 +117,7 @@ Você pode adicionar um `summary` e uma `description`: //// tab | Python 3.10 and above ```Python hl_lines="18-19" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} ``` //// @@ -131,7 +131,7 @@ Você pode escrever ../../../docs_src/path_operation_configuration/tutorial004.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004.py!} ``` //// @@ -139,7 +139,7 @@ Você pode escrever ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} ``` //// @@ -147,7 +147,7 @@ Você pode escrever ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} ``` //// @@ -164,7 +164,7 @@ Você pode especificar a descrição da resposta com o parâmetro `response_desc //// tab | Python 3.8 and above ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005.py!} ``` //// @@ -172,7 +172,7 @@ Você pode especificar a descrição da resposta com o parâmetro `response_desc //// tab | Python 3.9 and above ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} ``` //// @@ -180,7 +180,7 @@ Você pode especificar a descrição da resposta com o parâmetro `response_desc //// tab | Python 3.10 and above ```Python hl_lines="19" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} ``` //// @@ -206,7 +206,7 @@ Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma Se você precisar marcar uma *operação de rota* como descontinuada, mas sem removê-la, passe o parâmetro `deprecated`: ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` Ela será claramente marcada como descontinuada nas documentações interativas: diff --git a/docs/pt/docs/tutorial/path-params-numeric-validations.md b/docs/pt/docs/tutorial/path-params-numeric-validations.md index 08ed03f75..28c55482f 100644 --- a/docs/pt/docs/tutorial/path-params-numeric-validations.md +++ b/docs/pt/docs/tutorial/path-params-numeric-validations.md @@ -9,7 +9,7 @@ Primeiro, importe `Path` de `fastapi`: //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ Primeiro, importe `Path` de `fastapi`: //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -31,7 +31,7 @@ Por exemplo para declarar um valor de metadado `title` para o parâmetro de rota //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -39,7 +39,7 @@ Por exemplo para declarar um valor de metadado `title` para o parâmetro de rota //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -71,7 +71,7 @@ Isso não faz diferença para o **FastAPI**. Ele vai detectar os parâmetros pel Então, você pode declarar sua função assim: ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` ## Ordene os parâmetros de a acordo com sua necessidade, truques @@ -83,7 +83,7 @@ Passe `*`, como o primeiro parâmetro da função. O Python não vai fazer nada com esse `*`, mas ele vai saber que a partir dali os parâmetros seguintes deverão ser chamados argumentos nomeados (pares chave-valor), também conhecidos como kwargs. Mesmo que eles não possuam um valor padrão. ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ## Validações numéricas: maior que ou igual @@ -93,7 +93,7 @@ Com `Query` e `Path` (e outras que você verá mais tarde) você pode declarar r Aqui, com `ge=1`, `item_id` precisará ser um número inteiro maior que ("`g`reater than") ou igual ("`e`qual") a 1. ```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` ## Validações numéricas: maior que e menor que ou igual @@ -104,7 +104,7 @@ O mesmo se aplica para: * `le`: menor que ou igual (`l`ess than or `e`qual) ```Python hl_lines="9" -{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` ## Validações numéricas: valores do tipo float, maior que e menor que @@ -118,7 +118,7 @@ Assim, `0.5` seria um valor válido. Mas `0.0` ou `0` não seria. E o mesmo para lt. ```Python hl_lines="11" -{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` ## Recapitulando diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md index fb872e4f5..a68354a1b 100644 --- a/docs/pt/docs/tutorial/path-params.md +++ b/docs/pt/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ Você pode declarar os "parâmetros" ou "variáveis" com a mesma sintaxe utilizada pelo formato de strings do Python: ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` O valor do parâmetro que foi passado à `item_id` será passado para a sua função como o argumento `item_id`. @@ -19,7 +19,7 @@ Então, se você rodar este exemplo e for até expressão regular que combine com um padrão esperado pelo parâmetro: ```Python hl_lines="11" -{!../../../docs_src/query_params_str_validations/tutorial004.py!} +{!../../docs_src/query_params_str_validations/tutorial004.py!} ``` Essa expressão regular específica verifica se o valor recebido no parâmetro: @@ -115,7 +115,7 @@ Da mesma maneira que você utiliza `None` como o primeiro argumento para ser uti Vamos dizer que você queira que o parâmetro de consulta `q` tenha um `min_length` de `3`, e um valor padrão de `"fixedquery"`, então declararíamos assim: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} +{!../../docs_src/query_params_str_validations/tutorial005.py!} ``` /// note | "Observação" @@ -147,7 +147,7 @@ q: Union[str, None] = Query(default=None, min_length=3) Então, quando você precisa declarar um parâmetro obrigatório utilizando o `Query`, você pode utilizar `...` como o primeiro argumento: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} +{!../../docs_src/query_params_str_validations/tutorial006.py!} ``` /// info | "Informação" @@ -165,7 +165,7 @@ Quando você declara explicitamente um parâmetro com `Query` você pode declar Por exemplo, para declarar que o parâmetro `q` pode aparecer diversas vezes na URL, você escreveria: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial011.py!} +{!../../docs_src/query_params_str_validations/tutorial011.py!} ``` Então, com uma URL assim: @@ -202,7 +202,7 @@ A documentação interativa da API irá atualizar de acordo, permitindo múltipl E você também pode definir uma lista (`list`) de valores padrão caso nenhum seja informado: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial012.py!} +{!../../docs_src/query_params_str_validations/tutorial012.py!} ``` Se você for até: @@ -227,7 +227,7 @@ O valor padrão de `q` será: `["foo", "bar"]` e sua resposta será: Você também pode utilizar o tipo `list` diretamente em vez de `List[str]`: ```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} +{!../../docs_src/query_params_str_validations/tutorial013.py!} ``` /// note | "Observação" @@ -255,13 +255,13 @@ Algumas delas não exibem todas as informações extras que declaramos, ainda qu Você pode adicionar um `title`: ```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial007.py!} +{!../../docs_src/query_params_str_validations/tutorial007.py!} ``` E uma `description`: ```Python hl_lines="13" -{!../../../docs_src/query_params_str_validations/tutorial008.py!} +{!../../docs_src/query_params_str_validations/tutorial008.py!} ``` ## Apelidos (alias) de parâmetros @@ -283,7 +283,7 @@ Mas ainda você precisa que o nome seja exatamente `item-query`... Então você pode declarar um `alias`, e esse apelido (alias) que será utilizado para encontrar o valor do parâmetro: ```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial009.py!} +{!../../docs_src/query_params_str_validations/tutorial009.py!} ``` ## Parâmetros descontinuados @@ -295,7 +295,7 @@ Você tem que deixá-lo ativo por um tempo, já que existem clientes o utilizand Então você passa o parâmetro `deprecated=True` para `Query`: ```Python hl_lines="18" -{!../../../docs_src/query_params_str_validations/tutorial010.py!} +{!../../docs_src/query_params_str_validations/tutorial010.py!} ``` Na documentação aparecerá assim: diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md index 78d54f09b..6e6699cd5 100644 --- a/docs/pt/docs/tutorial/query-params.md +++ b/docs/pt/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ Quando você declara outros parâmetros na função que não fazem parte dos parâmetros da rota, esses parâmetros são automaticamente interpretados como parâmetros de "consulta". ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` A consulta é o conjunto de pares chave-valor que vai depois de `?` na URL, separado pelo caractere `&`. @@ -66,7 +66,7 @@ Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial002_py310.py!} +{!> ../../docs_src/query_params/tutorial002_py310.py!} ``` //// @@ -74,7 +74,7 @@ Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial002.py!} +{!> ../../docs_src/query_params/tutorial002.py!} ``` //// @@ -94,7 +94,7 @@ Você também pode declarar tipos `bool`, e eles serão convertidos: //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial003_py310.py!} +{!> ../../docs_src/query_params/tutorial003_py310.py!} ``` //// @@ -102,7 +102,7 @@ Você também pode declarar tipos `bool`, e eles serão convertidos: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial003.py!} +{!> ../../docs_src/query_params/tutorial003.py!} ``` //// @@ -150,7 +150,7 @@ Eles serão detectados pelo nome: //// tab | Python 3.10+ ```Python hl_lines="6 8" -{!> ../../../docs_src/query_params/tutorial004_py310.py!} +{!> ../../docs_src/query_params/tutorial004_py310.py!} ``` //// @@ -158,7 +158,7 @@ Eles serão detectados pelo nome: //// tab | Python 3.8+ ```Python hl_lines="8 10" -{!> ../../../docs_src/query_params/tutorial004.py!} +{!> ../../docs_src/query_params/tutorial004.py!} ``` //// @@ -172,7 +172,7 @@ Caso você não queira adicionar um valor específico mas queira apenas torná-l Porém, quando você quiser fazer com que o parâmetro de consulta seja obrigatório, você pode simplesmente não declarar nenhum valor como padrão. ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` Aqui o parâmetro de consulta `needy` é um valor obrigatório, do tipo `str`. @@ -220,7 +220,7 @@ E claro, você pode definir alguns parâmetros como obrigatórios, alguns possui //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params/tutorial006_py310.py!} +{!> ../../docs_src/query_params/tutorial006_py310.py!} ``` //// @@ -228,7 +228,7 @@ E claro, você pode definir alguns parâmetros como obrigatórios, alguns possui //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params/tutorial006.py!} +{!> ../../docs_src/query_params/tutorial006.py!} ``` //// diff --git a/docs/pt/docs/tutorial/request-form-models.md b/docs/pt/docs/tutorial/request-form-models.md index a9db18e9d..837e24c34 100644 --- a/docs/pt/docs/tutorial/request-form-models.md +++ b/docs/pt/docs/tutorial/request-form-models.md @@ -27,7 +27,7 @@ Você precisa apenas declarar um **modelo Pydantic** com os campos que deseja re //// tab | Python 3.9+ ```Python hl_lines="9-11 15" -{!> ../../../docs_src/request_form_models/tutorial001_an_py39.py!} +{!> ../../docs_src/request_form_models/tutorial001_an_py39.py!} ``` //// @@ -35,7 +35,7 @@ Você precisa apenas declarar um **modelo Pydantic** com os campos que deseja re //// tab | Python 3.8+ ```Python hl_lines="8-10 14" -{!> ../../../docs_src/request_form_models/tutorial001_an.py!} +{!> ../../docs_src/request_form_models/tutorial001_an.py!} ``` //// @@ -49,7 +49,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="7-9 13" -{!> ../../../docs_src/request_form_models/tutorial001.py!} +{!> ../../docs_src/request_form_models/tutorial001.py!} ``` //// @@ -79,7 +79,7 @@ Você pode utilizar a configuração de modelo do Pydantic para `proibir` qualqu //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/request_form_models/tutorial002_an_py39.py!} +{!> ../../docs_src/request_form_models/tutorial002_an_py39.py!} ``` //// @@ -87,7 +87,7 @@ Você pode utilizar a configuração de modelo do Pydantic para `proibir` qualqu //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/request_form_models/tutorial002_an.py!} +{!> ../../docs_src/request_form_models/tutorial002_an.py!} ``` //// @@ -101,7 +101,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="10" -{!> ../../../docs_src/request_form_models/tutorial002.py!} +{!> ../../docs_src/request_form_models/tutorial002.py!} ``` //// diff --git a/docs/pt/docs/tutorial/request-forms-and-files.md b/docs/pt/docs/tutorial/request-forms-and-files.md index 2cf406386..29488b4f2 100644 --- a/docs/pt/docs/tutorial/request-forms-and-files.md +++ b/docs/pt/docs/tutorial/request-forms-and-files.md @@ -13,7 +13,7 @@ Por exemplo: `pip install python-multipart`. ## Importe `File` e `Form` ```Python hl_lines="1" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` ## Defina parâmetros de `File` e `Form` @@ -21,7 +21,7 @@ Por exemplo: `pip install python-multipart`. Crie parâmetros de arquivo e formulário da mesma forma que você faria para `Body` ou `Query`: ```Python hl_lines="8" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} +{!../../docs_src/request_forms_and_files/tutorial001.py!} ``` Os arquivos e campos de formulário serão carregados como dados de formulário e você receberá os arquivos e campos de formulário. diff --git a/docs/pt/docs/tutorial/request-forms.md b/docs/pt/docs/tutorial/request-forms.md index fc8c7bbad..1e2faf269 100644 --- a/docs/pt/docs/tutorial/request-forms.md +++ b/docs/pt/docs/tutorial/request-forms.md @@ -15,7 +15,7 @@ Ex: `pip install python-multipart`. Importe `Form` de `fastapi`: ```Python hl_lines="1" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` ## Declare parâmetros de `Form` @@ -23,7 +23,7 @@ Importe `Form` de `fastapi`: Crie parâmetros de formulário da mesma forma que você faria para `Body` ou `Query`: ```Python hl_lines="7" -{!../../../docs_src/request_forms/tutorial001.py!} +{!../../docs_src/request_forms/tutorial001.py!} ``` Por exemplo, em uma das maneiras que a especificação OAuth2 pode ser usada (chamada "fluxo de senha"), é necessário enviar um `username` e uma `password` como campos do formulário. diff --git a/docs/pt/docs/tutorial/request_files.md b/docs/pt/docs/tutorial/request_files.md index 60e4ecb26..39bfe284a 100644 --- a/docs/pt/docs/tutorial/request_files.md +++ b/docs/pt/docs/tutorial/request_files.md @@ -19,7 +19,7 @@ Importe `File` e `UploadFile` do `fastapi`: //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -27,7 +27,7 @@ Importe `File` e `UploadFile` do `fastapi`: //// tab | Python 3.8+ ```Python hl_lines="1" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -41,7 +41,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="1" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -53,7 +53,7 @@ Cria os parâmetros do arquivo da mesma forma que você faria para `Body` ou `Fo //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -61,7 +61,7 @@ Cria os parâmetros do arquivo da mesma forma que você faria para `Body` ou `Fo //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -75,7 +75,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="7" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -109,7 +109,7 @@ Defina um parâmetro de arquivo com o tipo `UploadFile` //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -117,7 +117,7 @@ Defina um parâmetro de arquivo com o tipo `UploadFile` //// tab | Python 3.8+ ```Python hl_lines="13" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -131,7 +131,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="12" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -220,7 +220,7 @@ Você pode definir um arquivo como opcional utilizando as anotações de tipo pa //// tab | Python 3.10+ ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} +{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} ``` //// @@ -228,7 +228,7 @@ Você pode definir um arquivo como opcional utilizando as anotações de tipo pa //// tab | Python 3.9+ ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} ``` //// @@ -236,7 +236,7 @@ Você pode definir um arquivo como opcional utilizando as anotações de tipo pa //// tab | Python 3.8+ ```Python hl_lines="10 18" -{!> ../../../docs_src/request_files/tutorial001_02_an.py!} +{!> ../../docs_src/request_files/tutorial001_02_an.py!} ``` //// @@ -250,7 +250,7 @@ Utilize a versão com `Annotated`, se possível /// ```Python hl_lines="7 15" -{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +{!> ../../docs_src/request_files/tutorial001_02_py310.py!} ``` //// @@ -264,7 +264,7 @@ Utilize a versão com `Annotated`, se possível /// ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02.py!} +{!> ../../docs_src/request_files/tutorial001_02.py!} ``` //// @@ -276,7 +276,7 @@ Você também pode utilizar `File()` com `UploadFile`, por exemplo, para definir //// tab | Python 3.9+ ```Python hl_lines="9 15" -{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} ``` //// @@ -284,7 +284,7 @@ Você também pode utilizar `File()` com `UploadFile`, por exemplo, para definir //// tab | Python 3.8+ ```Python hl_lines="8 14" -{!> ../../../docs_src/request_files/tutorial001_03_an.py!} +{!> ../../docs_src/request_files/tutorial001_03_an.py!} ``` //// @@ -298,7 +298,7 @@ Utilize a versão com `Annotated` se possível /// ```Python hl_lines="7 13" -{!> ../../../docs_src/request_files/tutorial001_03.py!} +{!> ../../docs_src/request_files/tutorial001_03.py!} ``` //// @@ -314,7 +314,7 @@ Para usar isso, declare uma lista de `bytes` ou `UploadFile`: //// tab | Python 3.9+ ```Python hl_lines="10 15" -{!> ../../../docs_src/request_files/tutorial002_an_py39.py!} +{!> ../../docs_src/request_files/tutorial002_an_py39.py!} ``` //// @@ -322,7 +322,7 @@ Para usar isso, declare uma lista de `bytes` ou `UploadFile`: //// tab | Python 3.8+ ```Python hl_lines="11 16" -{!> ../../../docs_src/request_files/tutorial002_an.py!} +{!> ../../docs_src/request_files/tutorial002_an.py!} ``` //// @@ -336,7 +336,7 @@ Utilize a versão com `Annotated` se possível /// ```Python hl_lines="8 13" -{!> ../../../docs_src/request_files/tutorial002_py39.py!} +{!> ../../docs_src/request_files/tutorial002_py39.py!} ``` //// @@ -350,7 +350,7 @@ Utilize a versão com `Annotated` se possível /// ```Python hl_lines="10 15" -{!> ../../../docs_src/request_files/tutorial002.py!} +{!> ../../docs_src/request_files/tutorial002.py!} ``` //// @@ -372,7 +372,7 @@ E da mesma forma que antes, você pode utilizar `File()` para definir parâmetro //// tab | Python 3.9+ ```Python hl_lines="11 18-20" -{!> ../../../docs_src/request_files/tutorial003_an_py39.py!} +{!> ../../docs_src/request_files/tutorial003_an_py39.py!} ``` //// @@ -380,7 +380,7 @@ E da mesma forma que antes, você pode utilizar `File()` para definir parâmetro //// tab | Python 3.8+ ```Python hl_lines="12 19-21" -{!> ../../../docs_src/request_files/tutorial003_an.py!} +{!> ../../docs_src/request_files/tutorial003_an.py!} ``` //// @@ -394,7 +394,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="9 16" -{!> ../../../docs_src/request_files/tutorial003_py39.py!} +{!> ../../docs_src/request_files/tutorial003_py39.py!} ``` //// @@ -408,7 +408,7 @@ Utilize a versão com `Annotated` se possível. /// ```Python hl_lines="11 18" -{!> ../../../docs_src/request_files/tutorial003.py!} +{!> ../../docs_src/request_files/tutorial003.py!} ``` //// diff --git a/docs/pt/docs/tutorial/response-status-code.md b/docs/pt/docs/tutorial/response-status-code.md index dc8e12048..bc4a2cd34 100644 --- a/docs/pt/docs/tutorial/response-status-code.md +++ b/docs/pt/docs/tutorial/response-status-code.md @@ -9,7 +9,7 @@ Da mesma forma que você pode especificar um modelo de resposta, você também p * etc. ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` /// note | "Nota" @@ -78,7 +78,7 @@ Para saber mais sobre cada código de status e qual código serve para quê, ver Vamos ver o exemplo anterior novamente: ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` `201` é o código de status para "Criado". @@ -88,7 +88,7 @@ Mas você não precisa memorizar o que cada um desses códigos significa. Você pode usar as variáveis de conveniência de `fastapi.status`. ```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} +{!../../docs_src/response_status_code/tutorial002.py!} ``` Eles são apenas uma conveniência, eles possuem o mesmo número, mas dessa forma você pode usar o autocomplete do editor para encontrá-los: diff --git a/docs/pt/docs/tutorial/schema-extra-example.md b/docs/pt/docs/tutorial/schema-extra-example.md index a291db045..2d78e4ef1 100644 --- a/docs/pt/docs/tutorial/schema-extra-example.md +++ b/docs/pt/docs/tutorial/schema-extra-example.md @@ -9,7 +9,7 @@ Aqui estão várias formas de se fazer isso. Você pode declarar um `example` para um modelo Pydantic usando `Config` e `schema_extra`, conforme descrito em Documentação do Pydantic: Schema customization: ```Python hl_lines="15-23" -{!../../../docs_src/schema_extra_example/tutorial001.py!} +{!../../docs_src/schema_extra_example/tutorial001.py!} ``` Essas informações extras serão adicionadas como se encontram no **JSON Schema** de resposta desse modelo e serão usadas na documentação da API. @@ -29,7 +29,7 @@ Ao usar `Field ()` com modelos Pydantic, você também pode declarar informaçõ Você pode usar isso para adicionar um `example` para cada campo: ```Python hl_lines="4 10-13" -{!../../../docs_src/schema_extra_example/tutorial002.py!} +{!../../docs_src/schema_extra_example/tutorial002.py!} ``` /// warning | "Atenção" @@ -57,7 +57,7 @@ você também pode declarar um dado `example` ou um grupo de `examples` com info Aqui nós passamos um `example` dos dados esperados por `Body()`: ```Python hl_lines="21-26" -{!../../../docs_src/schema_extra_example/tutorial003.py!} +{!../../docs_src/schema_extra_example/tutorial003.py!} ``` ### Exemplo na UI da documentação @@ -80,7 +80,7 @@ Cada `dict` de exemplo específico em `examples` pode conter: * `externalValue`: alternativa ao `value`, uma URL apontando para o exemplo. Embora isso possa não ser suportado por tantas ferramentas quanto `value`. ```Python hl_lines="22-48" -{!../../../docs_src/schema_extra_example/tutorial004.py!} +{!../../docs_src/schema_extra_example/tutorial004.py!} ``` ### Exemplos na UI da documentação diff --git a/docs/pt/docs/tutorial/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md index 007fefcb9..9fb94fe67 100644 --- a/docs/pt/docs/tutorial/security/first-steps.md +++ b/docs/pt/docs/tutorial/security/first-steps.md @@ -20,7 +20,7 @@ Vamos primeiro usar o código e ver como funciona, e depois voltaremos para ente Copie o exemplo em um arquivo `main.py`: ```Python -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` ## Execute-o @@ -136,7 +136,7 @@ Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um Quando nós criamos uma instância da classe `OAuth2PasswordBearer`, nós passamos pelo parâmetro `tokenUrl` Esse parâmetro contém a URL que o client (o frontend rodando no browser do usuário) vai usar para mandar o `username` e `senha` para obter um token. ```Python hl_lines="6" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` /// tip | "Dica" @@ -180,7 +180,7 @@ Então, pode ser usado com `Depends`. Agora você pode passar aquele `oauth2_scheme` em uma dependência com `Depends`. ```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} +{!../../docs_src/security/tutorial001.py!} ``` Esse dependência vai fornecer uma `str` que é atribuído ao parâmetro `token da *função do path operation* diff --git a/docs/pt/docs/tutorial/static-files.md b/docs/pt/docs/tutorial/static-files.md index efaf07dfb..901fca1d2 100644 --- a/docs/pt/docs/tutorial/static-files.md +++ b/docs/pt/docs/tutorial/static-files.md @@ -8,7 +8,7 @@ Você pode servir arquivos estáticos automaticamente de um diretório usando `S * "Monte" uma instância de `StaticFiles()` em um caminho específico. ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` /// note | "Detalhes técnicos" diff --git a/docs/pt/docs/tutorial/testing.md b/docs/pt/docs/tutorial/testing.md index f734a7d9a..4e28a43c0 100644 --- a/docs/pt/docs/tutorial/testing.md +++ b/docs/pt/docs/tutorial/testing.md @@ -31,7 +31,7 @@ Use o objeto `TestClient` da mesma forma que você faz com `httpx`. Escreva instruções `assert` simples com as expressões Python padrão que você precisa verificar (novamente, `pytest` padrão). ```Python hl_lines="2 12 15-18" -{!../../../docs_src/app_testing/tutorial001.py!} +{!../../docs_src/app_testing/tutorial001.py!} ``` /// tip | "Dica" @@ -79,7 +79,7 @@ No arquivo `main.py` você tem seu aplicativo **FastAPI**: ```Python -{!../../../docs_src/app_testing/main.py!} +{!../../docs_src/app_testing/main.py!} ``` ### Arquivo de teste @@ -97,7 +97,7 @@ Então você poderia ter um arquivo `test_main.py` com seus testes. Ele poderia Como esse arquivo está no mesmo pacote, você pode usar importações relativas para importar o objeto `app` do módulo `main` (`main.py`): ```Python hl_lines="3" -{!../../../docs_src/app_testing/test_main.py!} +{!../../docs_src/app_testing/test_main.py!} ``` ...e ter o código para os testes como antes. @@ -129,7 +129,7 @@ Ambas as *operações de rotas* requerem um cabeçalho `X-Token`. //// tab | Python 3.10+ ```Python -{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} ``` //// @@ -137,7 +137,7 @@ Ambas as *operações de rotas* requerem um cabeçalho `X-Token`. //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} ``` //// @@ -145,7 +145,7 @@ Ambas as *operações de rotas* requerem um cabeçalho `X-Token`. //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/app_testing/app_b_an/main.py!} +{!> ../../docs_src/app_testing/app_b_an/main.py!} ``` //// @@ -159,7 +159,7 @@ Prefira usar a versão `Annotated` se possível. /// ```Python -{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_py310/main.py!} ``` //// @@ -173,7 +173,7 @@ Prefira usar a versão `Annotated` se possível. /// ```Python -{!> ../../../docs_src/app_testing/app_b/main.py!} +{!> ../../docs_src/app_testing/app_b/main.py!} ``` //// @@ -183,7 +183,7 @@ Prefira usar a versão `Annotated` se possível. Você pode então atualizar `test_main.py` com os testes estendidos: ```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} +{!> ../../docs_src/app_testing/app_b/test_main.py!} ``` Sempre que você precisar que o cliente passe informações na requisição e não souber como, você pode pesquisar (no Google) como fazer isso no `httpx`, ou até mesmo como fazer isso com `requests`, já que o design do HTTPX é baseado no design do Requests. diff --git a/docs/ru/docs/python-types.md b/docs/ru/docs/python-types.md index c052bc675..e5905304a 100644 --- a/docs/ru/docs/python-types.md +++ b/docs/ru/docs/python-types.md @@ -23,7 +23,7 @@ Python имеет поддержку необязательных аннотац Давайте начнем с простого примера: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Вызов этой программы выводит: @@ -39,7 +39,7 @@ John Doe * Соединяет их через пробел. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Отредактируем пример @@ -83,7 +83,7 @@ John Doe Это аннотации типов: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` Это не то же самое, что объявление значений по умолчанию, например: @@ -113,7 +113,7 @@ John Doe Проверьте эту функцию, она уже имеет аннотации типов: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Поскольку редактор знает типы переменных, вы получаете не только дополнение, но и проверки ошибок: @@ -123,7 +123,7 @@ John Doe Теперь вы знаете, что вам нужно исправить, преобразовав `age` в строку с `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Объявление типов @@ -144,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Generic-типы с параметрами типов @@ -162,7 +162,7 @@ John Doe Импортируйте `List` из `typing` (с заглавной `L`): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` Объявите переменную с тем же синтаксисом двоеточия (`:`). @@ -172,7 +172,7 @@ John Doe Поскольку список является типом, содержащим некоторые внутренние типы, вы помещаете их в квадратные скобки: ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` /// tip @@ -200,7 +200,7 @@ John Doe Вы бы сделали то же самое, чтобы объявить `tuple` и `set`: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` Это означает: @@ -217,7 +217,7 @@ John Doe Второй параметр типа предназначен для значений `dict`: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` Это означает: @@ -231,7 +231,7 @@ John Doe Вы также можете использовать `Optional`, чтобы объявить, что переменная имеет тип, например, `str`, но это является «необязательным», что означает, что она также может быть `None`: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Использование `Optional[str]` вместо просто `str` позволит редактору помочь вам в обнаружении ошибок, в которых вы могли бы предположить, что значение всегда является `str`, хотя на самом деле это может быть и `None`. @@ -256,13 +256,13 @@ John Doe Допустим, у вас есть класс `Person` с полем `name`: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Тогда вы можете объявить переменную типа `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` И снова вы получаете полную поддержку редактора: @@ -284,7 +284,7 @@ John Doe Взято из официальной документации Pydantic: ```Python -{!../../../docs_src/python_types/tutorial011.py!} +{!../../docs_src/python_types/tutorial011.py!} ``` /// info diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md index 073276848..0f6ce0eb3 100644 --- a/docs/ru/docs/tutorial/background-tasks.md +++ b/docs/ru/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ Сначала импортируйте `BackgroundTasks`, потом добавьте в функцию параметр с типом `BackgroundTasks`: ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** создаст объект класса `BackgroundTasks` для вас и запишет его в параметр. @@ -34,7 +34,7 @@ Так как операция записи не использует `async` и `await`, мы определим ее как обычную `def`: ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## Добавление фоновой задачи @@ -42,7 +42,7 @@ Внутри функции вызовите метод `.add_task()` у объекта *background tasks* и передайте ему функцию, которую хотите выполнить в фоне: ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` принимает следующие аргументы: @@ -60,7 +60,7 @@ //// tab | Python 3.10+ ```Python hl_lines="11 13 20 23" -{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +{!> ../../docs_src/background_tasks/tutorial002_py310.py!} ``` //// @@ -68,7 +68,7 @@ //// tab | Python 3.8+ ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002.py!} +{!> ../../docs_src/background_tasks/tutorial002.py!} ``` //// diff --git a/docs/ru/docs/tutorial/body-fields.md b/docs/ru/docs/tutorial/body-fields.md index f4db0e9ff..f3b2c6113 100644 --- a/docs/ru/docs/tutorial/body-fields.md +++ b/docs/ru/docs/tutorial/body-fields.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="2" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// @@ -35,7 +35,7 @@ //// tab | Python 3.10+ ```Python hl_lines="9-12" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -43,7 +43,7 @@ //// tab | Python 3.8+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// diff --git a/docs/ru/docs/tutorial/body-multiple-params.md b/docs/ru/docs/tutorial/body-multiple-params.md index 107e6293b..53965f0ec 100644 --- a/docs/ru/docs/tutorial/body-multiple-params.md +++ b/docs/ru/docs/tutorial/body-multiple-params.md @@ -11,7 +11,7 @@ //// tab | Python 3.10+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} ``` //// @@ -19,7 +19,7 @@ //// tab | Python 3.9+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} ``` //// @@ -27,7 +27,7 @@ //// tab | Python 3.8+ ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} ``` //// @@ -41,7 +41,7 @@ /// ```Python hl_lines="17-19" -{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} ``` //// @@ -55,7 +55,7 @@ /// ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +{!> ../../docs_src/body_multiple_params/tutorial001.py!} ``` //// @@ -84,7 +84,7 @@ //// tab | Python 3.10+ ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} ``` //// @@ -92,7 +92,7 @@ //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +{!> ../../docs_src/body_multiple_params/tutorial002.py!} ``` //// @@ -139,7 +139,7 @@ //// tab | Python 3.10+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} ``` //// @@ -147,7 +147,7 @@ //// tab | Python 3.9+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} ``` //// @@ -155,7 +155,7 @@ //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} ``` //// @@ -169,7 +169,7 @@ /// ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} ``` //// @@ -183,7 +183,7 @@ /// ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +{!> ../../docs_src/body_multiple_params/tutorial003.py!} ``` //// @@ -229,7 +229,7 @@ q: str | None = None //// tab | Python 3.10+ ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} ``` //// @@ -237,7 +237,7 @@ q: str | None = None //// tab | Python 3.9+ ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} ``` //// @@ -245,7 +245,7 @@ q: str | None = None //// tab | Python 3.8+ ```Python hl_lines="28" -{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} ``` //// @@ -259,7 +259,7 @@ q: str | None = None /// ```Python hl_lines="25" -{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` //// @@ -273,7 +273,7 @@ q: str | None = None /// ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +{!> ../../docs_src/body_multiple_params/tutorial004.py!} ``` //// @@ -301,7 +301,7 @@ item: Item = Body(embed=True) //// tab | Python 3.10+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} ``` //// @@ -309,7 +309,7 @@ item: Item = Body(embed=True) //// tab | Python 3.9+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} ``` //// @@ -317,7 +317,7 @@ item: Item = Body(embed=True) //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} ``` //// @@ -331,7 +331,7 @@ item: Item = Body(embed=True) /// ```Python hl_lines="15" -{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} ``` //// @@ -345,7 +345,7 @@ item: Item = Body(embed=True) /// ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +{!> ../../docs_src/body_multiple_params/tutorial005.py!} ``` //// diff --git a/docs/ru/docs/tutorial/body-nested-models.md b/docs/ru/docs/tutorial/body-nested-models.md index ecb8b92a7..780946725 100644 --- a/docs/ru/docs/tutorial/body-nested-models.md +++ b/docs/ru/docs/tutorial/body-nested-models.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial001.py!} +{!> ../../docs_src/body_nested_models/tutorial001.py!} ``` //// @@ -35,7 +35,7 @@ Но в версиях Python до 3.9 (начиная с 3.6) сначала вам необходимо импортировать `List` из стандартного модуля `typing` в Python: ```Python hl_lines="1" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` ### Объявление `list` с указанием типов для вложенных элементов @@ -68,7 +68,7 @@ my_list: List[str] //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} ``` //// @@ -76,7 +76,7 @@ my_list: List[str] //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} ``` //// @@ -84,7 +84,7 @@ my_list: List[str] //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` //// @@ -100,7 +100,7 @@ my_list: List[str] //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} ``` //// @@ -108,7 +108,7 @@ my_list: List[str] //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} ``` //// @@ -116,7 +116,7 @@ my_list: List[str] //// tab | Python 3.8+ ```Python hl_lines="1 14" -{!> ../../../docs_src/body_nested_models/tutorial003.py!} +{!> ../../docs_src/body_nested_models/tutorial003.py!} ``` //// @@ -144,7 +144,7 @@ my_list: List[str] //// tab | Python 3.10+ ```Python hl_lines="7-9" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -152,7 +152,7 @@ my_list: List[str] //// tab | Python 3.9+ ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -160,7 +160,7 @@ my_list: List[str] //// tab | Python 3.8+ ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -172,7 +172,7 @@ my_list: List[str] //// tab | Python 3.10+ ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -180,7 +180,7 @@ my_list: List[str] //// tab | Python 3.9+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -188,7 +188,7 @@ my_list: List[str] //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -227,7 +227,7 @@ my_list: List[str] //// tab | Python 3.10+ ```Python hl_lines="2 8" -{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} ``` //// @@ -235,7 +235,7 @@ my_list: List[str] //// tab | Python 3.9+ ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} ``` //// @@ -243,7 +243,7 @@ my_list: List[str] //// tab | Python 3.8+ ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005.py!} +{!> ../../docs_src/body_nested_models/tutorial005.py!} ``` //// @@ -257,7 +257,7 @@ my_list: List[str] //// tab | Python 3.10+ ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} ``` //// @@ -265,7 +265,7 @@ my_list: List[str] //// tab | Python 3.9+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} ``` //// @@ -273,7 +273,7 @@ my_list: List[str] //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006.py!} +{!> ../../docs_src/body_nested_models/tutorial006.py!} ``` //// @@ -317,7 +317,7 @@ my_list: List[str] //// tab | Python 3.10+ ```Python hl_lines="7 12 18 21 25" -{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} ``` //// @@ -325,7 +325,7 @@ my_list: List[str] //// tab | Python 3.9+ ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} ``` //// @@ -333,7 +333,7 @@ my_list: List[str] //// tab | Python 3.8+ ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007.py!} +{!> ../../docs_src/body_nested_models/tutorial007.py!} ``` //// @@ -363,7 +363,7 @@ images: list[Image] //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} ``` //// @@ -371,7 +371,7 @@ images: list[Image] //// tab | Python 3.8+ ```Python hl_lines="15" -{!> ../../../docs_src/body_nested_models/tutorial008.py!} +{!> ../../docs_src/body_nested_models/tutorial008.py!} ``` //// @@ -407,7 +407,7 @@ images: list[Image] //// tab | Python 3.9+ ```Python hl_lines="7" -{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} ``` //// @@ -415,7 +415,7 @@ images: list[Image] //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/body_nested_models/tutorial009.py!} +{!> ../../docs_src/body_nested_models/tutorial009.py!} ``` //// diff --git a/docs/ru/docs/tutorial/body-updates.md b/docs/ru/docs/tutorial/body-updates.md index c458329d8..3ecfe52f4 100644 --- a/docs/ru/docs/tutorial/body-updates.md +++ b/docs/ru/docs/tutorial/body-updates.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="28-33" -{!> ../../../docs_src/body_updates/tutorial001_py310.py!} +{!> ../../docs_src/body_updates/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001_py39.py!} +{!> ../../docs_src/body_updates/tutorial001_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.6+ ```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001.py!} +{!> ../../docs_src/body_updates/tutorial001.py!} ``` //// @@ -77,7 +77,7 @@ //// tab | Python 3.10+ ```Python hl_lines="32" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -85,7 +85,7 @@ //// tab | Python 3.9+ ```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -93,7 +93,7 @@ //// tab | Python 3.6+ ```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// @@ -107,7 +107,7 @@ //// tab | Python 3.10+ ```Python hl_lines="33" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -115,7 +115,7 @@ //// tab | Python 3.9+ ```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -123,7 +123,7 @@ //// tab | Python 3.6+ ```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// @@ -146,7 +146,7 @@ //// tab | Python 3.10+ ```Python hl_lines="28-35" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +{!> ../../docs_src/body_updates/tutorial002_py310.py!} ``` //// @@ -154,7 +154,7 @@ //// tab | Python 3.9+ ```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +{!> ../../docs_src/body_updates/tutorial002_py39.py!} ``` //// @@ -162,7 +162,7 @@ //// tab | Python 3.6+ ```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002.py!} +{!> ../../docs_src/body_updates/tutorial002.py!} ``` //// diff --git a/docs/ru/docs/tutorial/body.md b/docs/ru/docs/tutorial/body.md index c3e6326da..91b169d07 100644 --- a/docs/ru/docs/tutorial/body.md +++ b/docs/ru/docs/tutorial/body.md @@ -23,7 +23,7 @@ Первое, что вам необходимо сделать, это импортировать `BaseModel` из пакета `pydantic`: ```Python hl_lines="4" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` ## Создание вашей собственной модели @@ -33,7 +33,7 @@ Используйте аннотации типов Python для всех атрибутов: ```Python hl_lines="7-11" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` Также как и при описании параметров запроса, когда атрибут модели имеет значение по умолчанию, он является необязательным. Иначе он обязателен. Используйте `None`, чтобы сделать его необязательным без использования конкретных значений по умолчанию. @@ -63,7 +63,7 @@ Чтобы добавить параметр к вашему *обработчику*, объявите его также, как вы объявляли параметры пути или параметры запроса: ```Python hl_lines="18" -{!../../../docs_src/body/tutorial001.py!} +{!../../docs_src/body/tutorial001.py!} ``` ...и укажите созданную модель в качестве типа параметра, `Item`. @@ -132,7 +132,7 @@ Внутри функции вам доступны все атрибуты объекта модели напрямую: ```Python hl_lines="21" -{!../../../docs_src/body/tutorial002.py!} +{!../../docs_src/body/tutorial002.py!} ``` ## Тело запроса + параметры пути @@ -142,7 +142,7 @@ **FastAPI** распознает, какие параметры функции соответствуют параметрам пути и должны быть **получены из пути**, а какие параметры функции, объявленные как модели Pydantic, должны быть **получены из тела запроса**. ```Python hl_lines="17-18" -{!../../../docs_src/body/tutorial003.py!} +{!../../docs_src/body/tutorial003.py!} ``` ## Тело запроса + параметры пути + параметры запроса @@ -152,7 +152,7 @@ **FastAPI** распознает каждый из них и возьмет данные из правильного источника. ```Python hl_lines="18" -{!../../../docs_src/body/tutorial004.py!} +{!../../docs_src/body/tutorial004.py!} ``` Параметры функции распознаются следующим образом: diff --git a/docs/ru/docs/tutorial/cookie-params.md b/docs/ru/docs/tutorial/cookie-params.md index e88b9d7ee..2a73a5918 100644 --- a/docs/ru/docs/tutorial/cookie-params.md +++ b/docs/ru/docs/tutorial/cookie-params.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -39,7 +39,7 @@ //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// diff --git a/docs/ru/docs/tutorial/cors.md b/docs/ru/docs/tutorial/cors.md index 852833208..8d415a2c1 100644 --- a/docs/ru/docs/tutorial/cors.md +++ b/docs/ru/docs/tutorial/cors.md @@ -47,7 +47,7 @@ * Отдельных HTTP-заголовков или всех вместе, используя `"*"`. ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` `CORSMiddleware` использует для параметров "запрещающие" значения по умолчанию, поэтому вам нужно явным образом разрешить использование отдельных источников, методов или заголовков, чтобы браузеры могли использовать их в кросс-доменном контексте. diff --git a/docs/ru/docs/tutorial/debugging.md b/docs/ru/docs/tutorial/debugging.md index 685fb7356..606a32bfc 100644 --- a/docs/ru/docs/tutorial/debugging.md +++ b/docs/ru/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ В вашем FastAPI приложении, импортируйте и вызовите `uvicorn` напрямую: ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### Описание `__name__ == "__main__"` diff --git a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md index d0471baca..161101bb3 100644 --- a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.6+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ /// ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -120,7 +120,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -128,7 +128,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.9+ ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -136,7 +136,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ ```Python hl_lines="12-16" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -150,7 +150,7 @@ fluffy = Cat(name="Mr Fluffy") /// ```Python hl_lines="9-13" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -164,7 +164,7 @@ fluffy = Cat(name="Mr Fluffy") /// ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -174,7 +174,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -182,7 +182,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -190,7 +190,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -204,7 +204,7 @@ fluffy = Cat(name="Mr Fluffy") /// ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -218,7 +218,7 @@ fluffy = Cat(name="Mr Fluffy") /// ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -228,7 +228,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -236,7 +236,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -244,7 +244,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -258,7 +258,7 @@ fluffy = Cat(name="Mr Fluffy") /// ```Python hl_lines="6" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -272,7 +272,7 @@ fluffy = Cat(name="Mr Fluffy") /// ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -294,7 +294,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} ``` //// @@ -302,7 +302,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} ``` //// @@ -310,7 +310,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial002_an.py!} +{!> ../../docs_src/dependencies/tutorial002_an.py!} ``` //// @@ -324,7 +324,7 @@ fluffy = Cat(name="Mr Fluffy") /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -338,7 +338,7 @@ fluffy = Cat(name="Mr Fluffy") /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -438,7 +438,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_an_py310.py!} ``` //// @@ -446,7 +446,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial003_an_py39.py!} ``` //// @@ -454,7 +454,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.6+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial003_an.py!} +{!> ../../docs_src/dependencies/tutorial003_an.py!} ``` //// @@ -468,7 +468,7 @@ commons = Depends(CommonQueryParams) /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_py310.py!} ``` //// @@ -482,7 +482,7 @@ commons = Depends(CommonQueryParams) /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003.py!} +{!> ../../docs_src/dependencies/tutorial003.py!} ``` //// @@ -575,7 +575,7 @@ commons: CommonQueryParams = Depends() //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_an_py310.py!} ``` //// @@ -583,7 +583,7 @@ commons: CommonQueryParams = Depends() //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial004_an_py39.py!} ``` //// @@ -591,7 +591,7 @@ commons: CommonQueryParams = Depends() //// tab | Python 3.6+ ```Python hl_lines="20" -{!> ../../../docs_src/dependencies/tutorial004_an.py!} +{!> ../../docs_src/dependencies/tutorial004_an.py!} ``` //// @@ -605,7 +605,7 @@ commons: CommonQueryParams = Depends() /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_py310.py!} ``` //// @@ -619,7 +619,7 @@ commons: CommonQueryParams = Depends() /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004.py!} +{!> ../../docs_src/dependencies/tutorial004.py!} ``` //// diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 11df4b474..305ce46cb 100644 --- a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -75,7 +75,7 @@ //// tab | Python 3.9+ ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ //// tab | Python 3.8+ ```Python hl_lines="7 12" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -97,7 +97,7 @@ /// ```Python hl_lines="6 11" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -109,7 +109,7 @@ //// tab | Python 3.9+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -117,7 +117,7 @@ //// tab | Python 3.8+ ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -131,7 +131,7 @@ /// ```Python hl_lines="8 13" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// @@ -145,7 +145,7 @@ //// tab | Python 3.9+ ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} ``` //// @@ -153,7 +153,7 @@ //// tab | Python 3.8+ ```Python hl_lines="10 15" -{!> ../../../docs_src/dependencies/tutorial006_an.py!} +{!> ../../docs_src/dependencies/tutorial006_an.py!} ``` //// @@ -167,7 +167,7 @@ /// ```Python hl_lines="9 14" -{!> ../../../docs_src/dependencies/tutorial006.py!} +{!> ../../docs_src/dependencies/tutorial006.py!} ``` //// diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md index ece7ef8e3..99a86e999 100644 --- a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md @@ -30,19 +30,19 @@ FastAPI поддерживает зависимости, которые выпо Перед созданием ответа будет выполнен только код до и включая `yield`. ```Python hl_lines="2-4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` Полученное значение и есть то, что будет внедрено в функцию операции пути и другие зависимости: ```Python hl_lines="4" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` Код, следующий за оператором `yield`, выполняется после доставки ответа: ```Python hl_lines="5-6" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` /// tip | "Подсказка" @@ -64,7 +64,7 @@ FastAPI поддерживает зависимости, которые выпо Таким же образом можно использовать `finally`, чтобы убедиться, что обязательные шаги при выходе выполнены, независимо от того, было ли исключение или нет. ```Python hl_lines="3 5" -{!../../../docs_src/dependencies/tutorial007.py!} +{!../../docs_src/dependencies/tutorial007.py!} ``` ## Подзависимости с `yield` @@ -78,7 +78,7 @@ FastAPI поддерживает зависимости, которые выпо //// tab | Python 3.9+ ```Python hl_lines="6 14 22" -{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} ``` //// @@ -86,7 +86,7 @@ FastAPI поддерживает зависимости, которые выпо //// tab | Python 3.6+ ```Python hl_lines="5 13 21" -{!> ../../../docs_src/dependencies/tutorial008_an.py!} +{!> ../../docs_src/dependencies/tutorial008_an.py!} ``` //// @@ -100,7 +100,7 @@ FastAPI поддерживает зависимости, которые выпо /// ```Python hl_lines="4 12 20" -{!> ../../../docs_src/dependencies/tutorial008.py!} +{!> ../../docs_src/dependencies/tutorial008.py!} ``` //// @@ -114,7 +114,7 @@ FastAPI поддерживает зависимости, которые выпо //// tab | Python 3.9+ ```Python hl_lines="18-19 26-27" -{!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} ``` //// @@ -122,7 +122,7 @@ FastAPI поддерживает зависимости, которые выпо //// tab | Python 3.6+ ```Python hl_lines="17-18 25-26" -{!> ../../../docs_src/dependencies/tutorial008_an.py!} +{!> ../../docs_src/dependencies/tutorial008_an.py!} ``` //// @@ -136,7 +136,7 @@ FastAPI поддерживает зависимости, которые выпо /// ```Python hl_lines="16-17 24-25" -{!> ../../../docs_src/dependencies/tutorial008.py!} +{!> ../../docs_src/dependencies/tutorial008.py!} ``` //// @@ -304,7 +304,7 @@ with open("./somefile.txt") as f: `with` или `async with` внутри функции зависимости: ```Python hl_lines="1-9 13" -{!../../../docs_src/dependencies/tutorial010.py!} +{!../../docs_src/dependencies/tutorial010.py!} ``` /// tip | "Подсказка" diff --git a/docs/ru/docs/tutorial/dependencies/global-dependencies.md b/docs/ru/docs/tutorial/dependencies/global-dependencies.md index 9e03e3723..7dbd50ae1 100644 --- a/docs/ru/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/global-dependencies.md @@ -9,7 +9,7 @@ //// tab | Python 3.9+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.8+ ```Python hl_lines="16" -{!> ../../../docs_src/dependencies/tutorial012_an.py!} +{!> ../../docs_src/dependencies/tutorial012_an.py!} ``` //// @@ -31,7 +31,7 @@ /// ```Python hl_lines="15" -{!> ../../../docs_src/dependencies/tutorial012.py!} +{!> ../../docs_src/dependencies/tutorial012.py!} ``` //// diff --git a/docs/ru/docs/tutorial/dependencies/index.md b/docs/ru/docs/tutorial/dependencies/index.md index b244b3fdc..fcd9f46dc 100644 --- a/docs/ru/docs/tutorial/dependencies/index.md +++ b/docs/ru/docs/tutorial/dependencies/index.md @@ -32,7 +32,7 @@ //// tab | Python 3.10+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -40,7 +40,7 @@ //// tab | Python 3.9+ ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -48,7 +48,7 @@ //// tab | Python 3.8+ ```Python hl_lines="9-12" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -62,7 +62,7 @@ /// ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -76,7 +76,7 @@ /// ```Python hl_lines="8-11" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -114,7 +114,7 @@ //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -122,7 +122,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -130,7 +130,7 @@ //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -144,7 +144,7 @@ /// ```Python hl_lines="1" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -158,7 +158,7 @@ /// ```Python hl_lines="3" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -170,7 +170,7 @@ //// tab | Python 3.10+ ```Python hl_lines="13 18" -{!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} ``` //// @@ -178,7 +178,7 @@ //// tab | Python 3.9+ ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} ``` //// @@ -186,7 +186,7 @@ //// tab | Python 3.8+ ```Python hl_lines="16 21" -{!> ../../../docs_src/dependencies/tutorial001_an.py!} +{!> ../../docs_src/dependencies/tutorial001_an.py!} ``` //// @@ -200,7 +200,7 @@ /// ```Python hl_lines="11 16" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -214,7 +214,7 @@ /// ```Python hl_lines="15 20" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -273,7 +273,7 @@ commons: Annotated[dict, Depends(common_parameters)] //// tab | Python 3.10+ ```Python hl_lines="12 16 21" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} ``` //// @@ -281,7 +281,7 @@ commons: Annotated[dict, Depends(common_parameters)] //// tab | Python 3.9+ ```Python hl_lines="14 18 23" -{!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} ``` //// @@ -289,7 +289,7 @@ commons: Annotated[dict, Depends(common_parameters)] //// tab | Python 3.8+ ```Python hl_lines="15 19 24" -{!> ../../../docs_src/dependencies/tutorial001_02_an.py!} +{!> ../../docs_src/dependencies/tutorial001_02_an.py!} ``` //// diff --git a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md index 332470396..ae0fd0824 100644 --- a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md @@ -13,7 +13,7 @@ //// tab | Python 3.10+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -21,7 +21,7 @@ //// tab | Python 3.9+ ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -29,7 +29,7 @@ //// tab | Python 3.6+ ```Python hl_lines="9-10" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -43,7 +43,7 @@ /// ```Python hl_lines="6-7" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -57,7 +57,7 @@ /// ```Python hl_lines="8-9" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -73,7 +73,7 @@ //// tab | Python 3.10+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -81,7 +81,7 @@ //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -89,7 +89,7 @@ //// tab | Python 3.6+ ```Python hl_lines="14" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -103,7 +103,7 @@ /// ```Python hl_lines="11" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -117,7 +117,7 @@ /// ```Python hl_lines="13" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// @@ -136,7 +136,7 @@ //// tab | Python 3.10+ ```Python hl_lines="23" -{!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} ``` //// @@ -144,7 +144,7 @@ //// tab | Python 3.9+ ```Python hl_lines="23" -{!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} ``` //// @@ -152,7 +152,7 @@ //// tab | Python 3.6+ ```Python hl_lines="24" -{!> ../../../docs_src/dependencies/tutorial005_an.py!} +{!> ../../docs_src/dependencies/tutorial005_an.py!} ``` //// @@ -166,7 +166,7 @@ /// ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial005_py310.py!} +{!> ../../docs_src/dependencies/tutorial005_py310.py!} ``` //// @@ -180,7 +180,7 @@ /// ```Python hl_lines="22" -{!> ../../../docs_src/dependencies/tutorial005.py!} +{!> ../../docs_src/dependencies/tutorial005.py!} ``` //// diff --git a/docs/ru/docs/tutorial/encoder.md b/docs/ru/docs/tutorial/encoder.md index 02c3587f3..c9900cb2c 100644 --- a/docs/ru/docs/tutorial/encoder.md +++ b/docs/ru/docs/tutorial/encoder.md @@ -23,7 +23,7 @@ //// tab | Python 3.10+ ```Python hl_lines="4 21" -{!> ../../../docs_src/encoder/tutorial001_py310.py!} +{!> ../../docs_src/encoder/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | Python 3.6+ ```Python hl_lines="5 22" -{!> ../../../docs_src/encoder/tutorial001.py!} +{!> ../../docs_src/encoder/tutorial001.py!} ``` //// diff --git a/docs/ru/docs/tutorial/extra-data-types.md b/docs/ru/docs/tutorial/extra-data-types.md index 2650bb0af..82cb0ff7a 100644 --- a/docs/ru/docs/tutorial/extra-data-types.md +++ b/docs/ru/docs/tutorial/extra-data-types.md @@ -58,7 +58,7 @@ //// tab | Python 3.8 и выше ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// @@ -66,7 +66,7 @@ //// tab | Python 3.10 и выше ```Python hl_lines="1 2 11-15" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -76,7 +76,7 @@ //// tab | Python 3.8 и выше ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// @@ -84,7 +84,7 @@ //// tab | Python 3.10 и выше ```Python hl_lines="17-18" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// diff --git a/docs/ru/docs/tutorial/extra-models.md b/docs/ru/docs/tutorial/extra-models.md index 2aac76aa3..e7ff3f40f 100644 --- a/docs/ru/docs/tutorial/extra-models.md +++ b/docs/ru/docs/tutorial/extra-models.md @@ -23,7 +23,7 @@ //// tab | Python 3.10+ ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../../docs_src/extra_models/tutorial001_py310.py!} +{!> ../../docs_src/extra_models/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | Python 3.8+ ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../../docs_src/extra_models/tutorial001.py!} +{!> ../../docs_src/extra_models/tutorial001.py!} ``` //// @@ -171,7 +171,7 @@ UserInDB( //// tab | Python 3.10+ ```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../../docs_src/extra_models/tutorial002_py310.py!} +{!> ../../docs_src/extra_models/tutorial002_py310.py!} ``` //// @@ -179,7 +179,7 @@ UserInDB( //// tab | Python 3.8+ ```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../../docs_src/extra_models/tutorial002.py!} +{!> ../../docs_src/extra_models/tutorial002.py!} ``` //// @@ -201,7 +201,7 @@ UserInDB( //// tab | Python 3.10+ ```Python hl_lines="1 14-15 18-20 33" -{!> ../../../docs_src/extra_models/tutorial003_py310.py!} +{!> ../../docs_src/extra_models/tutorial003_py310.py!} ``` //// @@ -209,7 +209,7 @@ UserInDB( //// tab | Python 3.8+ ```Python hl_lines="1 14-15 18-20 33" -{!> ../../../docs_src/extra_models/tutorial003.py!} +{!> ../../docs_src/extra_models/tutorial003.py!} ``` //// @@ -237,7 +237,7 @@ some_variable: PlaneItem | CarItem //// tab | Python 3.9+ ```Python hl_lines="18" -{!> ../../../docs_src/extra_models/tutorial004_py39.py!} +{!> ../../docs_src/extra_models/tutorial004_py39.py!} ``` //// @@ -245,7 +245,7 @@ some_variable: PlaneItem | CarItem //// tab | Python 3.8+ ```Python hl_lines="1 20" -{!> ../../../docs_src/extra_models/tutorial004.py!} +{!> ../../docs_src/extra_models/tutorial004.py!} ``` //// @@ -261,7 +261,7 @@ some_variable: PlaneItem | CarItem //// tab | Python 3.9+ ```Python hl_lines="6" -{!> ../../../docs_src/extra_models/tutorial005_py39.py!} +{!> ../../docs_src/extra_models/tutorial005_py39.py!} ``` //// @@ -269,7 +269,7 @@ some_variable: PlaneItem | CarItem //// tab | Python 3.8+ ```Python hl_lines="1 8" -{!> ../../../docs_src/extra_models/tutorial005.py!} +{!> ../../docs_src/extra_models/tutorial005.py!} ``` //// diff --git a/docs/ru/docs/tutorial/first-steps.md b/docs/ru/docs/tutorial/first-steps.md index e60d58823..b1de217cd 100644 --- a/docs/ru/docs/tutorial/first-steps.md +++ b/docs/ru/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ Самый простой FastAPI файл может выглядеть так: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Скопируйте в файл `main.py`. @@ -134,7 +134,7 @@ OpenAPI описывает схему API. Эта схема содержит о ### Шаг 1: импортируйте `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` это класс в Python, который предоставляет всю функциональность для API. @@ -150,7 +150,7 @@ OpenAPI описывает схему API. Эта схема содержит о ### Шаг 2: создайте экземпляр `FastAPI` ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Переменная `app` является экземпляром класса `FastAPI`. @@ -172,7 +172,7 @@ $ uvicorn main:app --reload Если создать такое приложение: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` И поместить его в `main.py`, тогда вызов `uvicorn` будет таким: @@ -251,7 +251,7 @@ https://example.com/items/foo #### Определите *декоратор операции пути (path operation decorator)* ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Декоратор `@app.get("/")` указывает **FastAPI**, что функция, прямо под ним, отвечает за обработку запросов, поступающих по адресу: @@ -307,7 +307,7 @@ https://example.com/items/foo * **функция**: функция ниже "декоратора" (ниже `@app.get("/")`). ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Это обычная Python функция. @@ -321,7 +321,7 @@ https://example.com/items/foo Вы также можете определить ее как обычную функцию вместо `async def`: ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` /// note | "Технические детали" @@ -333,7 +333,7 @@ https://example.com/items/foo ### Шаг 5: верните результат ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Вы можете вернуть `dict`, `list`, отдельные значения `str`, `int` и т.д. diff --git a/docs/ru/docs/tutorial/handling-errors.md b/docs/ru/docs/tutorial/handling-errors.md index 028f3e0d2..e7bfb85aa 100644 --- a/docs/ru/docs/tutorial/handling-errors.md +++ b/docs/ru/docs/tutorial/handling-errors.md @@ -26,7 +26,7 @@ ### Импортируйте `HTTPException` ```Python hl_lines="1" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### Вызовите `HTTPException` в своем коде @@ -42,7 +42,7 @@ В данном примере, когда клиент запрашивает элемент по несуществующему ID, возникает исключение со статус-кодом `404`: ```Python hl_lines="11" -{!../../../docs_src/handling_errors/tutorial001.py!} +{!../../docs_src/handling_errors/tutorial001.py!} ``` ### Возвращаемый ответ @@ -82,7 +82,7 @@ Но в случае, если это необходимо для продвинутого сценария, можно добавить пользовательские заголовки: ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial002.py!} +{!../../docs_src/handling_errors/tutorial002.py!} ``` ## Установка пользовательских обработчиков исключений @@ -96,7 +96,7 @@ Можно добавить собственный обработчик исключений с помощью `@app.exception_handler()`: ```Python hl_lines="5-7 13-18 24" -{!../../../docs_src/handling_errors/tutorial003.py!} +{!../../docs_src/handling_errors/tutorial003.py!} ``` Здесь, если запросить `/unicorns/yolo`, то *операция пути* вызовет `UnicornException`. @@ -136,7 +136,7 @@ Обработчик исключения получит объект `Request` и исключение. ```Python hl_lines="2 14-16" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` Теперь, если перейти к `/items/foo`, то вместо стандартной JSON-ошибки с: @@ -189,7 +189,7 @@ path -> item_id Например, для этих ошибок можно вернуть обычный текстовый ответ вместо JSON: ```Python hl_lines="3-4 9-11 22" -{!../../../docs_src/handling_errors/tutorial004.py!} +{!../../docs_src/handling_errors/tutorial004.py!} ``` /// note | "Технические детали" @@ -207,7 +207,7 @@ path -> item_id Вы можете использовать его при разработке приложения для регистрации тела и его отладки, возврата пользователю и т.д. ```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial005.py!} +{!../../docs_src/handling_errors/tutorial005.py!} ``` Теперь попробуйте отправить недействительный элемент, например: @@ -267,7 +267,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException Если вы хотите использовать исключение вместе с теми же обработчиками исключений по умолчанию из **FastAPI**, вы можете импортировать и повторно использовать обработчики исключений по умолчанию из `fastapi.exception_handlers`: ```Python hl_lines="2-5 15 21" -{!../../../docs_src/handling_errors/tutorial006.py!} +{!../../docs_src/handling_errors/tutorial006.py!} ``` В этом примере вы просто `выводите в терминал` ошибку с очень выразительным сообщением, но идея вам понятна. Вы можете использовать исключение, а затем просто повторно использовать стандартные обработчики исключений. diff --git a/docs/ru/docs/tutorial/header-params.md b/docs/ru/docs/tutorial/header-params.md index 3b5e38328..18e1e60d0 100644 --- a/docs/ru/docs/tutorial/header-params.md +++ b/docs/ru/docs/tutorial/header-params.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +{!> ../../docs_src/header_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +{!> ../../docs_src/header_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001_an.py!} +{!> ../../docs_src/header_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="1" -{!> ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ /// ```Python hl_lines="3" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -67,7 +67,7 @@ //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001_an_py310.py!} +{!> ../../docs_src/header_params/tutorial001_an_py310.py!} ``` //// @@ -75,7 +75,7 @@ //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001_an_py39.py!} +{!> ../../docs_src/header_params/tutorial001_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial001_an.py!} +{!> ../../docs_src/header_params/tutorial001_an.py!} ``` //// @@ -97,7 +97,7 @@ /// ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial001_py310.py!} +{!> ../../docs_src/header_params/tutorial001_py310.py!} ``` //// @@ -111,7 +111,7 @@ /// ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial001.py!} +{!> ../../docs_src/header_params/tutorial001.py!} ``` //// @@ -149,7 +149,7 @@ //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial002_an_py310.py!} +{!> ../../docs_src/header_params/tutorial002_an_py310.py!} ``` //// @@ -157,7 +157,7 @@ //// tab | Python 3.9+ ```Python hl_lines="11" -{!> ../../../docs_src/header_params/tutorial002_an_py39.py!} +{!> ../../docs_src/header_params/tutorial002_an_py39.py!} ``` //// @@ -165,7 +165,7 @@ //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/header_params/tutorial002_an.py!} +{!> ../../docs_src/header_params/tutorial002_an.py!} ``` //// @@ -179,7 +179,7 @@ /// ```Python hl_lines="8" -{!> ../../../docs_src/header_params/tutorial002_py310.py!} +{!> ../../docs_src/header_params/tutorial002_py310.py!} ``` //// @@ -193,7 +193,7 @@ /// ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial002.py!} +{!> ../../docs_src/header_params/tutorial002.py!} ``` //// @@ -217,7 +217,7 @@ //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_an_py310.py!} +{!> ../../docs_src/header_params/tutorial003_an_py310.py!} ``` //// @@ -225,7 +225,7 @@ //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_an_py39.py!} +{!> ../../docs_src/header_params/tutorial003_an_py39.py!} ``` //// @@ -233,7 +233,7 @@ //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/header_params/tutorial003_an.py!} +{!> ../../docs_src/header_params/tutorial003_an.py!} ``` //// @@ -247,7 +247,7 @@ /// ```Python hl_lines="7" -{!> ../../../docs_src/header_params/tutorial003_py310.py!} +{!> ../../docs_src/header_params/tutorial003_py310.py!} ``` //// @@ -261,7 +261,7 @@ /// ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003_py39.py!} +{!> ../../docs_src/header_params/tutorial003_py39.py!} ``` //// @@ -275,7 +275,7 @@ /// ```Python hl_lines="9" -{!> ../../../docs_src/header_params/tutorial003.py!} +{!> ../../docs_src/header_params/tutorial003.py!} ``` //// diff --git a/docs/ru/docs/tutorial/metadata.md b/docs/ru/docs/tutorial/metadata.md index 9799fe538..246458f42 100644 --- a/docs/ru/docs/tutorial/metadata.md +++ b/docs/ru/docs/tutorial/metadata.md @@ -18,7 +18,7 @@ Вы можете задать их следующим образом: ```Python hl_lines="3-16 19-31" -{!../../../docs_src/metadata/tutorial001.py!} +{!../../docs_src/metadata/tutorial001.py!} ``` /// tip | "Подсказка" @@ -52,7 +52,7 @@ Создайте метаданные для ваших тегов и передайте их в параметре `openapi_tags`: ```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` Помните, что вы можете использовать Markdown внутри описания, к примеру "login" будет отображен жирным шрифтом (**login**) и "fancy" будет отображаться курсивом (_fancy_). @@ -67,7 +67,7 @@ Используйте параметр `tags` с вашими *операциями пути* (и `APIRouter`ами), чтобы присвоить им различные теги: ```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} +{!../../docs_src/metadata/tutorial004.py!} ``` /// info | "Дополнительная информация" @@ -97,7 +97,7 @@ К примеру, чтобы задать её отображение по адресу `/api/v1/openapi.json`: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} +{!../../docs_src/metadata/tutorial002.py!} ``` Если вы хотите отключить схему OpenAPI полностью, вы можете задать `openapi_url=None`, это также отключит пользовательские интерфейсы документации, которые его использует. @@ -116,5 +116,5 @@ К примеру, чтобы задать отображение Swagger UI по адресу `/documentation` и отключить ReDoc: ```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} +{!../../docs_src/metadata/tutorial003.py!} ``` diff --git a/docs/ru/docs/tutorial/path-operation-configuration.md b/docs/ru/docs/tutorial/path-operation-configuration.md index 26b1726ad..5f3855af2 100644 --- a/docs/ru/docs/tutorial/path-operation-configuration.md +++ b/docs/ru/docs/tutorial/path-operation-configuration.md @@ -19,7 +19,7 @@ //// tab | Python 3.10+ ```Python hl_lines="1 15" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} ``` //// @@ -27,7 +27,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} ``` //// @@ -35,7 +35,7 @@ //// tab | Python 3.8+ ```Python hl_lines="3 17" -{!> ../../../docs_src/path_operation_configuration/tutorial001.py!} +{!> ../../docs_src/path_operation_configuration/tutorial001.py!} ``` //// @@ -57,7 +57,7 @@ //// tab | Python 3.10+ ```Python hl_lines="15 20 25" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} ``` //// @@ -65,7 +65,7 @@ //// tab | Python 3.9+ ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} ``` //// @@ -73,7 +73,7 @@ //// tab | Python 3.8+ ```Python hl_lines="17 22 27" -{!> ../../../docs_src/path_operation_configuration/tutorial002.py!} +{!> ../../docs_src/path_operation_configuration/tutorial002.py!} ``` //// @@ -91,7 +91,7 @@ **FastAPI** поддерживает это так же, как и в случае с обычными строками: ```Python hl_lines="1 8-10 13 18" -{!../../../docs_src/path_operation_configuration/tutorial002b.py!} +{!../../docs_src/path_operation_configuration/tutorial002b.py!} ``` ## Краткое и развёрнутое содержание @@ -101,7 +101,7 @@ //// tab | Python 3.10+ ```Python hl_lines="18-19" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} ``` //// @@ -109,7 +109,7 @@ //// tab | Python 3.9+ ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} ``` //// @@ -117,7 +117,7 @@ //// tab | Python 3.8+ ```Python hl_lines="20-21" -{!> ../../../docs_src/path_operation_configuration/tutorial003.py!} +{!> ../../docs_src/path_operation_configuration/tutorial003.py!} ``` //// @@ -131,7 +131,7 @@ //// tab | Python 3.10+ ```Python hl_lines="17-25" -{!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} ``` //// @@ -139,7 +139,7 @@ //// tab | Python 3.9+ ```Python hl_lines="19-27" -{!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} ``` //// @@ -147,7 +147,7 @@ //// tab | Python 3.8+ ```Python hl_lines="19-27" -{!> ../../../docs_src/path_operation_configuration/tutorial004.py!} +{!> ../../docs_src/path_operation_configuration/tutorial004.py!} ``` //// @@ -163,7 +163,7 @@ //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} ``` //// @@ -171,7 +171,7 @@ //// tab | Python 3.9+ ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} ``` //// @@ -179,7 +179,7 @@ //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/path_operation_configuration/tutorial005.py!} +{!> ../../docs_src/path_operation_configuration/tutorial005.py!} ``` //// @@ -205,7 +205,7 @@ OpenAPI указывает, что каждой *операции пути* не Если вам необходимо пометить *операцию пути* как устаревшую, при этом не удаляя её, передайте параметр `deprecated`: ```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} +{!../../docs_src/path_operation_configuration/tutorial006.py!} ``` Он будет четко помечен как устаревший в интерактивной документации: diff --git a/docs/ru/docs/tutorial/path-params-numeric-validations.md b/docs/ru/docs/tutorial/path-params-numeric-validations.md index ced12c826..bf42ec725 100644 --- a/docs/ru/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ru/docs/tutorial/path-params-numeric-validations.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="1 3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="1 3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="3-4" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="1" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ /// ```Python hl_lines="3" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -77,7 +77,7 @@ //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} ``` //// @@ -85,7 +85,7 @@ //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} ``` //// @@ -93,7 +93,7 @@ //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} ``` //// @@ -107,7 +107,7 @@ /// ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} ``` //// @@ -121,7 +121,7 @@ /// ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` //// @@ -167,7 +167,7 @@ Path-параметр всегда является обязательным, п /// ```Python hl_lines="7" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` //// @@ -177,7 +177,7 @@ Path-параметр всегда является обязательным, п //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} ``` //// @@ -185,7 +185,7 @@ Path-параметр всегда является обязательным, п //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial002_an.py!} ``` //// @@ -214,7 +214,7 @@ Path-параметр всегда является обязательным, п Python не будет ничего делать с `*`, но он будет знать, что все следующие параметры являются именованными аргументами (парами ключ-значение), также известными как kwargs, даже если у них нет значений по умолчанию. ```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +{!../../docs_src/path_params_numeric_validations/tutorial003.py!} ``` ### Лучше с `Annotated` @@ -224,7 +224,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} ``` //// @@ -232,7 +232,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial003_an.py!} ``` //// @@ -246,7 +246,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} ``` //// @@ -254,7 +254,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!} ``` //// @@ -268,7 +268,7 @@ Python не будет ничего делать с `*`, но он будет з /// ```Python hl_lines="8" -{!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!} ``` //// @@ -283,7 +283,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} ``` //// @@ -291,7 +291,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005_an.py!} ``` //// @@ -305,7 +305,7 @@ Python не будет ничего делать с `*`, но он будет з /// ```Python hl_lines="9" -{!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!} ``` //// @@ -323,7 +323,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} ``` //// @@ -331,7 +331,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.py!} ``` //// @@ -345,7 +345,7 @@ Python не будет ничего делать с `*`, но он будет з /// ```Python hl_lines="11" -{!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} +{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!} ``` //// diff --git a/docs/ru/docs/tutorial/path-params.md b/docs/ru/docs/tutorial/path-params.md index dc3d64af4..d1d76cf7b 100644 --- a/docs/ru/docs/tutorial/path-params.md +++ b/docs/ru/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ Вы можете определить "параметры" или "переменные" пути, используя синтаксис форматированных строк Python: ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` Значение параметра пути `item_id` будет передано в функцию в качестве аргумента `item_id`. @@ -19,7 +19,7 @@ Вы можете объявить тип параметра пути в функции, используя стандартные аннотации типов Python. ```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} +{!../../docs_src/path_params/tutorial002.py!} ``` Здесь, `item_id` объявлен типом `int`. @@ -123,7 +123,7 @@ ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} +{!../../docs_src/path_params/tutorial003.py!} ``` Иначе путь для `/users/{user_id}` также будет соответствовать `/users/me`, "подразумевая", что он получает параметр `user_id` со значением `"me"`. @@ -131,7 +131,7 @@ Аналогично, вы не можете переопределить операцию с путем: ```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003b.py!} +{!../../docs_src/path_params/tutorial003b.py!} ``` Первый будет выполняться всегда, так как путь совпадает первым. @@ -149,7 +149,7 @@ Затем создайте атрибуты класса с фиксированными допустимыми значениями: ```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// info | "Дополнительная информация" @@ -169,7 +169,7 @@ Определите *параметр пути*, используя в аннотации типа класс перечисления (`ModelName`), созданный ранее: ```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` ### Проверьте документацию @@ -187,7 +187,7 @@ Вы можете сравнить это значение с *элементом перечисления* класса `ModelName`: ```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` #### Получение *значения перечисления* @@ -195,7 +195,7 @@ Можно получить фактическое значение (в данном случае - `str`) с помощью `model_name.value` или в общем случае `your_enum_member.value`: ```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` /// tip | "Подсказка" @@ -211,7 +211,7 @@ Они будут преобразованы в соответствующие значения (в данном случае - строки) перед их возвратом клиенту: ```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} +{!../../docs_src/path_params/tutorial005.py!} ``` Вы отправите клиенту такой JSON-ответ: @@ -251,7 +251,7 @@ OpenAPI не поддерживает способов объявления *п Можете использовать так: ```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} +{!../../docs_src/path_params/tutorial004.py!} ``` /// tip | "Подсказка" diff --git a/docs/ru/docs/tutorial/query-params-str-validations.md b/docs/ru/docs/tutorial/query-params-str-validations.md index e6653a837..0054af6ed 100644 --- a/docs/ru/docs/tutorial/query-params-str-validations.md +++ b/docs/ru/docs/tutorial/query-params-str-validations.md @@ -7,7 +7,7 @@ //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} ``` //// @@ -15,7 +15,7 @@ //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial001.py!} +{!> ../../docs_src/query_params_str_validations/tutorial001.py!} ``` //// @@ -46,7 +46,7 @@ FastAPI определит параметр `q` как необязательн В Python 3.9 или выше, `Annotated` является частью стандартной библиотеки, таким образом вы можете импортировать его из `typing`. ```Python hl_lines="1 3" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} ``` //// @@ -58,7 +58,7 @@ FastAPI определит параметр `q` как необязательн Эта библиотека будет установлена вместе с FastAPI. ```Python hl_lines="3-4" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} ``` //// @@ -116,7 +116,7 @@ q: Annotated[Union[str, None]] = None //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} ``` //// @@ -124,7 +124,7 @@ q: Annotated[Union[str, None]] = None //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} ``` //// @@ -154,7 +154,7 @@ q: Annotated[Union[str, None]] = None //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} ``` //// @@ -162,7 +162,7 @@ q: Annotated[Union[str, None]] = None //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial002.py!} +{!> ../../docs_src/query_params_str_validations/tutorial002.py!} ``` //// @@ -268,7 +268,7 @@ q: str = Query(default="rick") //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} ``` //// @@ -276,7 +276,7 @@ q: str = Query(default="rick") //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} ``` //// @@ -284,7 +284,7 @@ q: str = Query(default="rick") //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_an.py!} ``` //// @@ -298,7 +298,7 @@ q: str = Query(default="rick") /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} ``` //// @@ -312,7 +312,7 @@ q: str = Query(default="rick") /// ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial003.py!} +{!> ../../docs_src/query_params_str_validations/tutorial003.py!} ``` //// @@ -324,7 +324,7 @@ q: str = Query(default="rick") //// tab | Python 3.10+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} ``` //// @@ -332,7 +332,7 @@ q: str = Query(default="rick") //// tab | Python 3.9+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} ``` //// @@ -340,7 +340,7 @@ q: str = Query(default="rick") //// tab | Python 3.8+ ```Python hl_lines="12" -{!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_an.py!} ``` //// @@ -354,7 +354,7 @@ q: str = Query(default="rick") /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} ``` //// @@ -368,7 +368,7 @@ q: str = Query(default="rick") /// ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial004.py!} +{!> ../../docs_src/query_params_str_validations/tutorial004.py!} ``` //// @@ -392,7 +392,7 @@ q: str = Query(default="rick") //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} ``` //// @@ -400,7 +400,7 @@ q: str = Query(default="rick") //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial005_an.py!} ``` //// @@ -414,7 +414,7 @@ q: str = Query(default="rick") /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial005.py!} +{!> ../../docs_src/query_params_str_validations/tutorial005.py!} ``` //// @@ -462,7 +462,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} ``` //// @@ -470,7 +470,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006_an.py!} ``` //// @@ -484,7 +484,7 @@ q: Union[str, None] = Query(default=None, min_length=3) /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006.py!} ``` /// tip | "Подсказка" @@ -504,7 +504,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} ``` //// @@ -512,7 +512,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006b_an.py!} ``` //// @@ -526,7 +526,7 @@ q: Union[str, None] = Query(default=None, min_length=3) /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006b.py!} ``` //// @@ -550,7 +550,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} ``` //// @@ -558,7 +558,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} ``` //// @@ -566,7 +566,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_an.py!} ``` //// @@ -580,7 +580,7 @@ q: Union[str, None] = Query(default=None, min_length=3) /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} ``` //// @@ -594,7 +594,7 @@ q: Union[str, None] = Query(default=None, min_length=3) /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} ``` //// @@ -612,7 +612,7 @@ Pydantic, мощь которого используется в FastAPI для //// tab | Python 3.9+ ```Python hl_lines="4 10" -{!> ../../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!} ``` //// @@ -620,7 +620,7 @@ Pydantic, мощь которого используется в FastAPI для //// tab | Python 3.8+ ```Python hl_lines="2 9" -{!> ../../../docs_src/query_params_str_validations/tutorial006d_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006d_an.py!} ``` //// @@ -634,7 +634,7 @@ Pydantic, мощь которого используется в FastAPI для /// ```Python hl_lines="2 8" -{!> ../../../docs_src/query_params_str_validations/tutorial006d.py!} +{!> ../../docs_src/query_params_str_validations/tutorial006d.py!} ``` //// @@ -654,7 +654,7 @@ Pydantic, мощь которого используется в FastAPI для //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} ``` //// @@ -662,7 +662,7 @@ Pydantic, мощь которого используется в FastAPI для //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} ``` //// @@ -670,7 +670,7 @@ Pydantic, мощь которого используется в FastAPI для //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_an.py!} ``` //// @@ -684,7 +684,7 @@ Pydantic, мощь которого используется в FastAPI для /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} ``` //// @@ -698,7 +698,7 @@ Pydantic, мощь которого используется в FastAPI для /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} ``` //// @@ -712,7 +712,7 @@ Pydantic, мощь которого используется в FastAPI для /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial011.py!} +{!> ../../docs_src/query_params_str_validations/tutorial011.py!} ``` //// @@ -753,7 +753,7 @@ http://localhost:8000/items/?q=foo&q=bar //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} ``` //// @@ -761,7 +761,7 @@ http://localhost:8000/items/?q=foo&q=bar //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_an.py!} ``` //// @@ -775,7 +775,7 @@ http://localhost:8000/items/?q=foo&q=bar /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} ``` //// @@ -789,7 +789,7 @@ http://localhost:8000/items/?q=foo&q=bar /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial012.py!} +{!> ../../docs_src/query_params_str_validations/tutorial012.py!} ``` //// @@ -818,7 +818,7 @@ http://localhost:8000/items/ //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} ``` //// @@ -826,7 +826,7 @@ http://localhost:8000/items/ //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial013_an.py!} ``` //// @@ -840,7 +840,7 @@ http://localhost:8000/items/ /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial013.py!} +{!> ../../docs_src/query_params_str_validations/tutorial013.py!} ``` //// @@ -872,7 +872,7 @@ http://localhost:8000/items/ //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} ``` //// @@ -880,7 +880,7 @@ http://localhost:8000/items/ //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} ``` //// @@ -888,7 +888,7 @@ http://localhost:8000/items/ //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_an.py!} ``` //// @@ -902,7 +902,7 @@ http://localhost:8000/items/ /// ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} ``` //// @@ -916,7 +916,7 @@ http://localhost:8000/items/ /// ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial007.py!} +{!> ../../docs_src/query_params_str_validations/tutorial007.py!} ``` //// @@ -926,7 +926,7 @@ http://localhost:8000/items/ //// tab | Python 3.10+ ```Python hl_lines="14" -{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} ``` //// @@ -934,7 +934,7 @@ http://localhost:8000/items/ //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} ``` //// @@ -942,7 +942,7 @@ http://localhost:8000/items/ //// tab | Python 3.8+ ```Python hl_lines="15" -{!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_an.py!} ``` //// @@ -956,7 +956,7 @@ http://localhost:8000/items/ /// ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} ``` //// @@ -970,7 +970,7 @@ http://localhost:8000/items/ /// ```Python hl_lines="13" -{!> ../../../docs_src/query_params_str_validations/tutorial008.py!} +{!> ../../docs_src/query_params_str_validations/tutorial008.py!} ``` //// @@ -996,7 +996,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} ``` //// @@ -1004,7 +1004,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} ``` //// @@ -1012,7 +1012,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_an.py!} ``` //// @@ -1026,7 +1026,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems /// ```Python hl_lines="7" -{!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} ``` //// @@ -1040,7 +1040,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems /// ```Python hl_lines="9" -{!> ../../../docs_src/query_params_str_validations/tutorial009.py!} +{!> ../../docs_src/query_params_str_validations/tutorial009.py!} ``` //// @@ -1056,7 +1056,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} ``` //// @@ -1064,7 +1064,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.9+ ```Python hl_lines="19" -{!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} ``` //// @@ -1072,7 +1072,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_an.py!} ``` //// @@ -1086,7 +1086,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems /// ```Python hl_lines="16" -{!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} ``` //// @@ -1100,7 +1100,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems /// ```Python hl_lines="18" -{!> ../../../docs_src/query_params_str_validations/tutorial010.py!} +{!> ../../docs_src/query_params_str_validations/tutorial010.py!} ``` //// @@ -1116,7 +1116,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} ``` //// @@ -1124,7 +1124,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.9+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} ``` //// @@ -1132,7 +1132,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!} ``` //// @@ -1146,7 +1146,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems /// ```Python hl_lines="8" -{!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} ``` //// @@ -1160,7 +1160,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems /// ```Python hl_lines="10" -{!> ../../../docs_src/query_params_str_validations/tutorial014.py!} +{!> ../../docs_src/query_params_str_validations/tutorial014.py!} ``` //// diff --git a/docs/ru/docs/tutorial/query-params.md b/docs/ru/docs/tutorial/query-params.md index 061f9be04..edf06746b 100644 --- a/docs/ru/docs/tutorial/query-params.md +++ b/docs/ru/docs/tutorial/query-params.md @@ -3,7 +3,7 @@ Когда вы объявляете параметры функции, которые не являются параметрами пути, они автоматически интерпретируются как "query"-параметры. ```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} +{!../../docs_src/query_params/tutorial001.py!} ``` Query-параметры представляют из себя набор пар ключ-значение, которые идут после знака `?` в URL-адресе, разделенные символами `&`. @@ -66,7 +66,7 @@ http://127.0.0.1:8000/items/?skip=20 //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial002_py310.py!} +{!> ../../docs_src/query_params/tutorial002_py310.py!} ``` //// @@ -74,7 +74,7 @@ http://127.0.0.1:8000/items/?skip=20 //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial002.py!} +{!> ../../docs_src/query_params/tutorial002.py!} ``` //// @@ -94,7 +94,7 @@ http://127.0.0.1:8000/items/?skip=20 //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial003_py310.py!} +{!> ../../docs_src/query_params/tutorial003_py310.py!} ``` //// @@ -102,7 +102,7 @@ http://127.0.0.1:8000/items/?skip=20 //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial003.py!} +{!> ../../docs_src/query_params/tutorial003.py!} ``` //// @@ -151,7 +151,7 @@ http://127.0.0.1:8000/items/foo?short=yes //// tab | Python 3.10+ ```Python hl_lines="6 8" -{!> ../../../docs_src/query_params/tutorial004_py310.py!} +{!> ../../docs_src/query_params/tutorial004_py310.py!} ``` //// @@ -159,7 +159,7 @@ http://127.0.0.1:8000/items/foo?short=yes //// tab | Python 3.8+ ```Python hl_lines="8 10" -{!> ../../../docs_src/query_params/tutorial004.py!} +{!> ../../docs_src/query_params/tutorial004.py!} ``` //// @@ -173,7 +173,7 @@ http://127.0.0.1:8000/items/foo?short=yes Но если вы хотите сделать query-параметр обязательным, вы можете просто не указывать значение по умолчанию: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` Здесь параметр запроса `needy` является обязательным параметром с типом данных `str`. @@ -221,7 +221,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params/tutorial006_py310.py!} +{!> ../../docs_src/query_params/tutorial006_py310.py!} ``` //// @@ -229,7 +229,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params/tutorial006.py!} +{!> ../../docs_src/query_params/tutorial006.py!} ``` //// diff --git a/docs/ru/docs/tutorial/request-files.md b/docs/ru/docs/tutorial/request-files.md index 1fbc4acc0..34b9c94fa 100644 --- a/docs/ru/docs/tutorial/request-files.md +++ b/docs/ru/docs/tutorial/request-files.md @@ -19,7 +19,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -27,7 +27,7 @@ //// tab | Python 3.6+ ```Python hl_lines="1" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -41,7 +41,7 @@ /// ```Python hl_lines="1" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -53,7 +53,7 @@ //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -61,7 +61,7 @@ //// tab | Python 3.6+ ```Python hl_lines="8" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -75,7 +75,7 @@ /// ```Python hl_lines="7" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -109,7 +109,7 @@ //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_an_py39.py!} ``` //// @@ -117,7 +117,7 @@ //// tab | Python 3.6+ ```Python hl_lines="13" -{!> ../../../docs_src/request_files/tutorial001_an.py!} +{!> ../../docs_src/request_files/tutorial001_an.py!} ``` //// @@ -131,7 +131,7 @@ /// ```Python hl_lines="12" -{!> ../../../docs_src/request_files/tutorial001.py!} +{!> ../../docs_src/request_files/tutorial001.py!} ``` //// @@ -220,7 +220,7 @@ contents = myfile.file.read() //// tab | Python 3.10+ ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} +{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} ``` //// @@ -228,7 +228,7 @@ contents = myfile.file.read() //// tab | Python 3.9+ ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} ``` //// @@ -236,7 +236,7 @@ contents = myfile.file.read() //// tab | Python 3.6+ ```Python hl_lines="10 18" -{!> ../../../docs_src/request_files/tutorial001_02_an.py!} +{!> ../../docs_src/request_files/tutorial001_02_an.py!} ``` //// @@ -250,7 +250,7 @@ contents = myfile.file.read() /// ```Python hl_lines="7 15" -{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +{!> ../../docs_src/request_files/tutorial001_02_py310.py!} ``` //// @@ -264,7 +264,7 @@ contents = myfile.file.read() /// ```Python hl_lines="9 17" -{!> ../../../docs_src/request_files/tutorial001_02.py!} +{!> ../../docs_src/request_files/tutorial001_02.py!} ``` //// @@ -276,7 +276,7 @@ contents = myfile.file.read() //// tab | Python 3.9+ ```Python hl_lines="9 15" -{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} +{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} ``` //// @@ -284,7 +284,7 @@ contents = myfile.file.read() //// tab | Python 3.6+ ```Python hl_lines="8 14" -{!> ../../../docs_src/request_files/tutorial001_03_an.py!} +{!> ../../docs_src/request_files/tutorial001_03_an.py!} ``` //// @@ -298,7 +298,7 @@ contents = myfile.file.read() /// ```Python hl_lines="7 13" -{!> ../../../docs_src/request_files/tutorial001_03.py!} +{!> ../../docs_src/request_files/tutorial001_03.py!} ``` //// @@ -314,7 +314,7 @@ contents = myfile.file.read() //// tab | Python 3.9+ ```Python hl_lines="10 15" -{!> ../../../docs_src/request_files/tutorial002_an_py39.py!} +{!> ../../docs_src/request_files/tutorial002_an_py39.py!} ``` //// @@ -322,7 +322,7 @@ contents = myfile.file.read() //// tab | Python 3.6+ ```Python hl_lines="11 16" -{!> ../../../docs_src/request_files/tutorial002_an.py!} +{!> ../../docs_src/request_files/tutorial002_an.py!} ``` //// @@ -336,7 +336,7 @@ contents = myfile.file.read() /// ```Python hl_lines="8 13" -{!> ../../../docs_src/request_files/tutorial002_py39.py!} +{!> ../../docs_src/request_files/tutorial002_py39.py!} ``` //// @@ -350,7 +350,7 @@ contents = myfile.file.read() /// ```Python hl_lines="10 15" -{!> ../../../docs_src/request_files/tutorial002.py!} +{!> ../../docs_src/request_files/tutorial002.py!} ``` //// @@ -372,7 +372,7 @@ contents = myfile.file.read() //// tab | Python 3.9+ ```Python hl_lines="11 18-20" -{!> ../../../docs_src/request_files/tutorial003_an_py39.py!} +{!> ../../docs_src/request_files/tutorial003_an_py39.py!} ``` //// @@ -380,7 +380,7 @@ contents = myfile.file.read() //// tab | Python 3.6+ ```Python hl_lines="12 19-21" -{!> ../../../docs_src/request_files/tutorial003_an.py!} +{!> ../../docs_src/request_files/tutorial003_an.py!} ``` //// @@ -394,7 +394,7 @@ contents = myfile.file.read() /// ```Python hl_lines="9 16" -{!> ../../../docs_src/request_files/tutorial003_py39.py!} +{!> ../../docs_src/request_files/tutorial003_py39.py!} ``` //// @@ -408,7 +408,7 @@ contents = myfile.file.read() /// ```Python hl_lines="11 18" -{!> ../../../docs_src/request_files/tutorial003.py!} +{!> ../../docs_src/request_files/tutorial003.py!} ``` //// diff --git a/docs/ru/docs/tutorial/request-forms-and-files.md b/docs/ru/docs/tutorial/request-forms-and-files.md index b38962866..9b449bcd9 100644 --- a/docs/ru/docs/tutorial/request-forms-and-files.md +++ b/docs/ru/docs/tutorial/request-forms-and-files.md @@ -15,7 +15,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} ``` //// @@ -23,7 +23,7 @@ //// tab | Python 3.6+ ```Python hl_lines="1" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} ``` //// @@ -37,7 +37,7 @@ /// ```Python hl_lines="1" -{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001.py!} ``` //// @@ -49,7 +49,7 @@ //// tab | Python 3.9+ ```Python hl_lines="10-12" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} ``` //// @@ -57,7 +57,7 @@ //// tab | Python 3.6+ ```Python hl_lines="9-11" -{!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} ``` //// @@ -71,7 +71,7 @@ /// ```Python hl_lines="8" -{!> ../../../docs_src/request_forms_and_files/tutorial001.py!} +{!> ../../docs_src/request_forms_and_files/tutorial001.py!} ``` //// diff --git a/docs/ru/docs/tutorial/request-forms.md b/docs/ru/docs/tutorial/request-forms.md index 3737f1347..93b44437b 100644 --- a/docs/ru/docs/tutorial/request-forms.md +++ b/docs/ru/docs/tutorial/request-forms.md @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="1" -{!> ../../../docs_src/request_forms/tutorial001_an.py!} +{!> ../../docs_src/request_forms/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="1" -{!> ../../../docs_src/request_forms/tutorial001.py!} +{!> ../../docs_src/request_forms/tutorial001.py!} ``` //// @@ -51,7 +51,7 @@ //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} ``` //// @@ -59,7 +59,7 @@ //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/request_forms/tutorial001_an.py!} +{!> ../../docs_src/request_forms/tutorial001_an.py!} ``` //// @@ -73,7 +73,7 @@ /// ```Python hl_lines="7" -{!> ../../../docs_src/request_forms/tutorial001.py!} +{!> ../../docs_src/request_forms/tutorial001.py!} ``` //// diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md index f8c910fe9..363e64676 100644 --- a/docs/ru/docs/tutorial/response-model.md +++ b/docs/ru/docs/tutorial/response-model.md @@ -7,7 +7,7 @@ FastAPI позволяет использовать **аннотации тип //// tab | Python 3.10+ ```Python hl_lines="16 21" -{!> ../../../docs_src/response_model/tutorial001_01_py310.py!} +{!> ../../docs_src/response_model/tutorial001_01_py310.py!} ``` //// @@ -15,7 +15,7 @@ FastAPI позволяет использовать **аннотации тип //// tab | Python 3.9+ ```Python hl_lines="18 23" -{!> ../../../docs_src/response_model/tutorial001_01_py39.py!} +{!> ../../docs_src/response_model/tutorial001_01_py39.py!} ``` //// @@ -23,7 +23,7 @@ FastAPI позволяет использовать **аннотации тип //// tab | Python 3.8+ ```Python hl_lines="18 23" -{!> ../../../docs_src/response_model/tutorial001_01.py!} +{!> ../../docs_src/response_model/tutorial001_01.py!} ``` //// @@ -62,7 +62,7 @@ FastAPI будет использовать этот возвращаемый т //// tab | Python 3.10+ ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001_py310.py!} +{!> ../../docs_src/response_model/tutorial001_py310.py!} ``` //// @@ -70,7 +70,7 @@ FastAPI будет использовать этот возвращаемый т //// tab | Python 3.9+ ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001_py39.py!} +{!> ../../docs_src/response_model/tutorial001_py39.py!} ``` //// @@ -78,7 +78,7 @@ FastAPI будет использовать этот возвращаемый т //// tab | Python 3.8+ ```Python hl_lines="17 22 24-27" -{!> ../../../docs_src/response_model/tutorial001.py!} +{!> ../../docs_src/response_model/tutorial001.py!} ``` //// @@ -116,7 +116,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.10+ ```Python hl_lines="7 9" -{!> ../../../docs_src/response_model/tutorial002_py310.py!} +{!> ../../docs_src/response_model/tutorial002_py310.py!} ``` //// @@ -124,7 +124,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.8+ ```Python hl_lines="9 11" -{!> ../../../docs_src/response_model/tutorial002.py!} +{!> ../../docs_src/response_model/tutorial002.py!} ``` //// @@ -142,7 +142,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/response_model/tutorial002_py310.py!} +{!> ../../docs_src/response_model/tutorial002_py310.py!} ``` //// @@ -150,7 +150,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/response_model/tutorial002.py!} +{!> ../../docs_src/response_model/tutorial002.py!} ``` //// @@ -174,7 +174,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.10+ ```Python hl_lines="9 11 16" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -182,7 +182,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.8+ ```Python hl_lines="9 11 16" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -192,7 +192,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.10+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -200,7 +200,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -210,7 +210,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.10+ ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial003_py310.py!} +{!> ../../docs_src/response_model/tutorial003_py310.py!} ``` //// @@ -218,7 +218,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial003.py!} +{!> ../../docs_src/response_model/tutorial003.py!} ``` //// @@ -248,7 +248,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.10+ ```Python hl_lines="7-10 13-14 18" -{!> ../../../docs_src/response_model/tutorial003_01_py310.py!} +{!> ../../docs_src/response_model/tutorial003_01_py310.py!} ``` //// @@ -256,7 +256,7 @@ FastAPI будет использовать значение `response_model` д //// tab | Python 3.8+ ```Python hl_lines="9-13 15-16 20" -{!> ../../../docs_src/response_model/tutorial003_01.py!} +{!> ../../docs_src/response_model/tutorial003_01.py!} ``` //// @@ -302,7 +302,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Самый частый сценарий использования - это [возвращать Response напрямую, как описано в расширенной документации](../advanced/response-directly.md){.internal-link target=_blank}. ```Python hl_lines="8 10-11" -{!> ../../../docs_src/response_model/tutorial003_02.py!} +{!> ../../docs_src/response_model/tutorial003_02.py!} ``` Это поддерживается FastAPI по-умолчанию, т.к. аннотация проставлена в классе (или подклассе) `Response`. @@ -314,7 +314,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Вы также можете указать подкласс `Response` в аннотации типа: ```Python hl_lines="8-9" -{!> ../../../docs_src/response_model/tutorial003_03.py!} +{!> ../../docs_src/response_model/tutorial003_03.py!} ``` Это сработает, потому что `RedirectResponse` является подклассом `Response` и FastAPI автоматически обработает этот простейший случай. @@ -328,7 +328,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/response_model/tutorial003_04_py310.py!} +{!> ../../docs_src/response_model/tutorial003_04_py310.py!} ``` //// @@ -336,7 +336,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/response_model/tutorial003_04.py!} +{!> ../../docs_src/response_model/tutorial003_04.py!} ``` //// @@ -354,7 +354,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/response_model/tutorial003_05_py310.py!} +{!> ../../docs_src/response_model/tutorial003_05_py310.py!} ``` //// @@ -362,7 +362,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/response_model/tutorial003_05.py!} +{!> ../../docs_src/response_model/tutorial003_05.py!} ``` //// @@ -376,7 +376,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.10+ ```Python hl_lines="9 11-12" -{!> ../../../docs_src/response_model/tutorial004_py310.py!} +{!> ../../docs_src/response_model/tutorial004_py310.py!} ``` //// @@ -384,7 +384,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.9+ ```Python hl_lines="11 13-14" -{!> ../../../docs_src/response_model/tutorial004_py39.py!} +{!> ../../docs_src/response_model/tutorial004_py39.py!} ``` //// @@ -392,7 +392,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.8+ ```Python hl_lines="11 13-14" -{!> ../../../docs_src/response_model/tutorial004.py!} +{!> ../../docs_src/response_model/tutorial004.py!} ``` //// @@ -412,7 +412,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.10+ ```Python hl_lines="22" -{!> ../../../docs_src/response_model/tutorial004_py310.py!} +{!> ../../docs_src/response_model/tutorial004_py310.py!} ``` //// @@ -420,7 +420,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.9+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial004_py39.py!} +{!> ../../docs_src/response_model/tutorial004_py39.py!} ``` //// @@ -428,7 +428,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/response_model/tutorial004.py!} +{!> ../../docs_src/response_model/tutorial004.py!} ``` //// @@ -523,7 +523,7 @@ FastAPI достаточно умен (на самом деле, это засл //// tab | Python 3.10+ ```Python hl_lines="29 35" -{!> ../../../docs_src/response_model/tutorial005_py310.py!} +{!> ../../docs_src/response_model/tutorial005_py310.py!} ``` //// @@ -531,7 +531,7 @@ FastAPI достаточно умен (на самом деле, это засл //// tab | Python 3.8+ ```Python hl_lines="31 37" -{!> ../../../docs_src/response_model/tutorial005.py!} +{!> ../../docs_src/response_model/tutorial005.py!} ``` //// @@ -551,7 +551,7 @@ FastAPI достаточно умен (на самом деле, это засл //// tab | Python 3.10+ ```Python hl_lines="29 35" -{!> ../../../docs_src/response_model/tutorial006_py310.py!} +{!> ../../docs_src/response_model/tutorial006_py310.py!} ``` //// @@ -559,7 +559,7 @@ FastAPI достаточно умен (на самом деле, это засл //// tab | Python 3.8+ ```Python hl_lines="31 37" -{!> ../../../docs_src/response_model/tutorial006.py!} +{!> ../../docs_src/response_model/tutorial006.py!} ``` //// diff --git a/docs/ru/docs/tutorial/response-status-code.md b/docs/ru/docs/tutorial/response-status-code.md index a36c42d05..48808bea7 100644 --- a/docs/ru/docs/tutorial/response-status-code.md +++ b/docs/ru/docs/tutorial/response-status-code.md @@ -9,7 +9,7 @@ * и других. ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` /// note | "Примечание" @@ -77,7 +77,7 @@ FastAPI знает об этом и создаст документацию Open Рассмотрим предыдущий пример еще раз: ```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} +{!../../docs_src/response_status_code/tutorial001.py!} ``` `201` – это код статуса "Создано". @@ -87,7 +87,7 @@ FastAPI знает об этом и создаст документацию Open Для удобства вы можете использовать переменные из `fastapi.status`. ```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} +{!../../docs_src/response_status_code/tutorial002.py!} ``` Они содержат те же числовые значения, но позволяют использовать подсказки редактора для выбора кода статуса: diff --git a/docs/ru/docs/tutorial/schema-extra-example.md b/docs/ru/docs/tutorial/schema-extra-example.md index 1b216de3a..daa264afc 100644 --- a/docs/ru/docs/tutorial/schema-extra-example.md +++ b/docs/ru/docs/tutorial/schema-extra-example.md @@ -11,7 +11,7 @@ //// tab | Python 3.10+ ```Python hl_lines="13-21" -{!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} ``` //// @@ -19,7 +19,7 @@ //// tab | Python 3.8+ ```Python hl_lines="15-23" -{!> ../../../docs_src/schema_extra_example/tutorial001.py!} +{!> ../../docs_src/schema_extra_example/tutorial001.py!} ``` //// @@ -43,7 +43,7 @@ //// tab | Python 3.10+ ```Python hl_lines="2 8-11" -{!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} ``` //// @@ -51,7 +51,7 @@ //// tab | Python 3.8+ ```Python hl_lines="4 10-13" -{!> ../../../docs_src/schema_extra_example/tutorial002.py!} +{!> ../../docs_src/schema_extra_example/tutorial002.py!} ``` //// @@ -83,7 +83,7 @@ //// tab | Python 3.10+ ```Python hl_lines="22-27" -{!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} ``` //// @@ -91,7 +91,7 @@ //// tab | Python 3.9+ ```Python hl_lines="22-27" -{!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} ``` //// @@ -99,7 +99,7 @@ //// tab | Python 3.8+ ```Python hl_lines="23-28" -{!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} ``` //// @@ -113,7 +113,7 @@ /// ```Python hl_lines="18-23" -{!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} ``` //// @@ -127,7 +127,7 @@ /// ```Python hl_lines="20-25" -{!> ../../../docs_src/schema_extra_example/tutorial003.py!} +{!> ../../docs_src/schema_extra_example/tutorial003.py!} ``` //// @@ -154,7 +154,7 @@ //// tab | Python 3.10+ ```Python hl_lines="23-49" -{!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!} ``` //// @@ -162,7 +162,7 @@ //// tab | Python 3.9+ ```Python hl_lines="23-49" -{!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!} ``` //// @@ -170,7 +170,7 @@ //// tab | Python 3.8+ ```Python hl_lines="24-50" -{!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_an.py!} ``` //// @@ -184,7 +184,7 @@ /// ```Python hl_lines="19-45" -{!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} +{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} ``` //// @@ -198,7 +198,7 @@ /// ```Python hl_lines="21-47" -{!> ../../../docs_src/schema_extra_example/tutorial004.py!} +{!> ../../docs_src/schema_extra_example/tutorial004.py!} ``` //// diff --git a/docs/ru/docs/tutorial/security/first-steps.md b/docs/ru/docs/tutorial/security/first-steps.md index 444a06915..c98ce2c60 100644 --- a/docs/ru/docs/tutorial/security/first-steps.md +++ b/docs/ru/docs/tutorial/security/first-steps.md @@ -23,7 +23,7 @@ //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -45,7 +45,7 @@ /// ```Python -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// @@ -155,7 +155,7 @@ OAuth2 был разработан для того, чтобы бэкэнд ил //// tab | Python 3.9+ ```Python hl_lines="8" -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -163,7 +163,7 @@ OAuth2 был разработан для того, чтобы бэкэнд ил //// tab | Python 3.8+ ```Python hl_lines="7" -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -177,7 +177,7 @@ OAuth2 был разработан для того, чтобы бэкэнд ил /// ```Python hl_lines="6" -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// @@ -221,7 +221,7 @@ oauth2_scheme(some, parameters) //// tab | Python 3.9+ ```Python hl_lines="12" -{!> ../../../docs_src/security/tutorial001_an_py39.py!} +{!> ../../docs_src/security/tutorial001_an_py39.py!} ``` //// @@ -229,7 +229,7 @@ oauth2_scheme(some, parameters) //// tab | Python 3.8+ ```Python hl_lines="11" -{!> ../../../docs_src/security/tutorial001_an.py!} +{!> ../../docs_src/security/tutorial001_an.py!} ``` //// @@ -243,7 +243,7 @@ oauth2_scheme(some, parameters) /// ```Python hl_lines="10" -{!> ../../../docs_src/security/tutorial001.py!} +{!> ../../docs_src/security/tutorial001.py!} ``` //// diff --git a/docs/ru/docs/tutorial/static-files.md b/docs/ru/docs/tutorial/static-files.md index ccddae249..4734554f3 100644 --- a/docs/ru/docs/tutorial/static-files.md +++ b/docs/ru/docs/tutorial/static-files.md @@ -8,7 +8,7 @@ * "Примонтируйте" экземпляр `StaticFiles()` с указанием определенной директории. ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` /// note | "Технические детали" diff --git a/docs/ru/docs/tutorial/testing.md b/docs/ru/docs/tutorial/testing.md index efefbfb01..ae045bbbe 100644 --- a/docs/ru/docs/tutorial/testing.md +++ b/docs/ru/docs/tutorial/testing.md @@ -27,7 +27,7 @@ Напишите простое утверждение с `assert` дабы проверить истинность Python-выражения (это тоже стандарт `pytest`). ```Python hl_lines="2 12 15-18" -{!../../../docs_src/app_testing/tutorial001.py!} +{!../../docs_src/app_testing/tutorial001.py!} ``` /// tip | "Подсказка" @@ -75,7 +75,7 @@ ```Python -{!../../../docs_src/app_testing/main.py!} +{!../../docs_src/app_testing/main.py!} ``` ### Файл тестов @@ -93,7 +93,7 @@ Так как оба файла находятся в одной директории, для импорта объекта приложения из файла `main` в файл `test_main` Вы можете использовать относительный импорт: ```Python hl_lines="3" -{!../../../docs_src/app_testing/test_main.py!} +{!../../docs_src/app_testing/test_main.py!} ``` ...и писать дальше тесты, как и раньше. @@ -125,7 +125,7 @@ //// tab | Python 3.10+ ```Python -{!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} ``` //// @@ -133,7 +133,7 @@ //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} ``` //// @@ -141,7 +141,7 @@ //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/app_testing/app_b_an/main.py!} +{!> ../../docs_src/app_testing/app_b_an/main.py!} ``` //// @@ -155,7 +155,7 @@ /// ```Python -{!> ../../../docs_src/app_testing/app_b_py310/main.py!} +{!> ../../docs_src/app_testing/app_b_py310/main.py!} ``` //// @@ -169,7 +169,7 @@ /// ```Python -{!> ../../../docs_src/app_testing/app_b/main.py!} +{!> ../../docs_src/app_testing/app_b/main.py!} ``` //// @@ -179,7 +179,7 @@ Теперь обновим файл `test_main.py`, добавив в него тестов: ```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} +{!> ../../docs_src/app_testing/app_b/test_main.py!} ``` Если Вы не знаете, как передать информацию в запросе, можете воспользоваться поисковиком (погуглить) и задать вопрос: "Как передать информацию в запросе с помощью `httpx`", можно даже спросить: "Как передать информацию в запросе с помощью `requests`", поскольку дизайн HTTPX основан на дизайне Requests. diff --git a/docs/tr/docs/advanced/testing-websockets.md b/docs/tr/docs/advanced/testing-websockets.md index 59a2499e2..aa8a040d0 100644 --- a/docs/tr/docs/advanced/testing-websockets.md +++ b/docs/tr/docs/advanced/testing-websockets.md @@ -5,7 +5,7 @@ WebSockets testi yapmak için `TestClient`'ı kullanabilirsiniz. Bu işlem için, `TestClient`'ı bir `with` ifadesinde kullanarak WebSocket'e bağlanabilirsiniz: ```Python hl_lines="27-31" -{!../../../docs_src/app_testing/tutorial002.py!} +{!../../docs_src/app_testing/tutorial002.py!} ``` /// note | "Not" diff --git a/docs/tr/docs/advanced/wsgi.md b/docs/tr/docs/advanced/wsgi.md index 54a6f20e2..bc8da16df 100644 --- a/docs/tr/docs/advanced/wsgi.md +++ b/docs/tr/docs/advanced/wsgi.md @@ -13,7 +13,7 @@ Ardından WSGI (örneğin Flask) uygulamanızı middleware ile sarmalayın. Son olarak da bir yol altında bağlama işlemini gerçekleştirin. ```Python hl_lines="2-3 23" -{!../../../docs_src/wsgi/tutorial001.py!} +{!../../docs_src/wsgi/tutorial001.py!} ``` ## Kontrol Edelim diff --git a/docs/tr/docs/python-types.md b/docs/tr/docs/python-types.md index b8b880c6d..9584a5732 100644 --- a/docs/tr/docs/python-types.md +++ b/docs/tr/docs/python-types.md @@ -23,7 +23,7 @@ Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, Basit bir örnek ile başlayalım: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Programın çıktısı: @@ -39,7 +39,7 @@ Fonksiyon sırayla şunları yapar: * Değişkenleri aralarında bir boşlukla beraber Birleştirir. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Düzenle @@ -83,7 +83,7 @@ Bu kadar. İşte bunlar "tip belirteçleri": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` Bu, aşağıdaki gibi varsayılan değerleri bildirmekle aynı şey değildir: @@ -113,7 +113,7 @@ Aradığınızı bulana kadar seçenekleri kaydırabilirsiniz: Bu fonksiyon, zaten tür belirteçlerine sahip: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama değil, hata kontrolleri de sağlar: @@ -123,7 +123,7 @@ Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama de Artık `age` değişkenini `str(age)` olarak kullanmanız gerektiğini biliyorsunuz: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Tip bildirme @@ -144,7 +144,7 @@ Yalnızca `str` değil, tüm standart Python tiplerinin bildirebilirsiniz. * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Tip parametreleri ile Generic tipler @@ -162,7 +162,7 @@ Bu tür tip belirteçlerini desteklemek için özel olarak mevcuttur. From `typing`, import `List` (büyük harf olan `L` ile): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` Değişkenin tipini yine iki nokta üstüste (`:`) ile belirleyin. @@ -172,7 +172,7 @@ tip olarak `List` kullanın. Liste, bazı dahili tipleri içeren bir tür olduğundan, bunları köşeli parantez içine alırsınız: ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` /// tip | "Ipucu" @@ -200,7 +200,7 @@ Ve yine, editör bunun bir `str` ​​olduğunu biliyor ve bunun için destek s `Tuple` ve `set`lerin tiplerini bildirmek için de aynısını yapıyoruz: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` Bu şu anlama geliyor: @@ -217,7 +217,7 @@ Bir `dict` tanımlamak için virgülle ayrılmış iki parametre verebilirsiniz. İkinci parametre ise `dict` değerinin `value` değeri içindir: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` Bu şu anlama gelir: @@ -231,7 +231,7 @@ Bu şu anlama gelir: `Optional` bir değişkenin `str`gibi bir tipi olabileceğini ama isteğe bağlı olarak tipinin `None` olabileceğini belirtir: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` `str` yerine `Optional[str]` kullanmak editorün bu değerin her zaman `str` tipinde değil bazen `None` tipinde de olabileceğini belirtir ve hataları tespit etmemizde yardımcı olur. @@ -256,13 +256,13 @@ Bir değişkenin tipini bir sınıf ile bildirebilirsiniz. Diyelim ki `name` değerine sahip `Person` sınıfınız var: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Sonra bir değişkeni 'Person' tipinde tanımlayabilirsiniz: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Ve yine bütün editör desteğini alırsınız: @@ -284,7 +284,7 @@ Ve ortaya çıkan nesne üzerindeki bütün editör desteğini alırsınız. Resmi Pydantic dokümanlarından alınmıştır: ```Python -{!../../../docs_src/python_types/tutorial011.py!} +{!../../docs_src/python_types/tutorial011.py!} ``` /// info diff --git a/docs/tr/docs/tutorial/cookie-params.md b/docs/tr/docs/tutorial/cookie-params.md index 807f85e8a..895cf9b03 100644 --- a/docs/tr/docs/tutorial/cookie-params.md +++ b/docs/tr/docs/tutorial/cookie-params.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. /// ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. /// ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -67,7 +67,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -75,7 +75,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -97,7 +97,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. /// ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -111,7 +111,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. /// ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// diff --git a/docs/tr/docs/tutorial/first-steps.md b/docs/tr/docs/tutorial/first-steps.md index 76c035992..335fcaece 100644 --- a/docs/tr/docs/tutorial/first-steps.md +++ b/docs/tr/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ En sade FastAPI dosyası şu şekilde görünür: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Yukarıdaki içeriği bir `main.py` dosyasına kopyalayalım. @@ -134,7 +134,7 @@ Ayrıca, API'ınızla iletişim kuracak önyüz, mobil veya IoT uygulamaları gi ### Adım 1: `FastAPI`yı Projemize Dahil Edelim ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI`, API'niz için tüm işlevselliği sağlayan bir Python sınıfıdır. @@ -150,7 +150,7 @@ Ayrıca, API'ınızla iletişim kuracak önyüz, mobil veya IoT uygulamaları gi ### Adım 2: Bir `FastAPI` "Örneği" Oluşturalım ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Burada `app` değişkeni `FastAPI` sınıfının bir örneği olacaktır. @@ -172,7 +172,7 @@ $ uvicorn main:app --reload Uygulamanızı aşağıdaki gibi oluşturursanız: ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} +{!../../docs_src/first_steps/tutorial002.py!} ``` Ve bunu `main.py` dosyasına yerleştirirseniz eğer `uvicorn` komutunu şu şekilde çalıştırabilirsiniz: @@ -251,7 +251,7 @@ Biz de onları "**operasyonlar**" olarak adlandıracağız. #### Bir *Yol Operasyonu Dekoratörü* Tanımlayalım ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `@app.get("/")` dekoratörü, **FastAPI**'a hemen altındaki fonksiyonun aşağıdaki durumlardan sorumlu olduğunu söyler: @@ -307,7 +307,7 @@ Aşağıdaki, bizim **yol operasyonu fonksiyonumuzdur**: * **fonksiyon**: "dekoratör"ün (`@app.get("/")`'in) altındaki fonksiyondur. ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Bu bir Python fonksiyonudur. @@ -321,7 +321,7 @@ Bu durumda bu fonksiyon bir `async` fonksiyondur. Bu fonksiyonu `async def` yerine normal bir fonksiyon olarak da tanımlayabilirsiniz. ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` /// note | "Not" @@ -333,7 +333,7 @@ Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurr ### Adım 5: İçeriği Geri Döndürün ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Bir `dict`, `list` veya `str`, `int` gibi tekil değerler döndürebilirsiniz. diff --git a/docs/tr/docs/tutorial/path-params.md b/docs/tr/docs/tutorial/path-params.md index d36242083..9017d99ab 100644 --- a/docs/tr/docs/tutorial/path-params.md +++ b/docs/tr/docs/tutorial/path-params.md @@ -3,7 +3,7 @@ Yol "parametrelerini" veya "değişkenlerini" Python string biçimlemede kullanılan sözdizimi ile tanımlayabilirsiniz. ```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} +{!../../docs_src/path_params/tutorial001.py!} ``` Yol parametresi olan `item_id`'nin değeri, fonksiyonunuza `item_id` argümanı olarak aktarılacaktır. @@ -19,7 +19,7 @@ Eğer bu örneği çalıştırıp ../../../docs_src/query_params/tutorial002_py310.py!} +{!> ../../docs_src/query_params/tutorial002_py310.py!} ``` //// @@ -74,7 +74,7 @@ Aynı şekilde, varsayılan değerlerini `None` olarak atayarak isteğe bağlı //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial002.py!} +{!> ../../docs_src/query_params/tutorial002.py!} ``` //// @@ -94,7 +94,7 @@ Aşağıda görüldüğü gibi dönüştürülmek üzere `bool` tipleri de tanı //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/query_params/tutorial003_py310.py!} +{!> ../../docs_src/query_params/tutorial003_py310.py!} ``` //// @@ -102,7 +102,7 @@ Aşağıda görüldüğü gibi dönüştürülmek üzere `bool` tipleri de tanı //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/query_params/tutorial003.py!} +{!> ../../docs_src/query_params/tutorial003.py!} ``` //// @@ -151,7 +151,7 @@ Ve parametreleri, herhangi bir sıraya koymanıza da gerek yoktur. //// tab | Python 3.10+ ```Python hl_lines="6 8" -{!> ../../../docs_src/query_params/tutorial004_py310.py!} +{!> ../../docs_src/query_params/tutorial004_py310.py!} ``` //// @@ -159,7 +159,7 @@ Ve parametreleri, herhangi bir sıraya koymanıza da gerek yoktur. //// tab | Python 3.8+ ```Python hl_lines="8 10" -{!> ../../../docs_src/query_params/tutorial004.py!} +{!> ../../docs_src/query_params/tutorial004.py!} ``` //// @@ -173,7 +173,7 @@ Parametre için belirli bir değer atamak istemeyip parametrenin sadece isteğe Fakat, bir sorgu parametresini zorunlu yapmak istiyorsanız varsayılan bir değer atamamanız yeterli olacaktır: ```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} +{!../../docs_src/query_params/tutorial005.py!} ``` Burada `needy` parametresi `str` tipinden oluşan zorunlu bir sorgu parametresidir. @@ -223,7 +223,7 @@ Ve elbette, bazı parametreleri zorunlu, bazılarını varsayılan değerli ve b //// tab | Python 3.10+ ```Python hl_lines="8" -{!> ../../../docs_src/query_params/tutorial006_py310.py!} +{!> ../../docs_src/query_params/tutorial006_py310.py!} ``` //// @@ -231,7 +231,7 @@ Ve elbette, bazı parametreleri zorunlu, bazılarını varsayılan değerli ve b //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/query_params/tutorial006.py!} +{!> ../../docs_src/query_params/tutorial006.py!} ``` //// diff --git a/docs/tr/docs/tutorial/request-forms.md b/docs/tr/docs/tutorial/request-forms.md index 8e8ccfba4..19b6150ff 100644 --- a/docs/tr/docs/tutorial/request-forms.md +++ b/docs/tr/docs/tutorial/request-forms.md @@ -17,7 +17,7 @@ Formları kullanmak için öncelikle ../../../docs_src/request_forms/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ Formları kullanmak için öncelikle ../../../docs_src/request_forms/tutorial001_an.py!} +{!> ../../docs_src/request_forms/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="1" -{!> ../../../docs_src/request_forms/tutorial001.py!} +{!> ../../docs_src/request_forms/tutorial001.py!} ``` //// @@ -51,7 +51,7 @@ Form parametrelerini `Body` veya `Query` için yaptığınız gibi oluşturun: //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} +{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} ``` //// @@ -59,7 +59,7 @@ Form parametrelerini `Body` veya `Query` için yaptığınız gibi oluşturun: //// tab | Python 3.8+ ```Python hl_lines="8" -{!> ../../../docs_src/request_forms/tutorial001_an.py!} +{!> ../../docs_src/request_forms/tutorial001_an.py!} ``` //// @@ -73,7 +73,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="7" -{!> ../../../docs_src/request_forms/tutorial001.py!} +{!> ../../docs_src/request_forms/tutorial001.py!} ``` //// diff --git a/docs/tr/docs/tutorial/static-files.md b/docs/tr/docs/tutorial/static-files.md index b82be611f..8bff59744 100644 --- a/docs/tr/docs/tutorial/static-files.md +++ b/docs/tr/docs/tutorial/static-files.md @@ -8,7 +8,7 @@ * Bir `StaticFiles()` örneğini belirli bir yola bağlayın. ```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} +{!../../docs_src/static_files/tutorial001.py!} ``` /// note | "Teknik Detaylar" diff --git a/docs/uk/docs/python-types.md b/docs/uk/docs/python-types.md index 511a5264a..573b5372c 100644 --- a/docs/uk/docs/python-types.md +++ b/docs/uk/docs/python-types.md @@ -23,7 +23,7 @@ Python підтримує додаткові "підказки типу" ("type Давайте почнемо з простого прикладу: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Виклик цієї програми виводить: @@ -39,7 +39,7 @@ John Doe * Конкатенує їх разом із пробілом по середині. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Редагуйте це @@ -83,7 +83,7 @@ John Doe Це "type hints": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` Це не те саме, що оголошення значень за замовчуванням, як це було б з: @@ -113,7 +113,7 @@ John Doe Перевірте цю функцію, вона вже має анотацію типу: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Оскільки редактор знає типи змінних, ви не тільки отримаєте автозаповнення, ви також отримаєте перевірку помилок: @@ -123,7 +123,7 @@ John Doe Тепер ви знаєте, щоб виправити це, вам потрібно перетворити `age` у строку з допомогою `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Оголошення типів @@ -144,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Generic-типи з параметрами типів @@ -172,7 +172,7 @@ John Doe З модуля `typing`, імпортуємо `List` (з великої літери `L`): ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). @@ -182,7 +182,7 @@ John Doe Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: ```Python hl_lines="4" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` //// @@ -196,7 +196,7 @@ John Doe Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006_py39.py!} +{!> ../../docs_src/python_types/tutorial006_py39.py!} ``` //// @@ -234,7 +234,7 @@ John Doe //// tab | Python 3.8 і вище ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial007.py!} +{!> ../../docs_src/python_types/tutorial007.py!} ``` //// @@ -242,7 +242,7 @@ John Doe //// tab | Python 3.9 і вище ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial007_py39.py!} +{!> ../../docs_src/python_types/tutorial007_py39.py!} ``` //// @@ -263,7 +263,7 @@ John Doe //// tab | Python 3.8 і вище ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008.py!} +{!> ../../docs_src/python_types/tutorial008.py!} ``` //// @@ -271,7 +271,7 @@ John Doe //// tab | Python 3.9 і вище ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008_py39.py!} +{!> ../../docs_src/python_types/tutorial008_py39.py!} ``` //// @@ -293,7 +293,7 @@ John Doe //// tab | Python 3.8 і вище ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008b.py!} +{!> ../../docs_src/python_types/tutorial008b.py!} ``` //// @@ -301,7 +301,7 @@ John Doe //// tab | Python 3.10 і вище ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +{!> ../../docs_src/python_types/tutorial008b_py310.py!} ``` //// @@ -315,7 +315,7 @@ John Doe У Python 3.6 і вище (включаючи Python 3.10) ви можете оголосити його, імпортувавши та використовуючи `Optional` з модуля `typing`. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Використання `Optional[str]` замість просто `str` дозволить редактору допомогти вам виявити помилки, коли ви могли б вважати, що значенням завжди є `str`, хоча насправді воно також може бути `None`. @@ -327,7 +327,7 @@ John Doe //// tab | Python 3.8 і вище ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009.py!} +{!> ../../docs_src/python_types/tutorial009.py!} ``` //// @@ -335,7 +335,7 @@ John Doe //// tab | Python 3.8 і вище - альтернатива ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009b.py!} +{!> ../../docs_src/python_types/tutorial009b.py!} ``` //// @@ -343,7 +343,7 @@ John Doe //// tab | Python 3.10 і вище ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial009_py310.py!} +{!> ../../docs_src/python_types/tutorial009_py310.py!} ``` //// @@ -407,13 +407,13 @@ John Doe Скажімо, у вас є клас `Person` з імʼям: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Потім ви можете оголосити змінну типу `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` І знову ж таки, ви отримуєте всю підтримку редактора: @@ -437,7 +437,7 @@ John Doe //// tab | Python 3.8 і вище ```Python -{!> ../../../docs_src/python_types/tutorial011.py!} +{!> ../../docs_src/python_types/tutorial011.py!} ``` //// @@ -445,7 +445,7 @@ John Doe //// tab | Python 3.9 і вище ```Python -{!> ../../../docs_src/python_types/tutorial011_py39.py!} +{!> ../../docs_src/python_types/tutorial011_py39.py!} ``` //// @@ -453,7 +453,7 @@ John Doe //// tab | Python 3.10 і вище ```Python -{!> ../../../docs_src/python_types/tutorial011_py310.py!} +{!> ../../docs_src/python_types/tutorial011_py310.py!} ``` //// diff --git a/docs/uk/docs/tutorial/body-fields.md b/docs/uk/docs/tutorial/body-fields.md index e4d5b1fad..b1f645932 100644 --- a/docs/uk/docs/tutorial/body-fields.md +++ b/docs/uk/docs/tutorial/body-fields.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="2" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ /// ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// @@ -71,7 +71,7 @@ //// tab | Python 3.10+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -79,7 +79,7 @@ //// tab | Python 3.9+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -87,7 +87,7 @@ //// tab | Python 3.8+ ```Python hl_lines="12-15" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -101,7 +101,7 @@ /// ```Python hl_lines="9-12" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -115,7 +115,7 @@ /// ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// diff --git a/docs/uk/docs/tutorial/body.md b/docs/uk/docs/tutorial/body.md index 50fd76f84..1e4188831 100644 --- a/docs/uk/docs/tutorial/body.md +++ b/docs/uk/docs/tutorial/body.md @@ -25,7 +25,7 @@ //// tab | Python 3.8 і вище ```Python hl_lines="4" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -33,7 +33,7 @@ //// tab | Python 3.10 і вище ```Python hl_lines="2" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -47,7 +47,7 @@ //// tab | Python 3.8 і вище ```Python hl_lines="7-11" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -55,7 +55,7 @@ //// tab | Python 3.10 і вище ```Python hl_lines="5-9" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -89,7 +89,7 @@ //// tab | Python 3.8 і вище ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -97,7 +97,7 @@ //// tab | Python 3.10 і вище ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -170,7 +170,7 @@ //// tab | Python 3.8 і вище ```Python hl_lines="21" -{!> ../../../docs_src/body/tutorial002.py!} +{!> ../../docs_src/body/tutorial002.py!} ``` //// @@ -178,7 +178,7 @@ //// tab | Python 3.10 і вище ```Python hl_lines="19" -{!> ../../../docs_src/body/tutorial002_py310.py!} +{!> ../../docs_src/body/tutorial002_py310.py!} ``` //// @@ -192,7 +192,7 @@ //// tab | Python 3.8 і вище ```Python hl_lines="17-18" -{!> ../../../docs_src/body/tutorial003.py!} +{!> ../../docs_src/body/tutorial003.py!} ``` //// @@ -200,7 +200,7 @@ //// tab | Python 3.10 і вище ```Python hl_lines="15-16" -{!> ../../../docs_src/body/tutorial003_py310.py!} +{!> ../../docs_src/body/tutorial003_py310.py!} ``` //// @@ -214,7 +214,7 @@ //// tab | Python 3.8 і вище ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial004.py!} +{!> ../../docs_src/body/tutorial004.py!} ``` //// @@ -222,7 +222,7 @@ //// tab | Python 3.10 і вище ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial004_py310.py!} +{!> ../../docs_src/body/tutorial004_py310.py!} ``` //// diff --git a/docs/uk/docs/tutorial/cookie-params.md b/docs/uk/docs/tutorial/cookie-params.md index 4720a42ba..40ca4f6e6 100644 --- a/docs/uk/docs/tutorial/cookie-params.md +++ b/docs/uk/docs/tutorial/cookie-params.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ /// ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -67,7 +67,7 @@ //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -75,7 +75,7 @@ //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -83,7 +83,7 @@ //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -97,7 +97,7 @@ /// ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -111,7 +111,7 @@ /// ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// diff --git a/docs/uk/docs/tutorial/encoder.md b/docs/uk/docs/tutorial/encoder.md index 9ef8d5c5d..39dca9be8 100644 --- a/docs/uk/docs/tutorial/encoder.md +++ b/docs/uk/docs/tutorial/encoder.md @@ -23,7 +23,7 @@ //// tab | Python 3.10+ ```Python hl_lines="4 21" -{!> ../../../docs_src/encoder/tutorial001_py310.py!} +{!> ../../docs_src/encoder/tutorial001_py310.py!} ``` //// @@ -31,7 +31,7 @@ //// tab | Python 3.8+ ```Python hl_lines="5 22" -{!> ../../../docs_src/encoder/tutorial001.py!} +{!> ../../docs_src/encoder/tutorial001.py!} ``` //// diff --git a/docs/uk/docs/tutorial/extra-data-types.md b/docs/uk/docs/tutorial/extra-data-types.md index 54cbd4b00..5e6c364e4 100644 --- a/docs/uk/docs/tutorial/extra-data-types.md +++ b/docs/uk/docs/tutorial/extra-data-types.md @@ -58,7 +58,7 @@ //// tab | Python 3.10+ ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} ``` //// @@ -66,7 +66,7 @@ //// tab | Python 3.9+ ```Python hl_lines="1 3 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` //// @@ -74,7 +74,7 @@ //// tab | Python 3.8+ ```Python hl_lines="1 3 13-17" -{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} ``` //// @@ -88,7 +88,7 @@ /// ```Python hl_lines="1 2 11-15" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -102,7 +102,7 @@ /// ```Python hl_lines="1 2 12-16" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// @@ -112,7 +112,7 @@ //// tab | Python 3.10+ ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} ``` //// @@ -120,7 +120,7 @@ //// tab | Python 3.9+ ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} ``` //// @@ -128,7 +128,7 @@ //// tab | Python 3.8+ ```Python hl_lines="19-20" -{!> ../../../docs_src/extra_data_types/tutorial001_an.py!} +{!> ../../docs_src/extra_data_types/tutorial001_an.py!} ``` //// @@ -142,7 +142,7 @@ /// ```Python hl_lines="17-18" -{!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} +{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} ``` //// @@ -156,7 +156,7 @@ /// ```Python hl_lines="18-19" -{!> ../../../docs_src/extra_data_types/tutorial001.py!} +{!> ../../docs_src/extra_data_types/tutorial001.py!} ``` //// diff --git a/docs/uk/docs/tutorial/first-steps.md b/docs/uk/docs/tutorial/first-steps.md index 784da65f5..6f79c0d1d 100644 --- a/docs/uk/docs/tutorial/first-steps.md +++ b/docs/uk/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ Найпростіший файл FastAPI може виглядати так: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Скопіюйте це до файлу `main.py`. @@ -158,7 +158,7 @@ OpenAPI описує схему для вашого API. І ця схема вк ### Крок 1: імпортуємо `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` це клас у Python, який надає всю функціональність для API. @@ -174,7 +174,7 @@ OpenAPI описує схему для вашого API. І ця схема вк ### Крок 2: створюємо екземпляр `FastAPI` ```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Змінна `app` є екземпляром класу `FastAPI`. @@ -243,7 +243,7 @@ https://example.com/items/foo #### Визначте декоратор операції шляху (path operation decorator) ```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Декоратор `@app.get("/")` вказує **FastAPI**, що функція нижче, відповідає за обробку запитів, які надходять до неї: @@ -298,7 +298,7 @@ https://example.com/items/foo * **функція**: це функція, яка знаходиться нижче "декоратора" (нижче `@app.get("/")`). ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Це звичайна функція Python. @@ -312,7 +312,7 @@ FastAPI викликатиме її щоразу, коли отримає зап Ви також можете визначити її як звичайну функцію замість `async def`: ```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} +{!../../docs_src/first_steps/tutorial003.py!} ``` /// note | "Примітка" @@ -324,7 +324,7 @@ FastAPI викликатиме її щоразу, коли отримає зап ### Крок 5: поверніть результат ```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Ви можете повернути `dict`, `list`, а також окремі значення `str`, `int`, ітд. diff --git a/docs/vi/docs/python-types.md b/docs/vi/docs/python-types.md index 99d1d207f..275b0eb39 100644 --- a/docs/vi/docs/python-types.md +++ b/docs/vi/docs/python-types.md @@ -23,7 +23,7 @@ Nếu bạn là một chuyên gia về Python, và bạn đã biết mọi thứ Hãy bắt đầu với một ví dụ đơn giản: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` Kết quả khi gọi chương trình này: @@ -39,7 +39,7 @@ Hàm thực hiện như sau: * Nối chúng lại với nhau bằng một kí tự trắng ở giữa. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### Sửa đổi @@ -83,7 +83,7 @@ Chính là nó. Những thứ đó là "type hints": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` Đó không giống như khai báo những giá trị mặc định giống như: @@ -113,7 +113,7 @@ Với cái đó, bạn có thể cuộn, nhìn thấy các lựa chọn, cho đ Kiểm tra hàm này, nó đã có gợi ý kiểu dữ liệu: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` Bởi vì trình soạn thảo biết kiểu dữ liệu của các biến, bạn không chỉ có được completion, bạn cũng được kiểm tra lỗi: @@ -123,7 +123,7 @@ Bởi vì trình soạn thảo biết kiểu dữ liệu của các biến, bạ Bây giờ bạn biết rằng bạn phải sửa nó, chuyển `age` sang một xâu với `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## Khai báo các kiểu dữ liệu @@ -144,7 +144,7 @@ Bạn có thể sử dụng, ví dụ: * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### Các kiểu dữ liệu tổng quát với tham số kiểu dữ liệu @@ -182,7 +182,7 @@ Tương tự kiểu dữ liệu `list`. Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệu có sẵn, bạn đặt chúng trong các dấu ngoặc vuông: ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006_py39.py!} +{!> ../../docs_src/python_types/tutorial006_py39.py!} ``` //// @@ -192,7 +192,7 @@ Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệ Từ `typing`, import `List` (với chữ cái `L` viết hoa): ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` Khai báo biến với cùng dấu hai chấm (`:`). @@ -202,7 +202,7 @@ Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`. Như danh sách là một kiểu dữ liệu chứa các kiểu dữ liệu có sẵn, bạn đặt chúng bên trong dấu ngoặc vuông: ```Python hl_lines="4" -{!> ../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` //// @@ -240,7 +240,7 @@ Bạn sẽ làm điều tương tự để khai báo các `tuple` và các `set //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial007_py39.py!} +{!> ../../docs_src/python_types/tutorial007_py39.py!} ``` //// @@ -248,7 +248,7 @@ Bạn sẽ làm điều tương tự để khai báo các `tuple` và các `set //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial007.py!} +{!> ../../docs_src/python_types/tutorial007.py!} ``` //// @@ -269,7 +269,7 @@ Tham số kiểu dữ liệu thứ hai dành cho giá trị của `dict`. //// tab | Python 3.9+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008_py39.py!} +{!> ../../docs_src/python_types/tutorial008_py39.py!} ``` //// @@ -277,7 +277,7 @@ Tham số kiểu dữ liệu thứ hai dành cho giá trị của `dict`. //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008.py!} +{!> ../../docs_src/python_types/tutorial008.py!} ``` //// @@ -302,7 +302,7 @@ Trong Python 3.10 cũng có một **cú pháp mới** mà bạn có thể đặt //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial008b_py310.py!} +{!> ../../docs_src/python_types/tutorial008b_py310.py!} ``` //// @@ -310,7 +310,7 @@ Trong Python 3.10 cũng có một **cú pháp mới** mà bạn có thể đặt //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial008b.py!} +{!> ../../docs_src/python_types/tutorial008b.py!} ``` //// @@ -324,7 +324,7 @@ Bạn có thể khai báo một giá trị có thể có một kiểu dữ liệ Trong Python 3.6 hoặc lớn hơn (bao gồm Python 3.10) bạn có thể khai báo nó bằng các import và sử dụng `Optional` từ mô đun `typing`. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo giúp bạn phát hiện các lỗi mà bạn có thể gặp như một giá trị luôn là một `str`, trong khi thực tế nó rất có thể là `None`. @@ -336,7 +336,7 @@ Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo g //// tab | Python 3.10+ ```Python hl_lines="1" -{!> ../../../docs_src/python_types/tutorial009_py310.py!} +{!> ../../docs_src/python_types/tutorial009_py310.py!} ``` //// @@ -344,7 +344,7 @@ Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo g //// tab | Python 3.8+ ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009.py!} +{!> ../../docs_src/python_types/tutorial009.py!} ``` //// @@ -352,7 +352,7 @@ Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo g //// tab | Python 3.8+ alternative ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial009b.py!} +{!> ../../docs_src/python_types/tutorial009b.py!} ``` //// @@ -375,7 +375,7 @@ Nó chỉ là về các từ và tên. Nhưng những từ đó có thể ảnh Cho một ví dụ, hãy để ý hàm này: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c.py!} +{!../../docs_src/python_types/tutorial009c.py!} ``` Tham số `name` được định nghĩa là `Optional[str]`, nhưng nó **không phải là tùy chọn**, bạn không thể gọi hàm mà không có tham số: @@ -393,7 +393,7 @@ say_hi(name=None) # This works, None is valid 🎉 Tin tốt là, khi bạn sử dụng Python 3.10, bạn sẽ không phải lo lắng về điều đó, bạn sẽ có thể sử dụng `|` để định nghĩa hợp của các kiểu dữ liệu một cách đơn giản: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c_py310.py!} +{!../../docs_src/python_types/tutorial009c_py310.py!} ``` Và sau đó, bạn sẽ không phải lo rằng những cái tên như `Optional` và `Union`. 😎 @@ -458,13 +458,13 @@ Bạn cũng có thể khai báo một lớp như là kiểu dữ liệu của m Hãy nói rằng bạn muốn có một lớp `Person` với một tên: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Sau đó bạn có thể khai báo một biến có kiểu là `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` Và lại một lần nữa, bạn có được tất cả sự hỗ trợ từ trình soạn thảo: @@ -492,7 +492,7 @@ Một ví dụ từ tài liệu chính thức của Pydantic: //// tab | Python 3.10+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py310.py!} +{!> ../../docs_src/python_types/tutorial011_py310.py!} ``` //// @@ -500,7 +500,7 @@ Một ví dụ từ tài liệu chính thức của Pydantic: //// tab | Python 3.9+ ```Python -{!> ../../../docs_src/python_types/tutorial011_py39.py!} +{!> ../../docs_src/python_types/tutorial011_py39.py!} ``` //// @@ -508,7 +508,7 @@ Một ví dụ từ tài liệu chính thức của Pydantic: //// tab | Python 3.8+ ```Python -{!> ../../../docs_src/python_types/tutorial011.py!} +{!> ../../docs_src/python_types/tutorial011.py!} ``` //// @@ -538,7 +538,7 @@ Python cũng có một tính năng cho phép đặt **metadata bổ sung** trong Trong Python 3.9, `Annotated` là một phần của thư viện chuẩn, do đó bạn có thể import nó từ `typing`. ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial013_py39.py!} +{!> ../../docs_src/python_types/tutorial013_py39.py!} ``` //// @@ -550,7 +550,7 @@ Trong Python 3.9, `Annotated` là một phần của thư viện chuẩn, do đ Nó đã được cài đặt sẵng cùng với **FastAPI**. ```Python hl_lines="1 4" -{!> ../../../docs_src/python_types/tutorial013.py!} +{!> ../../docs_src/python_types/tutorial013.py!} ``` //// diff --git a/docs/vi/docs/tutorial/first-steps.md b/docs/vi/docs/tutorial/first-steps.md index ce808eb91..d80d78506 100644 --- a/docs/vi/docs/tutorial/first-steps.md +++ b/docs/vi/docs/tutorial/first-steps.md @@ -3,7 +3,7 @@ Tệp tin FastAPI đơn giản nhất có thể trông như này: ```Python -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` Sao chép sang một tệp tin `main.py`. @@ -134,7 +134,7 @@ Bạn cũng có thể sử dụng nó để sinh code tự động, với các c ### Bước 1: import `FastAPI` ```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} +{!../../docs_src/first_steps/tutorial001.py!} ``` `FastAPI` là một Python class cung cấp tất cả chức năng cho API của bạn. @@ -150,7 +150,7 @@ Bạn cũng có thể sử dụng tất cả `dataclasses`): ```Python hl_lines="1 7-12 19-20" -{!../../../docs_src/dataclasses/tutorial001.py!} +{!../../docs_src/dataclasses/tutorial001.py!} ``` 这还是借助于 **Pydantic** 及其内置的 `dataclasses`。 @@ -35,7 +35,7 @@ FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 在 `response_model` 参数中使用 `dataclasses`: ```Python hl_lines="1 7-13 19" -{!../../../docs_src/dataclasses/tutorial002.py!} +{!../../docs_src/dataclasses/tutorial002.py!} ``` 本例把数据类自动转换为 Pydantic 数据类。 @@ -53,7 +53,7 @@ API 文档中也会显示相关概图: 本例把标准的 `dataclasses` 直接替换为 `pydantic.dataclasses`: ```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } -{!../../../docs_src/dataclasses/tutorial003.py!} +{!../../docs_src/dataclasses/tutorial003.py!} ``` 1. 本例依然要从标准的 `dataclasses` 中导入 `field`; diff --git a/docs/zh/docs/advanced/events.md b/docs/zh/docs/advanced/events.md index c9389f533..e5b44f321 100644 --- a/docs/zh/docs/advanced/events.md +++ b/docs/zh/docs/advanced/events.md @@ -15,7 +15,7 @@ 使用 `startup` 事件声明 `app` 启动前运行的函数: ```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} +{!../../docs_src/events/tutorial001.py!} ``` 本例中,`startup` 事件处理器函数为项目数据库(只是**字典**)提供了一些初始值。 @@ -29,7 +29,7 @@ 使用 `shutdown` 事件声明 `app` 关闭时运行的函数: ```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} +{!../../docs_src/events/tutorial002.py!} ``` 此处,`shutdown` 事件处理器函数在 `log.txt` 中写入一行文本 `Application shutdown`。 diff --git a/docs/zh/docs/advanced/generate-clients.md b/docs/zh/docs/advanced/generate-clients.md index 56aad3bd2..baf131361 100644 --- a/docs/zh/docs/advanced/generate-clients.md +++ b/docs/zh/docs/advanced/generate-clients.md @@ -19,7 +19,7 @@ //// tab | Python 3.9+ ```Python hl_lines="7-9 12-13 16-17 21" -{!> ../../../docs_src/generate_clients/tutorial001_py39.py!} +{!> ../../docs_src/generate_clients/tutorial001_py39.py!} ``` //// @@ -27,7 +27,7 @@ //// tab | Python 3.8+ ```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../../docs_src/generate_clients/tutorial001.py!} +{!> ../../docs_src/generate_clients/tutorial001.py!} ``` //// @@ -138,7 +138,7 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app //// tab | Python 3.9+ ```Python hl_lines="21 26 34" -{!> ../../../docs_src/generate_clients/tutorial002_py39.py!} +{!> ../../docs_src/generate_clients/tutorial002_py39.py!} ``` //// @@ -146,7 +146,7 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app //// tab | Python 3.8+ ```Python hl_lines="23 28 36" -{!> ../../../docs_src/generate_clients/tutorial002.py!} +{!> ../../docs_src/generate_clients/tutorial002.py!} ``` //// @@ -199,7 +199,7 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** //// tab | Python 3.9+ ```Python hl_lines="6-7 10" -{!> ../../../docs_src/generate_clients/tutorial003_py39.py!} +{!> ../../docs_src/generate_clients/tutorial003_py39.py!} ``` //// @@ -207,7 +207,7 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** //// tab | Python 3.8+ ```Python hl_lines="8-9 12" -{!> ../../../docs_src/generate_clients/tutorial003.py!} +{!> ../../docs_src/generate_clients/tutorial003.py!} ``` //// @@ -233,7 +233,7 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** 我们可以将 OpenAPI JSON 下载到一个名为`openapi.json`的文件中,然后使用以下脚本**删除此前缀的标签**: ```Python -{!../../../docs_src/generate_clients/tutorial004.py!} +{!../../docs_src/generate_clients/tutorial004.py!} ``` 通过这样做,操作ID将从类似于 `items-get_items` 的名称重命名为 `get_items` ,这样客户端生成器就可以生成更简洁的方法名称。 diff --git a/docs/zh/docs/advanced/middleware.md b/docs/zh/docs/advanced/middleware.md index 926082b94..525dc89ac 100644 --- a/docs/zh/docs/advanced/middleware.md +++ b/docs/zh/docs/advanced/middleware.md @@ -58,7 +58,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 任何传向 `http` 或 `ws` 的请求都会被重定向至安全方案。 ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial001.py!} +{!../../docs_src/advanced_middleware/tutorial001.py!} ``` ## `TrustedHostMiddleware` @@ -66,7 +66,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 强制所有传入请求都必须正确设置 `Host` 请求头,以防 HTTP 主机头攻击。 ```Python hl_lines="2 6-8" -{!../../../docs_src/advanced_middleware/tutorial002.py!} +{!../../docs_src/advanced_middleware/tutorial002.py!} ``` 支持以下参数: @@ -82,7 +82,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 中间件会处理标准响应与流响应。 ```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial003.py!} +{!../../docs_src/advanced_middleware/tutorial003.py!} ``` 支持以下参数: diff --git a/docs/zh/docs/advanced/openapi-callbacks.md b/docs/zh/docs/advanced/openapi-callbacks.md index 7c7323cb5..dc1c2539b 100644 --- a/docs/zh/docs/advanced/openapi-callbacks.md +++ b/docs/zh/docs/advanced/openapi-callbacks.md @@ -32,7 +32,7 @@ API 的用户 (外部开发者)要在您的 API 内使用 POST 请求创建 这部分代码很常规,您对绝大多数代码应该都比较熟悉了: ```Python hl_lines="10-14 37-54" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` /// tip | "提示" @@ -93,7 +93,7 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) 首先,新建包含一些用于回调的 `APIRouter`。 ```Python hl_lines="5 26" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` ### 创建回调*路径操作* @@ -106,7 +106,7 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) * 还要声明要返回的响应,例如,`response_model=InvoiceEventReceived` ```Python hl_lines="17-19 22-23 29-33" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` 回调*路径操作*与常规*路径操作*有两点主要区别: @@ -176,7 +176,7 @@ JSON 请求体包含如下内容: 现在使用 API *路径操作装饰器*的参数 `callbacks`,从回调路由传递属性 `.routes`(实际上只是路由/路径操作的**列表**): ```Python hl_lines="36" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} +{!../../docs_src/openapi_callbacks/tutorial001.py!} ``` /// tip | "提示" diff --git a/docs/zh/docs/advanced/path-operation-advanced-configuration.md b/docs/zh/docs/advanced/path-operation-advanced-configuration.md index c37846916..0d77dd69e 100644 --- a/docs/zh/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/zh/docs/advanced/path-operation-advanced-configuration.md @@ -13,7 +13,7 @@ 务必确保每个操作路径的 `operation_id` 都是唯一的。 ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} ``` ### 使用 *路径操作函数* 的函数名作为 operationId @@ -23,7 +23,7 @@ 你应该在添加了所有 *路径操作* 之后执行此操作。 ```Python hl_lines="2 12 13 14 15 16 17 18 19 20 21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` /// tip @@ -45,7 +45,7 @@ 使用参数 `include_in_schema` 并将其设置为 `False` ,来从生成的 OpenAPI 方案中排除一个 *路径操作*(这样一来,就从自动化文档系统中排除掉了)。 ```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} ``` ## docstring 的高级描述 @@ -58,5 +58,5 @@ ```Python hl_lines="19 20 21 22 23 24 25 26 27 28 29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} +{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} ``` diff --git a/docs/zh/docs/advanced/response-change-status-code.md b/docs/zh/docs/advanced/response-change-status-code.md index a289cf201..c38f80f1f 100644 --- a/docs/zh/docs/advanced/response-change-status-code.md +++ b/docs/zh/docs/advanced/response-change-status-code.md @@ -21,7 +21,7 @@ 然后你可以在这个*临时*响应对象中设置`status_code`。 ```Python hl_lines="1 9 12" -{!../../../docs_src/response_change_status_code/tutorial001.py!} +{!../../docs_src/response_change_status_code/tutorial001.py!} ``` 然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。 diff --git a/docs/zh/docs/advanced/response-cookies.md b/docs/zh/docs/advanced/response-cookies.md index dd942a981..5772664b0 100644 --- a/docs/zh/docs/advanced/response-cookies.md +++ b/docs/zh/docs/advanced/response-cookies.md @@ -5,7 +5,7 @@ 你可以在 *路径函数* 中定义一个类型为 `Response`的参数,这样你就可以在这个临时响应对象中设置cookie了。 ```Python hl_lines="1 8-9" -{!../../../docs_src/response_cookies/tutorial002.py!} +{!../../docs_src/response_cookies/tutorial002.py!} ``` 而且你还可以根据你的需要响应不同的对象,比如常用的 `dict`,数据库model等。 @@ -25,7 +25,7 @@ 然后设置Cookies,并返回: ```Python hl_lines="10-12" -{!../../../docs_src/response_cookies/tutorial001.py!} +{!../../docs_src/response_cookies/tutorial001.py!} ``` /// tip diff --git a/docs/zh/docs/advanced/response-directly.md b/docs/zh/docs/advanced/response-directly.md index b2c7de8fd..9d191c622 100644 --- a/docs/zh/docs/advanced/response-directly.md +++ b/docs/zh/docs/advanced/response-directly.md @@ -36,7 +36,7 @@ ```Python hl_lines="4 6 20 21" -{!../../../docs_src/response_directly/tutorial001.py!} +{!../../docs_src/response_directly/tutorial001.py!} ``` /// note | "技术细节" @@ -58,7 +58,7 @@ 你可以把你的 XML 内容放到一个字符串中,放到一个 `Response` 中,然后返回。 ```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} +{!../../docs_src/response_directly/tutorial002.py!} ``` ## 说明 diff --git a/docs/zh/docs/advanced/response-headers.md b/docs/zh/docs/advanced/response-headers.md index e18d1620d..d593fdccc 100644 --- a/docs/zh/docs/advanced/response-headers.md +++ b/docs/zh/docs/advanced/response-headers.md @@ -6,7 +6,7 @@ 然后你可以在这个*临时*响应对象中设置头部。 ```Python hl_lines="1 7-8" -{!../../../docs_src/response_headers/tutorial002.py!} +{!../../docs_src/response_headers/tutorial002.py!} ``` 然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。 @@ -21,7 +21,7 @@ 按照[直接返回响应](response-directly.md){.internal-link target=_blank}中所述创建响应,并将头部作为附加参数传递: ```Python hl_lines="10-12" -{!../../../docs_src/response_headers/tutorial001.py!} +{!../../docs_src/response_headers/tutorial001.py!} ``` diff --git a/docs/zh/docs/advanced/security/http-basic-auth.md b/docs/zh/docs/advanced/security/http-basic-auth.md index a76353186..06c6dbbab 100644 --- a/docs/zh/docs/advanced/security/http-basic-auth.md +++ b/docs/zh/docs/advanced/security/http-basic-auth.md @@ -23,7 +23,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 //// tab | Python 3.9+ ```Python hl_lines="4 8 12" -{!> ../../../docs_src/security/tutorial006_an_py39.py!} +{!> ../../docs_src/security/tutorial006_an_py39.py!} ``` //// @@ -31,7 +31,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 //// tab | Python 3.8+ ```Python hl_lines="2 7 11" -{!> ../../../docs_src/security/tutorial006_an.py!} +{!> ../../docs_src/security/tutorial006_an.py!} ``` //// @@ -45,7 +45,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 /// ```Python hl_lines="2 6 10" -{!> ../../../docs_src/security/tutorial006.py!} +{!> ../../docs_src/security/tutorial006.py!} ``` //// @@ -71,7 +71,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 //// tab | Python 3.9+ ```Python hl_lines="1 12-24" -{!> ../../../docs_src/security/tutorial007_an_py39.py!} +{!> ../../docs_src/security/tutorial007_an_py39.py!} ``` //// @@ -79,7 +79,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 //// tab | Python 3.8+ ```Python hl_lines="1 12-24" -{!> ../../../docs_src/security/tutorial007_an.py!} +{!> ../../docs_src/security/tutorial007_an.py!} ``` //// @@ -93,7 +93,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 /// ```Python hl_lines="1 11-21" -{!> ../../../docs_src/security/tutorial007.py!} +{!> ../../docs_src/security/tutorial007.py!} ``` //// @@ -163,7 +163,7 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": //// tab | Python 3.9+ ```Python hl_lines="26-30" -{!> ../../../docs_src/security/tutorial007_an_py39.py!} +{!> ../../docs_src/security/tutorial007_an_py39.py!} ``` //// @@ -171,7 +171,7 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": //// tab | Python 3.8+ ```Python hl_lines="26-30" -{!> ../../../docs_src/security/tutorial007_an.py!} +{!> ../../docs_src/security/tutorial007_an.py!} ``` //// @@ -185,7 +185,7 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": /// ```Python hl_lines="23-27" -{!> ../../../docs_src/security/tutorial007.py!} +{!> ../../docs_src/security/tutorial007.py!} ``` //// diff --git a/docs/zh/docs/advanced/security/oauth2-scopes.md b/docs/zh/docs/advanced/security/oauth2-scopes.md index b75ae11a4..d6354230e 100644 --- a/docs/zh/docs/advanced/security/oauth2-scopes.md +++ b/docs/zh/docs/advanced/security/oauth2-scopes.md @@ -63,7 +63,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 首先,快速浏览一下以下代码与**用户指南**中 [OAuth2 实现密码哈希与 Bearer JWT 令牌验证](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}一章中代码的区别。以下代码使用 OAuth2 作用域: ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` 下面,我们逐步说明修改的代码内容。 @@ -75,7 +75,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 `scopes` 参数接收**字典**,键是作用域、值是作用域的描述: ```Python hl_lines="62-65" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` 因为声明了作用域,所以登录或授权时会在 API 文档中显示。 @@ -103,7 +103,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 /// ```Python hl_lines="153" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 在*路径操作*与依赖项中声明作用域 @@ -131,7 +131,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 /// ```Python hl_lines="4 139 166" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` /// info | "技术细节" @@ -159,7 +159,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 `SecuriScopes` 类与 `Request` 类似(`Request` 用于直接提取请求对象)。 ```Python hl_lines="8 105" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 使用 `scopes` @@ -175,7 +175,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 该异常包含了作用域所需的(如有),以空格分割的字符串(使用 `scope_str`)。该字符串要放到包含作用域的 `WWW-Authenticate` 请求头中(这也是规范的要求)。 ```Python hl_lines="105 107-115" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 校验 `username` 与数据形状 @@ -193,7 +193,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 还可以使用用户名验证用户,如果没有用户,也会触发之前创建的异常。 ```Python hl_lines="46 116-127" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 校验 `scopes` @@ -203,7 +203,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 为此,要使用包含所有作用域**字符串列表**的 `security_scopes.scopes`, 。 ```Python hl_lines="128-134" -{!../../../docs_src/security/tutorial005.py!} +{!../../docs_src/security/tutorial005.py!} ``` ## 依赖项树与作用域 diff --git a/docs/zh/docs/advanced/settings.md b/docs/zh/docs/advanced/settings.md index 37a2d98d3..4d35731cb 100644 --- a/docs/zh/docs/advanced/settings.md +++ b/docs/zh/docs/advanced/settings.md @@ -151,7 +151,7 @@ Hello World from Python 您可以使用与 Pydantic 模型相同的验证功能和工具,比如不同的数据类型和使用 `Field()` 进行附加验证。 ```Python hl_lines="2 5-8 11" -{!../../../docs_src/settings/tutorial001.py!} +{!../../docs_src/settings/tutorial001.py!} ``` /// tip @@ -169,7 +169,7 @@ Hello World from Python 然后,您可以在应用程序中使用新的 `settings` 对象: ```Python hl_lines="18-20" -{!../../../docs_src/settings/tutorial001.py!} +{!../../docs_src/settings/tutorial001.py!} ``` ### 运行服务器 @@ -205,13 +205,13 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 例如,您可以创建一个名为 `config.py` 的文件,其中包含以下内容: ```Python -{!../../../docs_src/settings/app01/config.py!} +{!../../docs_src/settings/app01/config.py!} ``` 然后在一个名为 `main.py` 的文件中使用它: ```Python hl_lines="3 11-13" -{!../../../docs_src/settings/app01/main.py!} +{!../../docs_src/settings/app01/main.py!} ``` /// tip @@ -231,7 +231,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 根据前面的示例,您的 `config.py` 文件可能如下所示: ```Python hl_lines="10" -{!../../../docs_src/settings/app02/config.py!} +{!../../docs_src/settings/app02/config.py!} ``` 请注意,现在我们不创建默认实例 `settings = Settings()`。 @@ -243,7 +243,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app //// tab | Python 3.9+ ```Python hl_lines="6 12-13" -{!> ../../../docs_src/settings/app02_an_py39/main.py!} +{!> ../../docs_src/settings/app02_an_py39/main.py!} ``` //// @@ -251,7 +251,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app //// tab | Python 3.8+ ```Python hl_lines="6 12-13" -{!> ../../../docs_src/settings/app02_an/main.py!} +{!> ../../docs_src/settings/app02_an/main.py!} ``` //// @@ -265,7 +265,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app /// ```Python hl_lines="5 11-12" -{!> ../../../docs_src/settings/app02/main.py!} +{!> ../../docs_src/settings/app02/main.py!} ``` //// @@ -283,7 +283,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app //// tab | Python 3.9+ ```Python hl_lines="17 19-21" -{!> ../../../docs_src/settings/app02_an_py39/main.py!} +{!> ../../docs_src/settings/app02_an_py39/main.py!} ``` //// @@ -291,7 +291,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app //// tab | Python 3.8+ ```Python hl_lines="17 19-21" -{!> ../../../docs_src/settings/app02_an/main.py!} +{!> ../../docs_src/settings/app02_an/main.py!} ``` //// @@ -305,7 +305,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app /// ```Python hl_lines="16 18-20" -{!> ../../../docs_src/settings/app02/main.py!} +{!> ../../docs_src/settings/app02/main.py!} ``` //// @@ -315,7 +315,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 然后,在测试期间,通过创建 `get_settings` 的依赖项覆盖,很容易提供一个不同的设置对象: ```Python hl_lines="9-10 13 21" -{!../../../docs_src/settings/app02/test_main.py!} +{!../../docs_src/settings/app02/test_main.py!} ``` 在依赖项覆盖中,我们在创建新的 `Settings` 对象时为 `admin_email` 设置了一个新值,然后返回该新对象。 @@ -358,7 +358,7 @@ APP_NAME="ChimichangApp" 然后,您可以使用以下方式更新您的 `config.py`: ```Python hl_lines="9-10" -{!../../../docs_src/settings/app03/config.py!} +{!../../docs_src/settings/app03/config.py!} ``` 在这里,我们在 Pydantic 的 `Settings` 类中创建了一个名为 `Config` 的类,并将 `env_file` 设置为我们想要使用的 dotenv 文件的文件名。 @@ -395,7 +395,7 @@ def get_settings(): //// tab | Python 3.9+ ```Python hl_lines="1 11" -{!> ../../../docs_src/settings/app03_an_py39/main.py!} +{!> ../../docs_src/settings/app03_an_py39/main.py!} ``` //// @@ -403,7 +403,7 @@ def get_settings(): //// tab | Python 3.8+ ```Python hl_lines="1 11" -{!> ../../../docs_src/settings/app03_an/main.py!} +{!> ../../docs_src/settings/app03_an/main.py!} ``` //// @@ -417,7 +417,7 @@ def get_settings(): /// ```Python hl_lines="1 10" -{!> ../../../docs_src/settings/app03/main.py!} +{!> ../../docs_src/settings/app03/main.py!} ``` //// diff --git a/docs/zh/docs/advanced/sub-applications.md b/docs/zh/docs/advanced/sub-applications.md index a26301b50..f93ab1d24 100644 --- a/docs/zh/docs/advanced/sub-applications.md +++ b/docs/zh/docs/advanced/sub-applications.md @@ -11,7 +11,7 @@ 首先,创建主(顶层)**FastAPI** 应用及其*路径操作*: ```Python hl_lines="3 6-8" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### 子应用 @@ -21,7 +21,7 @@ 子应用只是另一个标准 FastAPI 应用,但这个应用是被**挂载**的应用: ```Python hl_lines="11 14-16" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### 挂载子应用 @@ -31,7 +31,7 @@ 本例的子应用挂载在 `/subapi` 路径下: ```Python hl_lines="11 19" -{!../../../docs_src/sub_applications/tutorial001.py!} +{!../../docs_src/sub_applications/tutorial001.py!} ``` ### 查看文档 diff --git a/docs/zh/docs/advanced/templates.md b/docs/zh/docs/advanced/templates.md index b09644e39..1159302a9 100644 --- a/docs/zh/docs/advanced/templates.md +++ b/docs/zh/docs/advanced/templates.md @@ -28,7 +28,7 @@ $ pip install jinja2 * 使用 `templates` 渲染并返回 `TemplateResponse`, 传递模板的名称、request对象以及一个包含多个键值对(用于Jinja2模板)的"context"字典, ```Python hl_lines="4 11 15-16" -{!../../../docs_src/templates/tutorial001.py!} +{!../../docs_src/templates/tutorial001.py!} ``` /// note | "笔记" @@ -57,7 +57,7 @@ $ pip install jinja2 编写模板 `templates/item.html`,代码如下: ```jinja hl_lines="7" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` ### 模板上下文 @@ -111,13 +111,13 @@ Item ID: 42 你还可以在模板内部将 `url_for()`用于静态文件,例如你挂载的 `name="static"`的 `StaticFiles`。 ```jinja hl_lines="4" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` 本例中,它将链接到 `static/styles.css`中的CSS文件: ```CSS hl_lines="4" -{!../../../docs_src/templates/static/styles.css!} +{!../../docs_src/templates/static/styles.css!} ``` 因为使用了 `StaticFiles`, **FastAPI** 应用会自动提供位于 URL `/static/styles.css`的 CSS 文件。 diff --git a/docs/zh/docs/advanced/testing-database.md b/docs/zh/docs/advanced/testing-database.md index 58bf9af8c..ecab4f65b 100644 --- a/docs/zh/docs/advanced/testing-database.md +++ b/docs/zh/docs/advanced/testing-database.md @@ -49,7 +49,7 @@ 但其余的会话代码基本上都是一样的,只要复制就可以了。 ```Python hl_lines="8-13" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` /// tip | "提示" @@ -73,7 +73,7 @@ Base.metadata.create_all(bind=engine) 因此,要在测试代码中添加这行代码创建新的数据库文件。 ```Python hl_lines="16" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` ## 覆盖依赖项 @@ -81,7 +81,7 @@ Base.metadata.create_all(bind=engine) 接下来,创建覆盖依赖项,并为应用添加覆盖内容。 ```Python hl_lines="19-24 27" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` /// tip | "提示" @@ -95,7 +95,7 @@ Base.metadata.create_all(bind=engine) 然后,就可以正常测试了。 ```Python hl_lines="32-47" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} +{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} ``` 测试期间,所有在数据库中所做的修改都在 `test.db` 里,不会影响主应用的 `sql_app.db`。 diff --git a/docs/zh/docs/advanced/testing-dependencies.md b/docs/zh/docs/advanced/testing-dependencies.md index cc9a38200..c3d912e2f 100644 --- a/docs/zh/docs/advanced/testing-dependencies.md +++ b/docs/zh/docs/advanced/testing-dependencies.md @@ -29,7 +29,7 @@ 这样一来,**FastAPI** 就会调用覆盖依赖项,不再调用原依赖项。 ```Python hl_lines="26-27 30" -{!../../../docs_src/dependency_testing/tutorial001.py!} +{!../../docs_src/dependency_testing/tutorial001.py!} ``` /// tip | "提示" diff --git a/docs/zh/docs/advanced/testing-events.md b/docs/zh/docs/advanced/testing-events.md index 222a67c8c..00e661cd2 100644 --- a/docs/zh/docs/advanced/testing-events.md +++ b/docs/zh/docs/advanced/testing-events.md @@ -3,5 +3,5 @@ 使用 `TestClient` 和 `with` 语句,在测试中运行事件处理器(`startup` 与 `shutdown`)。 ```Python hl_lines="9-12 20-24" -{!../../../docs_src/app_testing/tutorial003.py!} +{!../../docs_src/app_testing/tutorial003.py!} ``` diff --git a/docs/zh/docs/advanced/testing-websockets.md b/docs/zh/docs/advanced/testing-websockets.md index 795b73945..a69053f24 100644 --- a/docs/zh/docs/advanced/testing-websockets.md +++ b/docs/zh/docs/advanced/testing-websockets.md @@ -5,7 +5,7 @@ 为此,要在 `with` 语句中使用 `TestClient` 连接 WebSocket。 ```Python hl_lines="27-31" -{!../../../docs_src/app_testing/tutorial002.py!} +{!../../docs_src/app_testing/tutorial002.py!} ``` /// note | "笔记" diff --git a/docs/zh/docs/advanced/using-request-directly.md b/docs/zh/docs/advanced/using-request-directly.md index bc9e898d9..992458217 100644 --- a/docs/zh/docs/advanced/using-request-directly.md +++ b/docs/zh/docs/advanced/using-request-directly.md @@ -30,7 +30,7 @@ 此时,需要直接访问请求。 ```Python hl_lines="1 7-8" -{!../../../docs_src/using_request_directly/tutorial001.py!} +{!../../docs_src/using_request_directly/tutorial001.py!} ``` 把*路径操作函数*的参数类型声明为 `Request`,**FastAPI** 就能把 `Request` 传递到参数里。 diff --git a/docs/zh/docs/advanced/websockets.md b/docs/zh/docs/advanced/websockets.md index 3fcc36dfe..15ae84c58 100644 --- a/docs/zh/docs/advanced/websockets.md +++ b/docs/zh/docs/advanced/websockets.md @@ -35,7 +35,7 @@ $ pip install websockets 但这是一种专注于 WebSockets 的服务器端并提供一个工作示例的最简单方式: ```Python hl_lines="2 6-38 41-43" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` ## 创建 `websocket` @@ -43,7 +43,7 @@ $ pip install websockets 在您的 **FastAPI** 应用程序中,创建一个 `websocket`: ```Python hl_lines="1 46-47" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` /// note | "技术细节" @@ -59,7 +59,7 @@ $ pip install websockets 在您的 WebSocket 路由中,您可以使用 `await` 等待消息并发送消息。 ```Python hl_lines="48-52" -{!../../../docs_src/websockets/tutorial001.py!} +{!../../docs_src/websockets/tutorial001.py!} ``` 您可以接收和发送二进制、文本和 JSON 数据。 @@ -112,7 +112,7 @@ $ uvicorn main:app --reload //// tab | Python 3.10+ ```Python hl_lines="68-69 82" -{!> ../../../docs_src/websockets/tutorial002_an_py310.py!} +{!> ../../docs_src/websockets/tutorial002_an_py310.py!} ``` //// @@ -120,7 +120,7 @@ $ uvicorn main:app --reload //// tab | Python 3.9+ ```Python hl_lines="68-69 82" -{!> ../../../docs_src/websockets/tutorial002_an_py39.py!} +{!> ../../docs_src/websockets/tutorial002_an_py39.py!} ``` //// @@ -128,7 +128,7 @@ $ uvicorn main:app --reload //// tab | Python 3.8+ ```Python hl_lines="69-70 83" -{!> ../../../docs_src/websockets/tutorial002_an.py!} +{!> ../../docs_src/websockets/tutorial002_an.py!} ``` //// @@ -142,7 +142,7 @@ $ uvicorn main:app --reload /// ```Python hl_lines="66-67 79" -{!> ../../../docs_src/websockets/tutorial002_py310.py!} +{!> ../../docs_src/websockets/tutorial002_py310.py!} ``` //// @@ -156,7 +156,7 @@ $ uvicorn main:app --reload /// ```Python hl_lines="68-69 81" -{!> ../../../docs_src/websockets/tutorial002.py!} +{!> ../../docs_src/websockets/tutorial002.py!} ``` //// @@ -203,7 +203,7 @@ $ uvicorn main:app --reload //// tab | Python 3.9+ ```Python hl_lines="79-81" -{!> ../../../docs_src/websockets/tutorial003_py39.py!} +{!> ../../docs_src/websockets/tutorial003_py39.py!} ``` //// @@ -211,7 +211,7 @@ $ uvicorn main:app --reload //// tab | Python 3.8+ ```Python hl_lines="81-83" -{!> ../../../docs_src/websockets/tutorial003.py!} +{!> ../../docs_src/websockets/tutorial003.py!} ``` //// diff --git a/docs/zh/docs/advanced/wsgi.md b/docs/zh/docs/advanced/wsgi.md index 179ec88aa..92bd998d0 100644 --- a/docs/zh/docs/advanced/wsgi.md +++ b/docs/zh/docs/advanced/wsgi.md @@ -13,7 +13,7 @@ 之后将其挂载到某一个路径下。 ```Python hl_lines="2-3 22" -{!../../../docs_src/wsgi/tutorial001.py!} +{!../../docs_src/wsgi/tutorial001.py!} ``` ## 检查 diff --git a/docs/zh/docs/how-to/configure-swagger-ui.md b/docs/zh/docs/how-to/configure-swagger-ui.md index 17f89b22f..1a2daeec1 100644 --- a/docs/zh/docs/how-to/configure-swagger-ui.md +++ b/docs/zh/docs/how-to/configure-swagger-ui.md @@ -19,7 +19,7 @@ FastAPI会将这些配置转换为 **JSON**,使其与 JavaScript 兼容,因 但是你可以通过设置 `syntaxHighlight` 为 `False` 来禁用 Swagger UI 中的语法高亮: ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial001.py!} +{!../../docs_src/configure_swagger_ui/tutorial001.py!} ``` ...在此之后,Swagger UI 将不会高亮代码: @@ -31,7 +31,7 @@ FastAPI会将这些配置转换为 **JSON**,使其与 JavaScript 兼容,因 同样地,你也可以通过设置键 `"syntaxHighlight.theme"` 来设置语法高亮主题(注意中间有一个点): ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial002.py!} +{!../../docs_src/configure_swagger_ui/tutorial002.py!} ``` 这个配置会改变语法高亮主题: @@ -45,7 +45,7 @@ FastAPI 包含了一些默认配置参数,适用于大多数用例。 其包括这些默认配置参数: ```Python -{!../../../fastapi/openapi/docs.py[ln:7-23]!} +{!../../fastapi/openapi/docs.py[ln:7-23]!} ``` 你可以通过在 `swagger_ui_parameters` 中设置不同的值来覆盖它们。 @@ -53,7 +53,7 @@ FastAPI 包含了一些默认配置参数,适用于大多数用例。 比如,如果要禁用 `deepLinking`,你可以像这样传递设置到 `swagger_ui_parameters` 中: ```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial003.py!} +{!../../docs_src/configure_swagger_ui/tutorial003.py!} ``` ## 其他 Swagger UI 参数 diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md index c78852539..dab6bd4c0 100644 --- a/docs/zh/docs/python-types.md +++ b/docs/zh/docs/python-types.md @@ -23,7 +23,7 @@ 让我们从一个简单的例子开始: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` 运行这段程序将输出: @@ -39,7 +39,7 @@ John Doe * 中间用一个空格来拼接它们。 ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### 修改示例 @@ -83,7 +83,7 @@ John Doe 这些就是"类型提示": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` 这和声明默认值是不同的,例如: @@ -113,7 +113,7 @@ John Doe 下面是一个已经有类型提示的函数: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` 因为编辑器已经知道了这些变量的类型,所以不仅能对代码进行补全,还能检查其中的错误: @@ -123,7 +123,7 @@ John Doe 现在你知道了必须先修复这个问题,通过 `str(age)` 把 `age` 转换成字符串: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## 声明类型 @@ -144,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### 嵌套类型 @@ -162,7 +162,7 @@ John Doe 从 `typing` 模块导入 `List`(注意是大写的 `L`): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` 同样以冒号(`:`)来声明这个变量。 @@ -172,7 +172,7 @@ John Doe 由于列表是带有"子类型"的类型,所以我们把子类型放在方括号中: ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!../../docs_src/python_types/tutorial006.py!} ``` 这表示:"变量 `items` 是一个 `list`,并且这个列表里的每一个元素都是 `str`"。 @@ -192,7 +192,7 @@ John Doe 声明 `tuple` 和 `set` 的方法也是一样的: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!../../docs_src/python_types/tutorial007.py!} ``` 这表示: @@ -209,7 +209,7 @@ John Doe 第二个子类型声明 `dict` 的所有值: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!../../docs_src/python_types/tutorial008.py!} ``` 这表示: @@ -225,13 +225,13 @@ John Doe 假设你有一个名为 `Person` 的类,拥有 name 属性: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` 接下来,你可以将一个变量声明为 `Person` 类型: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` 然后,你将再次获得所有的编辑器支持: @@ -253,7 +253,7 @@ John Doe 下面的例子来自 Pydantic 官方文档: ```Python -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` /// info diff --git a/docs/zh/docs/tutorial/background-tasks.md b/docs/zh/docs/tutorial/background-tasks.md index 95fd7b6b5..fc9312bc5 100644 --- a/docs/zh/docs/tutorial/background-tasks.md +++ b/docs/zh/docs/tutorial/background-tasks.md @@ -16,7 +16,7 @@ 首先导入 `BackgroundTasks` 并在 *路径操作函数* 中使用类型声明 `BackgroundTasks` 定义一个参数: ```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` **FastAPI** 会创建一个 `BackgroundTasks` 类型的对象并作为该参数传入。 @@ -34,7 +34,7 @@ 由于写操作不使用 `async` 和 `await`,我们用普通的 `def` 定义函数: ```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` ## 添加后台任务 @@ -42,7 +42,7 @@ 在你的 *路径操作函数* 里,用 `.add_task()` 方法将任务函数传到 *后台任务* 对象中: ```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} +{!../../docs_src/background_tasks/tutorial001.py!} ``` `.add_task()` 接收以下参数: @@ -60,7 +60,7 @@ //// tab | Python 3.10+ ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} +{!> ../../docs_src/background_tasks/tutorial002_an_py310.py!} ``` //// @@ -68,7 +68,7 @@ //// tab | Python 3.9+ ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} +{!> ../../docs_src/background_tasks/tutorial002_an_py39.py!} ``` //// @@ -76,7 +76,7 @@ //// tab | Python 3.8+ ```Python hl_lines="14 16 23 26" -{!> ../../../docs_src/background_tasks/tutorial002_an.py!} +{!> ../../docs_src/background_tasks/tutorial002_an.py!} ``` //// @@ -90,7 +90,7 @@ /// ```Python hl_lines="11 13 20 23" -{!> ../../../docs_src/background_tasks/tutorial002_py310.py!} +{!> ../../docs_src/background_tasks/tutorial002_py310.py!} ``` //// @@ -104,7 +104,7 @@ /// ```Python hl_lines="13 15 22 25" -{!> ../../../docs_src/background_tasks/tutorial002.py!} +{!> ../../docs_src/background_tasks/tutorial002.py!} ``` //// diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md index a0c7095e9..64afd99af 100644 --- a/docs/zh/docs/tutorial/bigger-applications.md +++ b/docs/zh/docs/tutorial/bigger-applications.md @@ -86,7 +86,7 @@ from app.routers import items 你可以导入它并通过与 `FastAPI` 类相同的方式创建一个「实例」: ```Python hl_lines="1 3" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` ### 使用 `APIRouter` 的*路径操作* @@ -96,7 +96,7 @@ from app.routers import items 使用方式与 `FastAPI` 类相同: ```Python hl_lines="6 11 16" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` 你可以将 `APIRouter` 视为一个「迷你 `FastAPI`」类。 @@ -122,7 +122,7 @@ from app.routers import items 现在我们将使用一个简单的依赖项来读取一个自定义的 `X-Token` 请求首部: ```Python hl_lines="1 4-6" title="app/dependencies.py" -{!../../../docs_src/bigger_applications/app/dependencies.py!} +{!../../docs_src/bigger_applications/app/dependencies.py!} ``` /// tip @@ -156,7 +156,7 @@ from app.routers import items 因此,我们可以将其添加到 `APIRouter` 中,而不是将其添加到每个路径操作中。 ```Python hl_lines="5-10 16 21" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` 由于每个*路径操作*的路径都必须以 `/` 开头,例如: @@ -217,7 +217,7 @@ async def read_item(item_id: str): 因此,我们通过 `..` 对依赖项使用了相对导入: ```Python hl_lines="3" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` #### 相对导入如何工作 @@ -290,7 +290,7 @@ from ...dependencies import get_token_header 但是我们仍然可以添加*更多*将会应用于特定的*路径操作*的 `tags`,以及一些特定于该*路径操作*的额外 `responses`: ```Python hl_lines="30-31" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` /// tip @@ -318,7 +318,7 @@ from ...dependencies import get_token_header 我们甚至可以声明[全局依赖项](dependencies/global-dependencies.md){.internal-link target=_blank},它会和每个 `APIRouter` 的依赖项组合在一起: ```Python hl_lines="1 3 7" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### 导入 `APIRouter` @@ -326,7 +326,7 @@ from ...dependencies import get_token_header 现在,我们导入具有 `APIRouter` 的其他子模块: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 由于文件 `app/routers/users.py` 和 `app/routers/items.py` 是同一 Python 包 `app` 一个部分的子模块,因此我们可以使用单个点 ` .` 通过「相对导入」来导入它们。 @@ -391,7 +391,7 @@ from .routers.users import router 因此,为了能够在同一个文件中使用它们,我们直接导入子模块: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### 包含 `users` 和 `items` 的 `APIRouter` @@ -399,7 +399,7 @@ from .routers.users import router 现在,让我们来包含来自 `users` 和 `items` 子模块的 `router`。 ```Python hl_lines="10-11" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` /// info @@ -441,7 +441,7 @@ from .routers.users import router 对于此示例,它将非常简单。但是假设由于它是与组织中的其他项目所共享的,因此我们无法对其进行修改,以及直接在 `APIRouter` 中添加 `prefix`、`dependencies`、`tags` 等: ```Python hl_lines="3" title="app/internal/admin.py" -{!../../../docs_src/bigger_applications/app/internal/admin.py!} +{!../../docs_src/bigger_applications/app/internal/admin.py!} ``` 但是我们仍然希望在包含 `APIRouter` 时设置一个自定义的 `prefix`,以便其所有*路径操作*以 `/admin` 开头,我们希望使用本项目已经有的 `dependencies` 保护它,并且我们希望它包含自定义的 `tags` 和 `responses`。 @@ -449,7 +449,7 @@ from .routers.users import router 我们可以通过将这些参数传递给 `app.include_router()` 来完成所有的声明,而不必修改原始的 `APIRouter`: ```Python hl_lines="14-17" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 这样,原始的 `APIRouter` 将保持不变,因此我们仍然可以与组织中的其他项目共享相同的 `app/internal/admin.py` 文件。 @@ -472,7 +472,7 @@ from .routers.users import router 这里我们这样做了...只是为了表明我们可以做到🤷: ```Python hl_lines="21-23" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 它将与通过 `app.include_router()` 添加的所有其他*路径操作*一起正常运行。 diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md index 6e4c385dd..ac59d7e6a 100644 --- a/docs/zh/docs/tutorial/body-fields.md +++ b/docs/zh/docs/tutorial/body-fields.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="2" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ /// ```Python hl_lines="4" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// @@ -71,7 +71,7 @@ //// tab | Python 3.10+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} ``` //// @@ -79,7 +79,7 @@ //// tab | Python 3.9+ ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} +{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} ``` //// @@ -87,7 +87,7 @@ //// tab | Python 3.8+ ```Python hl_lines="12-15" -{!> ../../../docs_src/body_fields/tutorial001_an.py!} +{!> ../../docs_src/body_fields/tutorial001_an.py!} ``` //// @@ -101,7 +101,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="9-12" -{!> ../../../docs_src/body_fields/tutorial001_py310.py!} +{!> ../../docs_src/body_fields/tutorial001_py310.py!} ``` //// @@ -115,7 +115,7 @@ Prefer to use the `Annotated` version if possible. /// ```Python hl_lines="11-14" -{!> ../../../docs_src/body_fields/tutorial001.py!} +{!> ../../docs_src/body_fields/tutorial001.py!} ``` //// diff --git a/docs/zh/docs/tutorial/body-multiple-params.md b/docs/zh/docs/tutorial/body-multiple-params.md index fe951e544..c3bc0db9e 100644 --- a/docs/zh/docs/tutorial/body-multiple-params.md +++ b/docs/zh/docs/tutorial/body-multiple-params.md @@ -11,7 +11,7 @@ //// tab | Python 3.10+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} ``` //// @@ -19,7 +19,7 @@ //// tab | Python 3.9+ ```Python hl_lines="18-20" -{!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} ``` //// @@ -27,7 +27,7 @@ //// tab | Python 3.8+ ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} ``` //// @@ -41,7 +41,7 @@ /// ```Python hl_lines="17-19" -{!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} ``` //// @@ -55,7 +55,7 @@ /// ```Python hl_lines="19-21" -{!> ../../../docs_src/body_multiple_params/tutorial001.py!} +{!> ../../docs_src/body_multiple_params/tutorial001.py!} ``` //// @@ -84,7 +84,7 @@ //// tab | Python 3.10+ ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} ``` //// @@ -92,7 +92,7 @@ //// tab | Python 3.8+ ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial002.py!} +{!> ../../docs_src/body_multiple_params/tutorial002.py!} ``` //// @@ -140,7 +140,7 @@ //// tab | Python 3.10+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} ``` //// @@ -148,7 +148,7 @@ //// tab | Python 3.9+ ```Python hl_lines="23" -{!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} ``` //// @@ -156,7 +156,7 @@ //// tab | Python 3.8+ ```Python hl_lines="24" -{!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} ``` //// @@ -170,7 +170,7 @@ /// ```Python hl_lines="20" -{!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} ``` //// @@ -184,7 +184,7 @@ /// ```Python hl_lines="22" -{!> ../../../docs_src/body_multiple_params/tutorial003.py!} +{!> ../../docs_src/body_multiple_params/tutorial003.py!} ``` //// @@ -225,7 +225,7 @@ q: str = None //// tab | Python 3.10+ ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} ``` //// @@ -233,7 +233,7 @@ q: str = None //// tab | Python 3.9+ ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} ``` //// @@ -241,7 +241,7 @@ q: str = None //// tab | Python 3.8+ ```Python hl_lines="28" -{!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} ``` //// @@ -255,7 +255,7 @@ q: str = None /// ```Python hl_lines="25" -{!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} ``` //// @@ -269,7 +269,7 @@ q: str = None /// ```Python hl_lines="27" -{!> ../../../docs_src/body_multiple_params/tutorial004.py!} +{!> ../../docs_src/body_multiple_params/tutorial004.py!} ``` //// @@ -297,7 +297,7 @@ item: Item = Body(embed=True) //// tab | Python 3.10+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} ``` //// @@ -305,7 +305,7 @@ item: Item = Body(embed=True) //// tab | Python 3.9+ ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} ``` //// @@ -313,7 +313,7 @@ item: Item = Body(embed=True) //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} ``` //// @@ -327,7 +327,7 @@ item: Item = Body(embed=True) /// ```Python hl_lines="15" -{!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} +{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} ``` //// @@ -341,7 +341,7 @@ item: Item = Body(embed=True) /// ```Python hl_lines="17" -{!> ../../../docs_src/body_multiple_params/tutorial005.py!} +{!> ../../docs_src/body_multiple_params/tutorial005.py!} ``` //// diff --git a/docs/zh/docs/tutorial/body-nested-models.md b/docs/zh/docs/tutorial/body-nested-models.md index 26837abc6..316ba9878 100644 --- a/docs/zh/docs/tutorial/body-nested-models.md +++ b/docs/zh/docs/tutorial/body-nested-models.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial001.py!} +{!> ../../docs_src/body_nested_models/tutorial001.py!} ``` //// @@ -33,7 +33,7 @@ 首先,从 Python 的标准库 `typing` 模块中导入 `List`: ```Python hl_lines="1" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` ### 声明具有子类型的 List @@ -58,7 +58,7 @@ my_list: List[str] //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} ``` //// @@ -66,7 +66,7 @@ my_list: List[str] //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} ``` //// @@ -74,7 +74,7 @@ my_list: List[str] //// tab | Python 3.8+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} +{!> ../../docs_src/body_nested_models/tutorial002.py!} ``` //// @@ -90,7 +90,7 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se //// tab | Python 3.10+ ```Python hl_lines="12" -{!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} ``` //// @@ -98,7 +98,7 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se //// tab | Python 3.9+ ```Python hl_lines="14" -{!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} ``` //// @@ -106,7 +106,7 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se //// tab | Python 3.8+ ```Python hl_lines="1 14" -{!> ../../../docs_src/body_nested_models/tutorial003.py!} +{!> ../../docs_src/body_nested_models/tutorial003.py!} ``` //// @@ -134,7 +134,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.10+ ```Python hl_lines="7-9" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -142,7 +142,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.9+ ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -150,7 +150,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.8+ ```Python hl_lines="9-11" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -162,7 +162,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.10+ ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} ``` //// @@ -170,7 +170,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.9+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} ``` //// @@ -178,7 +178,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial004.py!} +{!> ../../docs_src/body_nested_models/tutorial004.py!} ``` //// @@ -217,7 +217,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.10+ ```Python hl_lines="2 8" -{!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} ``` //// @@ -225,7 +225,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.9+ ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} ``` //// @@ -233,7 +233,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.8+ ```Python hl_lines="4 10" -{!> ../../../docs_src/body_nested_models/tutorial005.py!} +{!> ../../docs_src/body_nested_models/tutorial005.py!} ``` //// @@ -247,7 +247,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.10+ ```Python hl_lines="18" -{!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} ``` //// @@ -255,7 +255,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.9+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} ``` //// @@ -263,7 +263,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.8+ ```Python hl_lines="20" -{!> ../../../docs_src/body_nested_models/tutorial006.py!} +{!> ../../docs_src/body_nested_models/tutorial006.py!} ``` //// @@ -307,7 +307,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.10+ ```Python hl_lines="7 12 18 21 25" -{!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} ``` //// @@ -315,7 +315,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.9+ ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} ``` //// @@ -323,7 +323,7 @@ Pydantic 模型的每个属性都具有类型。 //// tab | Python 3.8+ ```Python hl_lines="9 14 20 23 27" -{!> ../../../docs_src/body_nested_models/tutorial007.py!} +{!> ../../docs_src/body_nested_models/tutorial007.py!} ``` //// @@ -347,7 +347,7 @@ images: List[Image] //// tab | Python 3.9+ ```Python hl_lines="13" -{!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} ``` //// @@ -355,7 +355,7 @@ images: List[Image] //// tab | Python 3.8+ ```Python hl_lines="15" -{!> ../../../docs_src/body_nested_models/tutorial008.py!} +{!> ../../docs_src/body_nested_models/tutorial008.py!} ``` //// @@ -391,7 +391,7 @@ images: List[Image] //// tab | Python 3.9+ ```Python hl_lines="7" -{!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} +{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} ``` //// @@ -399,7 +399,7 @@ images: List[Image] //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/body_nested_models/tutorial009.py!} +{!> ../../docs_src/body_nested_models/tutorial009.py!} ``` //// diff --git a/docs/zh/docs/tutorial/body-updates.md b/docs/zh/docs/tutorial/body-updates.md index 6c74d12e0..5e9008d6a 100644 --- a/docs/zh/docs/tutorial/body-updates.md +++ b/docs/zh/docs/tutorial/body-updates.md @@ -7,7 +7,7 @@ 把输入数据转换为以 JSON 格式存储的数据(比如,使用 NoSQL 数据库时),可以使用 `jsonable_encoder`。例如,把 `datetime` 转换为 `str`。 ```Python hl_lines="30-35" -{!../../../docs_src/body_updates/tutorial001.py!} +{!../../docs_src/body_updates/tutorial001.py!} ``` `PUT` 用于接收替换现有数据的数据。 @@ -57,7 +57,7 @@ 然后再用它生成一个只含已设置(在请求中所发送)数据,且省略了默认值的 `dict`: ```Python hl_lines="34" -{!../../../docs_src/body_updates/tutorial002.py!} +{!../../docs_src/body_updates/tutorial002.py!} ``` ### 使用 Pydantic 的 `update` 参数 @@ -67,7 +67,7 @@ 例如,`stored_item_model.copy(update=update_data)`: ```Python hl_lines="35" -{!../../../docs_src/body_updates/tutorial002.py!} +{!../../docs_src/body_updates/tutorial002.py!} ``` ### 更新部分数据小结 @@ -86,7 +86,7 @@ * 返回更新后的模型。 ```Python hl_lines="30-37" -{!../../../docs_src/body_updates/tutorial002.py!} +{!../../docs_src/body_updates/tutorial002.py!} ``` /// tip | "提示" diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md index c47abec77..67a7f28e0 100644 --- a/docs/zh/docs/tutorial/body.md +++ b/docs/zh/docs/tutorial/body.md @@ -25,7 +25,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 //// tab | Python 3.10+ ```Python hl_lines="2" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -33,7 +33,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 //// tab | Python 3.8+ ```Python hl_lines="4" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -47,7 +47,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 //// tab | Python 3.10+ ```Python hl_lines="5-9" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -55,7 +55,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 //// tab | Python 3.8+ ```Python hl_lines="7-11" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -89,7 +89,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial001_py310.py!} +{!> ../../docs_src/body/tutorial001_py310.py!} ``` //// @@ -97,7 +97,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial001.py!} +{!> ../../docs_src/body/tutorial001.py!} ``` //// @@ -170,7 +170,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 //// tab | Python 3.10+ ```Python hl_lines="19" -{!> ../../../docs_src/body/tutorial002_py310.py!} +{!> ../../docs_src/body/tutorial002_py310.py!} ``` //// @@ -178,7 +178,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 //// tab | Python 3.8+ ```Python hl_lines="21" -{!> ../../../docs_src/body/tutorial002.py!} +{!> ../../docs_src/body/tutorial002.py!} ``` //// @@ -192,7 +192,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 //// tab | Python 3.10+ ```Python hl_lines="15-16" -{!> ../../../docs_src/body/tutorial003_py310.py!} +{!> ../../docs_src/body/tutorial003_py310.py!} ``` //// @@ -200,7 +200,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 //// tab | Python 3.8+ ```Python hl_lines="17-18" -{!> ../../../docs_src/body/tutorial003.py!} +{!> ../../docs_src/body/tutorial003.py!} ``` //// @@ -214,7 +214,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 //// tab | Python 3.10+ ```Python hl_lines="16" -{!> ../../../docs_src/body/tutorial004_py310.py!} +{!> ../../docs_src/body/tutorial004_py310.py!} ``` //// @@ -222,7 +222,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 //// tab | Python 3.8+ ```Python hl_lines="18" -{!> ../../../docs_src/body/tutorial004.py!} +{!> ../../docs_src/body/tutorial004.py!} ``` //// diff --git a/docs/zh/docs/tutorial/cookie-params.md b/docs/zh/docs/tutorial/cookie-params.md index 7ca77696e..b01c28238 100644 --- a/docs/zh/docs/tutorial/cookie-params.md +++ b/docs/zh/docs/tutorial/cookie-params.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.9+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -25,7 +25,7 @@ //// tab | Python 3.8+ ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -39,7 +39,7 @@ /// ```Python hl_lines="1" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -53,7 +53,7 @@ /// ```Python hl_lines="3" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// @@ -68,7 +68,7 @@ //// tab | Python 3.10+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} ``` //// @@ -76,7 +76,7 @@ //// tab | Python 3.9+ ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} ``` //// @@ -84,7 +84,7 @@ //// tab | Python 3.8+ ```Python hl_lines="10" -{!> ../../../docs_src/cookie_params/tutorial001_an.py!} +{!> ../../docs_src/cookie_params/tutorial001_an.py!} ``` //// @@ -98,7 +98,7 @@ /// ```Python hl_lines="7" -{!> ../../../docs_src/cookie_params/tutorial001_py310.py!} +{!> ../../docs_src/cookie_params/tutorial001_py310.py!} ``` //// @@ -112,7 +112,7 @@ /// ```Python hl_lines="9" -{!> ../../../docs_src/cookie_params/tutorial001.py!} +{!> ../../docs_src/cookie_params/tutorial001.py!} ``` //// diff --git a/docs/zh/docs/tutorial/cors.md b/docs/zh/docs/tutorial/cors.md index de880f347..1166d5c97 100644 --- a/docs/zh/docs/tutorial/cors.md +++ b/docs/zh/docs/tutorial/cors.md @@ -47,7 +47,7 @@ * 特定的 HTTP headers 或者使用通配符 `"*"` 允许所有 headers。 ```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} +{!../../docs_src/cors/tutorial001.py!} ``` 默认情况下,这个 `CORSMiddleware` 实现所使用的默认参数较为保守,所以你需要显式地启用特定的源、方法或者 headers,以便浏览器能够在跨域上下文中使用它们。 diff --git a/docs/zh/docs/tutorial/debugging.md b/docs/zh/docs/tutorial/debugging.md index 945094207..a5afa1aaa 100644 --- a/docs/zh/docs/tutorial/debugging.md +++ b/docs/zh/docs/tutorial/debugging.md @@ -7,7 +7,7 @@ 在你的 FastAPI 应用中直接导入 `uvicorn` 并运行: ```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} +{!../../docs_src/debugging/tutorial001.py!} ``` ### 关于 `__name__ == "__main__"` diff --git a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md index 9932f90fc..917459d1d 100644 --- a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md @@ -9,7 +9,7 @@ //// tab | Python 3.10+ ```Python hl_lines="7" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -17,7 +17,7 @@ //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -86,7 +86,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ ```Python hl_lines="9-13" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -94,7 +94,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.8+ ```Python hl_lines="11-15" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -104,7 +104,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ ```Python hl_lines="10" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -112,7 +112,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ ```Python hl_lines="12" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -122,7 +122,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ ```Python hl_lines="6" -{!> ../../../docs_src/dependencies/tutorial001_py310.py!} +{!> ../../docs_src/dependencies/tutorial001_py310.py!} ``` //// @@ -130,7 +130,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ ```Python hl_lines="9" -{!> ../../../docs_src/dependencies/tutorial001.py!} +{!> ../../docs_src/dependencies/tutorial001.py!} ``` //// @@ -152,7 +152,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial002_py310.py!} +{!> ../../docs_src/dependencies/tutorial002_py310.py!} ``` //// @@ -160,7 +160,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial002.py!} +{!> ../../docs_src/dependencies/tutorial002.py!} ``` //// @@ -206,7 +206,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.10+ ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial003_py310.py!} +{!> ../../docs_src/dependencies/tutorial003_py310.py!} ``` //// @@ -214,7 +214,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.6+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial003.py!} +{!> ../../docs_src/dependencies/tutorial003.py!} ``` //// @@ -254,7 +254,7 @@ commons: CommonQueryParams = Depends() //// tab | Python 3.10+ ```Python hl_lines="17" -{!> ../../../docs_src/dependencies/tutorial004_py310.py!} +{!> ../../docs_src/dependencies/tutorial004_py310.py!} ``` //// @@ -262,7 +262,7 @@ commons: CommonQueryParams = Depends() //// tab | Python 3.6+ ```Python hl_lines="19" -{!> ../../../docs_src/dependencies/tutorial004.py!} +{!> ../../docs_src/dependencies/tutorial004.py!} ``` //// diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index e6bbd47c1..c7cfe0531 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -15,7 +15,7 @@ 该参数的值是由 `Depends()` 组成的 `list`: ```Python hl_lines="17" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` 路径操作装饰器依赖项(以下简称为**“路径装饰器依赖项”**)的执行或解析方式和普通依赖项一样,但就算这些依赖项会返回值,它们的值也不会传递给*路径操作函数*。 @@ -47,7 +47,7 @@ 路径装饰器依赖项可以声明请求的需求项(比如响应头)或其他子依赖项: ```Python hl_lines="6 11" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ### 触发异常 @@ -55,7 +55,7 @@ 路径装饰器依赖项与正常的依赖项一样,可以 `raise` 异常: ```Python hl_lines="8 13" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ### 返回值 @@ -65,7 +65,7 @@ 因此,可以复用在其他位置使用过的、(能返回值的)普通依赖项,即使没有使用这个值,也会执行该依赖项: ```Python hl_lines="9 14" -{!../../../docs_src/dependencies/tutorial006.py!} +{!../../docs_src/dependencies/tutorial006.py!} ``` ## 为一组路径操作定义依赖项 diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md index 6058f7878..a30313719 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md @@ -30,19 +30,19 @@ FastAPI支持在完成后执行一些 ../../../docs_src/dependencies/tutorial008_an.py!} +{!> ../../docs_src/dependencies/tutorial008_an.py!} ``` //// @@ -99,7 +99,7 @@ FastAPI支持在完成后执行一些 ../../../docs_src/dependencies/tutorial008_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} ``` //// @@ -121,7 +121,7 @@ FastAPI支持在完成后执行一些 ../../../docs_src/dependencies/tutorial008.py!} +{!> ../../docs_src/dependencies/tutorial008.py!} ``` //// @@ -173,7 +173,7 @@ FastAPI支持在完成后执行一些 ../../../docs_src/dependencies/tutorial008b_an.py!} +{!> ../../docs_src/dependencies/tutorial008b_an.py!} ``` //// @@ -195,7 +195,7 @@ FastAPI支持在完成后执行一些 ../../../docs_src/dependencies/tutorial008c_an_py39.py!} +{!> ../../docs_src/dependencies/tutorial008c_an_py39.py!} ``` //// @@ -217,7 +217,7 @@ FastAPI支持在完成后执行一些 ../../../docs_src/dependencies/tutorial008c.py!} +{!> ../../docs_src/dependencies/tutorial008c.py!} ``` //// @@ -247,7 +247,7 @@ FastAPI支持在完成后执行一些 ../../../docs_src/dependencies/tutorial008d_an.py!} +{!> ../../docs_src/dependencies/tutorial008d_an.py!} ``` //// @@ -269,7 +269,7 @@ FastAPI支持在完成后执行一些 Date: Mon, 7 Oct 2024 20:11:42 +0000 Subject: [PATCH 042/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 490f99c70..26cba035b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Internal +* 👷 Tweak labeler to not override custom labels. PR [#12398](https://github.com/fastapi/fastapi/pull/12398) by [@tiangolo](https://github.com/tiangolo). * 👷 Update worfkow deploy-docs-notify URL. PR [#12392](https://github.com/fastapi/fastapi/pull/12392) by [@tiangolo](https://github.com/tiangolo). * 👷 Update Cloudflare GitHub Action. PR [#12387](https://github.com/fastapi/fastapi/pull/12387) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump pypa/gh-action-pypi-publish from 1.10.1 to 1.10.3. PR [#12386](https://github.com/fastapi/fastapi/pull/12386) by [@dependabot[bot]](https://github.com/apps/dependabot). From 797cad7162592b6e581228bec09682da8feb6752 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 7 Oct 2024 22:18:07 +0200 Subject: [PATCH 043/932] =?UTF-8?q?=F0=9F=93=9D=20Fix=20extra=20mdx-base-p?= =?UTF-8?q?ath=20paths=20(#12397)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/sql-databases.md | 48 ++++++++++---------- docs/it/docs/index.md | 3 -- docs/pt/docs/tutorial/cookie-param-models.md | 16 +++---- scripts/docs.py | 2 +- 4 files changed, 33 insertions(+), 36 deletions(-) diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index f65fa773c..7836efae1 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -296,7 +296,7 @@ But for security, the `password` won't be in other Pydantic *models*, for exampl //// tab | Python 3.10+ ```Python hl_lines="1 4-6 9-10 21-22 25-26" -{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} ``` //// @@ -304,7 +304,7 @@ But for security, the `password` won't be in other Pydantic *models*, for exampl //// tab | Python 3.9+ ```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` //// @@ -312,7 +312,7 @@ But for security, the `password` won't be in other Pydantic *models*, for exampl //// tab | Python 3.8+ ```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} ``` //// @@ -346,7 +346,7 @@ Not only the IDs of those items, but all the data that we defined in the Pydanti //// tab | Python 3.10+ ```Python hl_lines="13-15 29-32" -{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} ``` //// @@ -354,7 +354,7 @@ Not only the IDs of those items, but all the data that we defined in the Pydanti //// tab | Python 3.9+ ```Python hl_lines="15-17 31-34" -{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` //// @@ -362,7 +362,7 @@ Not only the IDs of those items, but all the data that we defined in the Pydanti //// tab | Python 3.8+ ```Python hl_lines="15-17 31-34" -{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} ``` //// @@ -384,7 +384,7 @@ In the `Config` class, set the attribute `orm_mode = True`. //// tab | Python 3.10+ ```Python hl_lines="13 17-18 29 34-35" -{!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} ``` //// @@ -392,7 +392,7 @@ In the `Config` class, set the attribute `orm_mode = True`. //// tab | Python 3.9+ ```Python hl_lines="15 19-20 31 36-37" -{!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` //// @@ -400,7 +400,7 @@ In the `Config` class, set the attribute `orm_mode = True`. //// tab | Python 3.8+ ```Python hl_lines="15 19-20 31 36-37" -{!> ../../../docs_src/sql_databases/sql_app/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} ``` //// @@ -559,7 +559,7 @@ In a very simplistic way create the database tables: //// tab | Python 3.9+ ```Python hl_lines="7" -{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -567,7 +567,7 @@ In a very simplistic way create the database tables: //// tab | Python 3.8+ ```Python hl_lines="9" -{!> ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -597,7 +597,7 @@ Our dependency will create a new SQLAlchemy `SessionLocal` that will be used in //// tab | Python 3.9+ ```Python hl_lines="13-18" -{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -605,7 +605,7 @@ Our dependency will create a new SQLAlchemy `SessionLocal` that will be used in //// tab | Python 3.8+ ```Python hl_lines="15-20" -{!> ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -629,7 +629,7 @@ This will then give us better editor support inside the *path operation function //// tab | Python 3.9+ ```Python hl_lines="22 30 36 45 51" -{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -637,7 +637,7 @@ This will then give us better editor support inside the *path operation function //// tab | Python 3.8+ ```Python hl_lines="24 32 38 47 53" -{!> ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -657,7 +657,7 @@ Now, finally, here's the standard **FastAPI** *path operations* code. //// tab | Python 3.9+ ```Python hl_lines="21-26 29-32 35-40 43-47 50-53" -{!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -665,7 +665,7 @@ Now, finally, here's the standard **FastAPI** *path operations* code. //// tab | Python 3.8+ ```Python hl_lines="23-28 31-34 37-42 45-49 52-55" -{!> ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -766,7 +766,7 @@ For example, in a background task worker with ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} ``` //// @@ -774,7 +774,7 @@ For example, in a background task worker with ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} ``` //// @@ -782,7 +782,7 @@ For example, in a background task worker with ../../../docs_src/sql_databases/sql_app/schemas.py!} +{!> ../../docs_src/sql_databases/sql_app/schemas.py!} ``` //// @@ -798,7 +798,7 @@ For example, in a background task worker with ../../../docs_src/sql_databases/sql_app_py39/main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} ``` //// @@ -806,7 +806,7 @@ For example, in a background task worker with ../../../docs_src/sql_databases/sql_app/main.py!} +{!> ../../docs_src/sql_databases/sql_app/main.py!} ``` //// @@ -863,7 +863,7 @@ The middleware we'll add (just a function) will create a new SQLAlchemy `Session //// tab | Python 3.9+ ```Python hl_lines="12-20" -{!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} +{!> ../../docs_src/sql_databases/sql_app_py39/alt_main.py!} ``` //// @@ -871,7 +871,7 @@ The middleware we'll add (just a function) will create a new SQLAlchemy `Session //// tab | Python 3.8+ ```Python hl_lines="14-22" -{!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} +{!> ../../docs_src/sql_databases/sql_app/alt_main.py!} ``` //// diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md index 57940f0ed..3bfff82f1 100644 --- a/docs/it/docs/index.md +++ b/docs/it/docs/index.md @@ -1,6 +1,3 @@ -{!../../../docs/missing-translation.md!} - -

FastAPI

diff --git a/docs/pt/docs/tutorial/cookie-param-models.md b/docs/pt/docs/tutorial/cookie-param-models.md index 12d7ee08c..671e0d74f 100644 --- a/docs/pt/docs/tutorial/cookie-param-models.md +++ b/docs/pt/docs/tutorial/cookie-param-models.md @@ -23,7 +23,7 @@ Declare o parâmetro de **cookie** que você precisa em um **modelo Pydantic**, //// tab | Python 3.10+ ```Python hl_lines="9-12 16" -{!> ../../../docs_src/cookie_param_models/tutorial001_an_py310.py!} +{!> ../../docs_src/cookie_param_models/tutorial001_an_py310.py!} ``` //// @@ -31,7 +31,7 @@ Declare o parâmetro de **cookie** que você precisa em um **modelo Pydantic**, //// tab | Python 3.9+ ```Python hl_lines="9-12 16" -{!> ../../../docs_src/cookie_param_models/tutorial001_an_py39.py!} +{!> ../../docs_src/cookie_param_models/tutorial001_an_py39.py!} ``` //// @@ -39,7 +39,7 @@ Declare o parâmetro de **cookie** que você precisa em um **modelo Pydantic**, //// tab | Python 3.8+ ```Python hl_lines="10-13 17" -{!> ../../../docs_src/cookie_param_models/tutorial001_an.py!} +{!> ../../docs_src/cookie_param_models/tutorial001_an.py!} ``` //// @@ -53,7 +53,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="7-10 14" -{!> ../../../docs_src/cookie_param_models/tutorial001_py310.py!} +{!> ../../docs_src/cookie_param_models/tutorial001_py310.py!} ``` //// @@ -67,7 +67,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="9-12 16" -{!> ../../../docs_src/cookie_param_models/tutorial001.py!} +{!> ../../docs_src/cookie_param_models/tutorial001.py!} ``` //// @@ -105,7 +105,7 @@ Agora a sua API possui o poder de contrar o seu próprio ../../../docs_src/cookie_param_models/tutorial002_an_py39.py!} +{!> ../../docs_src/cookie_param_models/tutorial002_an_py39.py!} ``` //// @@ -113,7 +113,7 @@ Agora a sua API possui o poder de contrar o seu próprio ../../../docs_src/cookie_param_models/tutorial002_an.py!} +{!> ../../docs_src/cookie_param_models/tutorial002_an.py!} ``` //// @@ -127,7 +127,7 @@ Prefira utilizar a versão `Annotated` se possível. /// ```Python hl_lines="10" -{!> ../../../docs_src/cookie_param_models/tutorial002.py!} +{!> ../../docs_src/cookie_param_models/tutorial002.py!} ``` //// diff --git a/scripts/docs.py b/scripts/docs.py index f0c51f7a6..e5c423d58 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -23,7 +23,7 @@ app = typer.Typer() mkdocs_name = "mkdocs.yml" missing_translation_snippet = """ -{!../../../docs/missing-translation.md!} +{!../../docs/missing-translation.md!} """ non_translated_sections = [ From ecc4133907df47830bab6f11607c981ec82091b2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 7 Oct 2024 20:18:29 +0000 Subject: [PATCH 044/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 26cba035b..ab23184a1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Internal +* 📝 Fix extra mdx-base-path paths. PR [#12397](https://github.com/fastapi/fastapi/pull/12397) by [@tiangolo](https://github.com/tiangolo). * 👷 Tweak labeler to not override custom labels. PR [#12398](https://github.com/fastapi/fastapi/pull/12398) by [@tiangolo](https://github.com/tiangolo). * 👷 Update worfkow deploy-docs-notify URL. PR [#12392](https://github.com/fastapi/fastapi/pull/12392) by [@tiangolo](https://github.com/tiangolo). * 👷 Update Cloudflare GitHub Action. PR [#12387](https://github.com/fastapi/fastapi/pull/12387) by [@tiangolo](https://github.com/tiangolo). From 95f167f0480f8df94c06c95cd19323534d123a2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 7 Oct 2024 22:24:40 +0200 Subject: [PATCH 045/932] =?UTF-8?q?=E2=9E=95=20Add=20docs=20dependency:=20?= =?UTF-8?q?markdown-include-variants=20(#12399)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/mkdocs.yml | 1 + requirements-docs.txt | 1 + 2 files changed, 2 insertions(+) diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index a18af2022..e55c6f176 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -305,6 +305,7 @@ markdown_extensions: # Other extensions mdx_include: + markdown_include_variants: extra: analytics: diff --git a/requirements-docs.txt b/requirements-docs.txt index 16b2998b9..c05bd51e3 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -16,3 +16,4 @@ griffe-typingdoc==0.2.7 # For griffe, it formats with black black==24.3.0 mkdocs-macros-plugin==1.0.5 +markdown-include-variants==0.0.1 From 6345147c245248302e90f0eb6371f7ab7557fd1b Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 7 Oct 2024 20:25:03 +0000 Subject: [PATCH 046/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ab23184a1..b9dfe3da5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Internal +* ➕ Add docs dependency: markdown-include-variants. PR [#12399](https://github.com/fastapi/fastapi/pull/12399) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix extra mdx-base-path paths. PR [#12397](https://github.com/fastapi/fastapi/pull/12397) by [@tiangolo](https://github.com/tiangolo). * 👷 Tweak labeler to not override custom labels. PR [#12398](https://github.com/fastapi/fastapi/pull/12398) by [@tiangolo](https://github.com/tiangolo). * 👷 Update worfkow deploy-docs-notify URL. PR [#12392](https://github.com/fastapi/fastapi/pull/12392) by [@tiangolo](https://github.com/tiangolo). From 018e303fd9d04fe91a12cd39561d5bc5ca7b0aee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 8 Oct 2024 10:37:32 +0200 Subject: [PATCH 047/932] =?UTF-8?q?=F0=9F=94=A7=20Add=20speakeasy-api=20to?= =?UTF-8?q?=20`sponsors=5Fbadge.yml`=20(#12404)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/sponsors_badge.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/data/sponsors_badge.yml b/docs/en/data/sponsors_badge.yml index d8a41fbcb..d45028aaa 100644 --- a/docs/en/data/sponsors_badge.yml +++ b/docs/en/data/sponsors_badge.yml @@ -30,3 +30,4 @@ logins: - svix - zuplo-oss - Kong + - speakeasy-api From fcb15b4db162f2504d3f9f984d938e9a8ff03b35 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 8 Oct 2024 08:38:00 +0000 Subject: [PATCH 048/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b9dfe3da5..d785805e9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Internal +* 🔧 Add speakeasy-api to `sponsors_badge.yml`. PR [#12404](https://github.com/fastapi/fastapi/pull/12404) by [@tiangolo](https://github.com/tiangolo). * ➕ Add docs dependency: markdown-include-variants. PR [#12399](https://github.com/fastapi/fastapi/pull/12399) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix extra mdx-base-path paths. PR [#12397](https://github.com/fastapi/fastapi/pull/12397) by [@tiangolo](https://github.com/tiangolo). * 👷 Tweak labeler to not override custom labels. PR [#12398](https://github.com/fastapi/fastapi/pull/12398) by [@tiangolo](https://github.com/tiangolo). From 40490abaa3526eee394eb84362bfa4ca6b4da9d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 8 Oct 2024 12:55:26 +0200 Subject: [PATCH 049/932] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Update=20type=20an?= =?UTF-8?q?notations=20for=20improved=20`python-multipart`=20(#12407)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/dependencies/utils.py | 6 +++--- requirements-docs-tests.txt | 2 ++ requirements-tests.txt | 1 - 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 5cebbf00f..813c74620 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -91,14 +91,14 @@ multipart_incorrect_install_error = ( def ensure_multipart_is_installed() -> None: try: # __version__ is available in both multiparts, and can be mocked - from multipart import __version__ # type: ignore + from multipart import __version__ assert __version__ try: # parse_options_header is only available in the right multipart - from multipart.multipart import parse_options_header # type: ignore + from multipart.multipart import parse_options_header - assert parse_options_header + assert parse_options_header # type: ignore[truthy-function] except ImportError: logger.error(multipart_incorrect_install_error) raise RuntimeError(multipart_incorrect_install_error) from None diff --git a/requirements-docs-tests.txt b/requirements-docs-tests.txt index b82df4933..40b956e51 100644 --- a/requirements-docs-tests.txt +++ b/requirements-docs-tests.txt @@ -1,2 +1,4 @@ # For mkdocstrings and tests httpx >=0.23.0,<0.25.0 +# For linting and generating docs versions +ruff ==0.6.4 diff --git a/requirements-tests.txt b/requirements-tests.txt index 2f2576dd5..7b1f7ea1a 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -3,7 +3,6 @@ pytest >=7.1.3,<8.0.0 coverage[toml] >= 6.5.0,< 8.0 mypy ==1.8.0 -ruff ==0.6.4 dirty-equals ==0.6.0 # TODO: once removing databases from tutorial, upgrade SQLAlchemy # probably when including SQLModel From a94d61b2c09c7ba5bc2bf5016e590e2b0a35189e Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 8 Oct 2024 10:55:50 +0000 Subject: [PATCH 050/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d785805e9..16faa52f9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Refactors + +* ♻️ Update type annotations for improved `python-multipart`. PR [#12407](https://github.com/fastapi/fastapi/pull/12407) by [@tiangolo](https://github.com/tiangolo). + ### Docs * 📝 Add External Link: How to profile a FastAPI asynchronous request. PR [#12389](https://github.com/fastapi/fastapi/pull/12389) by [@brouberol](https://github.com/brouberol). From c6dfdb85239d32eb0f9825b1374f780b33eb8a7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 8 Oct 2024 13:01:17 +0200 Subject: [PATCH 051/932] =?UTF-8?q?=F0=9F=94=A8=20Add=20script=20to=20gene?= =?UTF-8?q?rate=20variants=20of=20files=20(#12405)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/docs.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/scripts/docs.py b/scripts/docs.py index e5c423d58..f26f96d85 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -15,6 +15,7 @@ import mkdocs.utils import typer import yaml from jinja2 import Template +from ruff.__main__ import find_ruff_bin logging.basicConfig(level=logging.INFO) @@ -382,5 +383,41 @@ def langs_json(): print(json.dumps(langs)) +@app.command() +def generate_docs_src_versions_for_file(file_path: Path) -> None: + target_versions = ["py39", "py310"] + base_content = file_path.read_text(encoding="utf-8") + previous_content = {base_content} + for target_version in target_versions: + version_result = subprocess.run( + [ + find_ruff_bin(), + "check", + "--target-version", + target_version, + "--fix", + "--unsafe-fixes", + "-", + ], + input=base_content.encode("utf-8"), + capture_output=True, + ) + content_target = version_result.stdout.decode("utf-8") + format_result = subprocess.run( + [find_ruff_bin(), "format", "-"], + input=content_target.encode("utf-8"), + capture_output=True, + ) + content_format = format_result.stdout.decode("utf-8") + if content_format in previous_content: + continue + previous_content.add(content_format) + version_file = file_path.with_name( + file_path.name.replace(".py", f"_{target_version}.py") + ) + logging.info(f"Writing to {version_file}") + version_file.write_text(content_format, encoding="utf-8") + + if __name__ == "__main__": app() From 13a18f80b3b0c7f0272c67b6ac7b73aafbb8584c Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 8 Oct 2024 11:01:43 +0000 Subject: [PATCH 052/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 16faa52f9..e34fd0df9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -39,6 +39,7 @@ hide: ### Internal +* 🔨 Add script to generate variants of files. PR [#12405](https://github.com/fastapi/fastapi/pull/12405) by [@tiangolo](https://github.com/tiangolo). * 🔧 Add speakeasy-api to `sponsors_badge.yml`. PR [#12404](https://github.com/fastapi/fastapi/pull/12404) by [@tiangolo](https://github.com/tiangolo). * ➕ Add docs dependency: markdown-include-variants. PR [#12399](https://github.com/fastapi/fastapi/pull/12399) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix extra mdx-base-path paths. PR [#12397](https://github.com/fastapi/fastapi/pull/12397) by [@tiangolo](https://github.com/tiangolo). From 7daaac2bc350e2907554a01eb7eb1286247e5832 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 9 Oct 2024 21:44:42 +0200 Subject: [PATCH 053/932] =?UTF-8?q?=E2=9C=A8=20Add=20new=20tutorial=20for?= =?UTF-8?q?=20SQL=20databases=20with=20SQLModel=20(#12285)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/em/docs/advanced/testing-database.md | 101 -- docs/em/docs/how-to/sql-databases-peewee.md | 576 ------------ docs/en/docs/advanced/testing-database.md | 111 --- .../docs/how-to/async-sql-encode-databases.md | 201 ---- .../docs/how-to/nosql-databases-couchbase.md | 178 ---- docs/en/docs/how-to/sql-databases-peewee.md | 594 ------------ docs/en/docs/how-to/testing-database.md | 7 + .../img/tutorial/sql-databases/image01.png | Bin 78949 -> 69755 bytes .../img/tutorial/sql-databases/image02.png | Bin 83482 -> 69197 bytes docs/en/docs/tutorial/sql-databases.md | 888 ++++-------------- docs/en/mkdocs.yml | 9 +- docs/zh/docs/advanced/testing-database.md | 101 -- docs_src/async_sql_databases/tutorial001.py | 65 -- docs_src/nosql_databases/tutorial001.py | 53 -- docs_src/sql_databases/sql_app/__init__.py | 0 docs_src/sql_databases/sql_app/alt_main.py | 62 -- docs_src/sql_databases/sql_app/crud.py | 36 - docs_src/sql_databases/sql_app/database.py | 13 - docs_src/sql_databases/sql_app/main.py | 55 -- docs_src/sql_databases/sql_app/models.py | 26 - docs_src/sql_databases/sql_app/schemas.py | 37 - .../sql_databases/sql_app/tests/__init__.py | 0 .../sql_app/tests/test_sql_app.py | 50 - .../sql_databases/sql_app_py310/__init__.py | 0 .../sql_databases/sql_app_py310/alt_main.py | 60 -- docs_src/sql_databases/sql_app_py310/crud.py | 36 - .../sql_databases/sql_app_py310/database.py | 13 - docs_src/sql_databases/sql_app_py310/main.py | 53 -- .../sql_databases/sql_app_py310/models.py | 26 - .../sql_databases/sql_app_py310/schemas.py | 35 - .../sql_app_py310/tests/__init__.py | 0 .../sql_app_py310/tests/test_sql_app.py | 47 - .../sql_databases/sql_app_py39/__init__.py | 0 .../sql_databases/sql_app_py39/alt_main.py | 60 -- docs_src/sql_databases/sql_app_py39/crud.py | 36 - .../sql_databases/sql_app_py39/database.py | 13 - docs_src/sql_databases/sql_app_py39/main.py | 53 -- docs_src/sql_databases/sql_app_py39/models.py | 26 - .../sql_databases/sql_app_py39/schemas.py | 37 - .../sql_app_py39/tests/__init__.py | 0 .../sql_app_py39/tests/test_sql_app.py | 47 - docs_src/sql_databases/tutorial001.py | 71 ++ docs_src/sql_databases/tutorial001_an.py | 74 ++ .../sql_databases/tutorial001_an_py310.py | 73 ++ docs_src/sql_databases/tutorial001_an_py39.py | 73 ++ docs_src/sql_databases/tutorial001_py310.py | 69 ++ docs_src/sql_databases/tutorial001_py39.py | 71 ++ docs_src/sql_databases/tutorial002.py | 104 ++ docs_src/sql_databases/tutorial002_an.py | 104 ++ .../sql_databases/tutorial002_an_py310.py | 103 ++ docs_src/sql_databases/tutorial002_an_py39.py | 103 ++ docs_src/sql_databases/tutorial002_py310.py | 102 ++ docs_src/sql_databases/tutorial002_py39.py | 104 ++ requirements-docs.txt | 2 +- requirements-tests.txt | 5 +- scripts/playwright/sql_databases/image01.py | 37 + scripts/playwright/sql_databases/image02.py | 37 + .../test_async_sql_databases/__init__.py | 0 .../test_tutorial001.py | 146 --- .../test_sql_databases/test_sql_databases.py | 419 --------- .../test_sql_databases_middleware.py | 421 --------- .../test_sql_databases_middleware_py310.py | 433 --------- .../test_sql_databases_middleware_py39.py | 433 --------- .../test_sql_databases_py310.py | 432 --------- .../test_sql_databases_py39.py | 432 --------- .../test_testing_databases.py | 27 - .../test_testing_databases_py310.py | 28 - .../test_testing_databases_py39.py | 28 - .../test_sql_databases/test_tutorial001.py | 373 ++++++++ .../test_sql_databases/test_tutorial002.py | 481 ++++++++++ 70 files changed, 2154 insertions(+), 6336 deletions(-) delete mode 100644 docs/em/docs/advanced/testing-database.md delete mode 100644 docs/em/docs/how-to/sql-databases-peewee.md delete mode 100644 docs/en/docs/advanced/testing-database.md delete mode 100644 docs/en/docs/how-to/async-sql-encode-databases.md delete mode 100644 docs/en/docs/how-to/nosql-databases-couchbase.md delete mode 100644 docs/en/docs/how-to/sql-databases-peewee.md create mode 100644 docs/en/docs/how-to/testing-database.md delete mode 100644 docs/zh/docs/advanced/testing-database.md delete mode 100644 docs_src/async_sql_databases/tutorial001.py delete mode 100644 docs_src/nosql_databases/tutorial001.py delete mode 100644 docs_src/sql_databases/sql_app/__init__.py delete mode 100644 docs_src/sql_databases/sql_app/alt_main.py delete mode 100644 docs_src/sql_databases/sql_app/crud.py delete mode 100644 docs_src/sql_databases/sql_app/database.py delete mode 100644 docs_src/sql_databases/sql_app/main.py delete mode 100644 docs_src/sql_databases/sql_app/models.py delete mode 100644 docs_src/sql_databases/sql_app/schemas.py delete mode 100644 docs_src/sql_databases/sql_app/tests/__init__.py delete mode 100644 docs_src/sql_databases/sql_app/tests/test_sql_app.py delete mode 100644 docs_src/sql_databases/sql_app_py310/__init__.py delete mode 100644 docs_src/sql_databases/sql_app_py310/alt_main.py delete mode 100644 docs_src/sql_databases/sql_app_py310/crud.py delete mode 100644 docs_src/sql_databases/sql_app_py310/database.py delete mode 100644 docs_src/sql_databases/sql_app_py310/main.py delete mode 100644 docs_src/sql_databases/sql_app_py310/models.py delete mode 100644 docs_src/sql_databases/sql_app_py310/schemas.py delete mode 100644 docs_src/sql_databases/sql_app_py310/tests/__init__.py delete mode 100644 docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py delete mode 100644 docs_src/sql_databases/sql_app_py39/__init__.py delete mode 100644 docs_src/sql_databases/sql_app_py39/alt_main.py delete mode 100644 docs_src/sql_databases/sql_app_py39/crud.py delete mode 100644 docs_src/sql_databases/sql_app_py39/database.py delete mode 100644 docs_src/sql_databases/sql_app_py39/main.py delete mode 100644 docs_src/sql_databases/sql_app_py39/models.py delete mode 100644 docs_src/sql_databases/sql_app_py39/schemas.py delete mode 100644 docs_src/sql_databases/sql_app_py39/tests/__init__.py delete mode 100644 docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py create mode 100644 docs_src/sql_databases/tutorial001.py create mode 100644 docs_src/sql_databases/tutorial001_an.py create mode 100644 docs_src/sql_databases/tutorial001_an_py310.py create mode 100644 docs_src/sql_databases/tutorial001_an_py39.py create mode 100644 docs_src/sql_databases/tutorial001_py310.py create mode 100644 docs_src/sql_databases/tutorial001_py39.py create mode 100644 docs_src/sql_databases/tutorial002.py create mode 100644 docs_src/sql_databases/tutorial002_an.py create mode 100644 docs_src/sql_databases/tutorial002_an_py310.py create mode 100644 docs_src/sql_databases/tutorial002_an_py39.py create mode 100644 docs_src/sql_databases/tutorial002_py310.py create mode 100644 docs_src/sql_databases/tutorial002_py39.py create mode 100644 scripts/playwright/sql_databases/image01.py create mode 100644 scripts/playwright/sql_databases/image02.py delete mode 100644 tests/test_tutorial/test_async_sql_databases/__init__.py delete mode 100644 tests/test_tutorial/test_async_sql_databases/test_tutorial001.py delete mode 100644 tests/test_tutorial/test_sql_databases/test_sql_databases.py delete mode 100644 tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py delete mode 100644 tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py delete mode 100644 tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py delete mode 100644 tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py delete mode 100644 tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py delete mode 100644 tests/test_tutorial/test_sql_databases/test_testing_databases.py delete mode 100644 tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py delete mode 100644 tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py create mode 100644 tests/test_tutorial/test_sql_databases/test_tutorial001.py create mode 100644 tests/test_tutorial/test_sql_databases/test_tutorial002.py diff --git a/docs/em/docs/advanced/testing-database.md b/docs/em/docs/advanced/testing-database.md deleted file mode 100644 index 71b29f9b7..000000000 --- a/docs/em/docs/advanced/testing-database.md +++ /dev/null @@ -1,101 +0,0 @@ -# 🔬 💽 - -👆 💪 ⚙️ 🎏 🔗 🔐 ⚪️➡️ [🔬 🔗 ⏮️ 🔐](testing-dependencies.md){.internal-link target=_blank} 📉 💽 🔬. - -👆 💪 💚 ⚒ 🆙 🎏 💽 🔬, 💾 💽 ⏮️ 💯, 🏤-🥧 ⚫️ ⏮️ 🔬 💽, ♒️. - -👑 💭 ⚫️❔ 🎏 👆 👀 👈 ⏮️ 📃. - -## 🚮 💯 🗄 📱 - -➡️ ℹ 🖼 ⚪️➡️ [🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank} ⚙️ 🔬 💽. - -🌐 📱 📟 🎏, 👆 💪 🚶 🔙 👈 📃 ✅ ❔ ⚫️. - -🕴 🔀 📥 🆕 🔬 📁. - -👆 😐 🔗 `get_db()` 🔜 📨 💽 🎉. - -💯, 👆 💪 ⚙️ 🔗 🔐 📨 👆 *🛃* 💽 🎉 ↩️ 1️⃣ 👈 🔜 ⚙️ 🛎. - -👉 🖼 👥 🔜 ✍ 🍕 💽 🕴 💯. - -## 📁 📊 - -👥 ✍ 🆕 📁 `sql_app/tests/test_sql_app.py`. - -🆕 📁 📊 👀 💖: - -``` hl_lines="9-11" -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - ├── schemas.py - └── tests - ├── __init__.py - └── test_sql_app.py -``` - -## ✍ 🆕 💽 🎉 - -🥇, 👥 ✍ 🆕 💽 🎉 ⏮️ 🆕 💽. - -💯 👥 🔜 ⚙️ 📁 `test.db` ↩️ `sql_app.db`. - -✋️ 🎂 🎉 📟 🌅 ⚖️ 🌘 🎏, 👥 📁 ⚫️. - -```Python hl_lines="8-13" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -/// tip - -👆 💪 📉 ❎ 👈 📟 🚮 ⚫️ 🔢 & ⚙️ ⚫️ ⚪️➡️ 👯‍♂️ `database.py` & `tests/test_sql_app.py`. - -🦁 & 🎯 🔛 🎯 🔬 📟, 👥 🖨 ⚫️. - -/// - -## ✍ 💽 - -↩️ 🔜 👥 🔜 ⚙️ 🆕 💽 🆕 📁, 👥 💪 ⚒ 💭 👥 ✍ 💽 ⏮️: - -```Python -Base.metadata.create_all(bind=engine) -``` - -👈 🛎 🤙 `main.py`, ✋️ ⏸ `main.py` ⚙️ 💽 📁 `sql_app.db`, & 👥 💪 ⚒ 💭 👥 ✍ `test.db` 💯. - -👥 🚮 👈 ⏸ 📥, ⏮️ 🆕 📁. - -```Python hl_lines="16" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -## 🔗 🔐 - -🔜 👥 ✍ 🔗 🔐 & 🚮 ⚫️ 🔐 👆 📱. - -```Python hl_lines="19-24 27" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -/// tip - -📟 `override_get_db()` 🌖 ⚫️❔ 🎏 `get_db()`, ✋️ `override_get_db()` 👥 ⚙️ `TestingSessionLocal` 🔬 💽 ↩️. - -/// - -## 💯 📱 - -⤴️ 👥 💪 💯 📱 🛎. - -```Python hl_lines="32-47" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -& 🌐 🛠️ 👥 ⚒ 💽 ⏮️ 💯 🔜 `test.db` 💽 ↩️ 👑 `sql_app.db`. diff --git a/docs/em/docs/how-to/sql-databases-peewee.md b/docs/em/docs/how-to/sql-databases-peewee.md deleted file mode 100644 index d25b77894..000000000 --- a/docs/em/docs/how-to/sql-databases-peewee.md +++ /dev/null @@ -1,576 +0,0 @@ -# 🗄 (🔗) 💽 ⏮️ 🏒 - -/// warning - -🚥 👆 ▶️, 🔰 [🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank} 👈 ⚙️ 🇸🇲 🔜 🥃. - -💭 🆓 🚶 👉. - -/// - -🚥 👆 ▶️ 🏗 ⚪️➡️ 🖌, 👆 🎲 👻 📆 ⏮️ 🇸🇲 🐜 ([🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank}), ⚖️ 🙆 🎏 🔁 🐜. - -🚥 👆 ⏪ ✔️ 📟 🧢 👈 ⚙️ 🏒 🐜, 👆 💪 ✅ 📥 ❔ ⚙️ ⚫️ ⏮️ **FastAPI**. - -/// warning | "🐍 3️⃣.7️⃣ ➕ ✔" - -👆 🔜 💪 🐍 3️⃣.7️⃣ ⚖️ 🔛 🔒 ⚙️ 🏒 ⏮️ FastAPI. - -/// - -## 🏒 🔁 - -🏒 🚫 🔧 🔁 🛠️, ⚖️ ⏮️ 👫 🤯. - -🏒 ✔️ 🏋️ 🔑 🔃 🚮 🔢 & 🔃 ❔ ⚫️ 🔜 ⚙️. - -🚥 👆 🛠️ 🈸 ⏮️ 🗝 🚫-🔁 🛠️, & 💪 👷 ⏮️ 🌐 🚮 🔢, **⚫️ 💪 👑 🧰**. - -✋️ 🚥 👆 💪 🔀 🔢, 🐕‍🦺 🌖 🌘 1️⃣ 🔁 💽, 👷 ⏮️ 🔁 🛠️ (💖 FastAPI), ♒️, 👆 🔜 💪 🚮 🏗 ➕ 📟 🔐 👈 🔢. - -👐, ⚫️ 💪 ⚫️, & 📥 👆 🔜 👀 ⚫️❔ ⚫️❔ 📟 👆 ✔️ 🚮 💪 ⚙️ 🏒 ⏮️ FastAPI. - -/// note | "📡 ℹ" - -👆 💪 ✍ 🌅 🔃 🏒 🧍 🔃 🔁 🐍 🩺, , 🇵🇷. - -/// - -## 🎏 📱 - -👥 🔜 ✍ 🎏 🈸 🇸🇲 🔰 ([🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank}). - -🌅 📟 🤙 🎏. - -, 👥 🔜 🎯 🕴 🔛 🔺. - -## 📁 📊 - -➡️ 💬 👆 ✔️ 📁 📛 `my_super_project` 👈 🔌 🎧-📁 🤙 `sql_app` ⏮️ 📊 💖 👉: - -``` -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - └── schemas.py -``` - -👉 🌖 🎏 📊 👥 ✔️ 🇸🇲 🔰. - -🔜 ➡️ 👀 ⚫️❔ 🔠 📁/🕹 🔨. - -## ✍ 🏒 🍕 - -➡️ 🔗 📁 `sql_app/database.py`. - -### 🐩 🏒 📟 - -➡️ 🥇 ✅ 🌐 😐 🏒 📟, ✍ 🏒 💽: - -```Python hl_lines="3 5 22" -{!../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -/// tip - -✔️ 🤯 👈 🚥 👆 💚 ⚙️ 🎏 💽, 💖 ✳, 👆 🚫 🚫 🔀 🎻. 👆 🔜 💪 ⚙️ 🎏 🏒 💽 🎓. - -/// - -#### 🗒 - -❌: - -```Python -check_same_thread=False -``` - -🌓 1️⃣ 🇸🇲 🔰: - -```Python -connect_args={"check_same_thread": False} -``` - -...⚫️ 💪 🕴 `SQLite`. - -/// info | "📡 ℹ" - -⚫️❔ 🎏 📡 ℹ [🗄 (🔗) 💽](../tutorial/sql-databases.md#_7){.internal-link target=_blank} ✔. - -/// - -### ⚒ 🏒 🔁-🔗 `PeeweeConnectionState` - -👑 ❔ ⏮️ 🏒 & FastAPI 👈 🏒 ⚓️ 🙇 🔛 🐍 `threading.local`, & ⚫️ 🚫 ✔️ 🎯 🌌 🔐 ⚫️ ⚖️ ➡️ 👆 🍵 🔗/🎉 🔗 (🔨 🇸🇲 🔰). - -& `threading.local` 🚫 🔗 ⏮️ 🆕 🔁 ⚒ 🏛 🐍. - -/// note | "📡 ℹ" - -`threading.local` ⚙️ ✔️ "🎱" 🔢 👈 ✔️ 🎏 💲 🔠 🧵. - -👉 ⚠ 🗝 🛠️ 🏗 ✔️ 1️⃣ 👁 🧵 📍 📨, 🙅‍♂ 🌖, 🙅‍♂ 🌘. - -⚙️ 👉, 🔠 📨 🔜 ✔️ 🚮 👍 💽 🔗/🎉, ❔ ☑ 🏁 🥅. - -✋️ FastAPI, ⚙️ 🆕 🔁 ⚒, 💪 🍵 🌅 🌘 1️⃣ 📨 🔛 🎏 🧵. & 🎏 🕰, 👁 📨, ⚫️ 💪 🏃 💗 👜 🎏 🧵 (🧵), ⚓️ 🔛 🚥 👆 ⚙️ `async def` ⚖️ 😐 `def`. 👉 ⚫️❔ 🤝 🌐 🎭 📈 FastAPI. - -/// - -✋️ 🐍 3️⃣.7️⃣ & 🔛 🚚 🌖 🏧 🎛 `threading.local`, 👈 💪 ⚙️ 🥉 🌐❔ `threading.local` 🔜 ⚙️, ✋️ 🔗 ⏮️ 🆕 🔁 ⚒. - -👥 🔜 ⚙️ 👈. ⚫️ 🤙 `contextvars`. - -👥 🔜 🔐 🔗 🍕 🏒 👈 ⚙️ `threading.local` & ❎ 👫 ⏮️ `contextvars`, ⏮️ 🔗 ℹ. - -👉 5️⃣📆 😑 🍖 🏗 (& ⚫️ 🤙), 👆 🚫 🤙 💪 🍕 🤔 ❔ ⚫️ 👷 ⚙️ ⚫️. - -👥 🔜 ✍ `PeeweeConnectionState`: - -```Python hl_lines="10-19" -{!../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -👉 🎓 😖 ⚪️➡️ 🎁 🔗 🎓 ⚙️ 🏒. - -⚫️ ✔️ 🌐 ⚛ ⚒ 🏒 ⚙️ `contextvars` ↩️ `threading.local`. - -`contextvars` 👷 🍖 🎏 🌘 `threading.local`. ✋️ 🎂 🏒 🔗 📟 🤔 👈 👉 🎓 👷 ⏮️ `threading.local`. - -, 👥 💪 ➕ 🎱 ⚒ ⚫️ 👷 🚥 ⚫️ ⚙️ `threading.local`. `__init__`, `__setattr__`, & `__getattr__` 🛠️ 🌐 ✔ 🎱 👉 ⚙️ 🏒 🍵 🤔 👈 ⚫️ 🔜 🔗 ⏮️ FastAPI. - -/// tip - -👉 🔜 ⚒ 🏒 🎭 ☑ 🕐❔ ⚙️ ⏮️ FastAPI. 🚫 🎲 📂 ⚖️ 📪 🔗 👈 ➖ ⚙️, 🏗 ❌, ♒️. - -✋️ ⚫️ 🚫 🤝 🏒 🔁 💎-🏋️. 👆 🔜 ⚙️ 😐 `def` 🔢 & 🚫 `async def`. - -/// - -### ⚙️ 🛃 `PeeweeConnectionState` 🎓 - -🔜, 📁 `._state` 🔗 🔢 🏒 💽 `db` 🎚 ⚙️ 🆕 `PeeweeConnectionState`: - -```Python hl_lines="24" -{!../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -/// tip - -⚒ 💭 👆 📁 `db._state` *⏮️* 🏗 `db`. - -/// - -/// tip - -👆 🔜 🎏 🙆 🎏 🏒 💽, 🔌 `PostgresqlDatabase`, `MySQLDatabase`, ♒️. - -/// - -## ✍ 💽 🏷 - -➡️ 🔜 👀 📁 `sql_app/models.py`. - -### ✍ 🏒 🏷 👆 💽 - -🔜 ✍ 🏒 🏷 (🎓) `User` & `Item`. - -👉 🎏 👆 🔜 🚥 👆 ⏩ 🏒 🔰 & ℹ 🏷 ✔️ 🎏 💽 🇸🇲 🔰. - -/// tip - -🏒 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽. - -✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐. - -/// - -🗄 `db` ⚪️➡️ `database` (📁 `database.py` ⚪️➡️ 🔛) & ⚙️ ⚫️ 📥. - -```Python hl_lines="3 6-12 15-21" -{!../../docs_src/sql_databases_peewee/sql_app/models.py!} -``` - -/// tip - -🏒 ✍ 📚 🎱 🔢. - -⚫️ 🔜 🔁 🚮 `id` 🔢 🔢 👑 🔑. - -⚫️ 🔜 ⚒ 📛 🏓 ⚓️ 🔛 🎓 📛. - - `Item`, ⚫️ 🔜 ✍ 🔢 `owner_id` ⏮️ 🔢 🆔 `User`. ✋️ 👥 🚫 📣 ⚫️ 🙆. - -/// - -## ✍ Pydantic 🏷 - -🔜 ➡️ ✅ 📁 `sql_app/schemas.py`. - -/// tip - -❎ 😨 🖖 🏒 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🏒 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷. - -👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠). - -👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯‍♂️. - -/// - -### ✍ Pydantic *🏷* / 🔗 - -✍ 🌐 🎏 Pydantic 🏷 🇸🇲 🔰: - -```Python hl_lines="16-18 21-22 25-30 34-35 38-39 42-48" -{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -/// tip - -📥 👥 🏗 🏷 ⏮️ `id`. - -👥 🚫 🎯 ✔ `id` 🔢 🏒 🏷, ✋️ 🏒 🚮 1️⃣ 🔁. - -👥 ❎ 🎱 `owner_id` 🔢 `Item`. - -/// - -### ✍ `PeeweeGetterDict` Pydantic *🏷* / 🔗 - -🕐❔ 👆 🔐 💛 🏒 🎚, 💖 `some_user.items`, 🏒 🚫 🚚 `list` `Item`. - -⚫️ 🚚 🎁 🛃 🎚 🎓 `ModelSelect`. - -⚫️ 💪 ✍ `list` 🚮 🏬 ⏮️ `list(some_user.items)`. - -✋️ 🎚 ⚫️ 🚫 `list`. & ⚫️ 🚫 ☑ 🐍 🚂. ↩️ 👉, Pydantic 🚫 💭 🔢 ❔ 🗜 ⚫️ `list` Pydantic *🏷* / 🔗. - -✋️ ⏮️ ⏬ Pydantic ✔ 🚚 🛃 🎓 👈 😖 ⚪️➡️ `pydantic.utils.GetterDict`, 🚚 🛠️ ⚙️ 🕐❔ ⚙️ `orm_mode = True` 🗃 💲 🐜 🏷 🔢. - -👥 🔜 ✍ 🛃 `PeeweeGetterDict` 🎓 & ⚙️ ⚫️ 🌐 🎏 Pydantic *🏷* / 🔗 👈 ⚙️ `orm_mode`: - -```Python hl_lines="3 8-13 31 49" -{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -📥 👥 ✅ 🚥 🔢 👈 ➖ 🔐 (✅ `.items` `some_user.items`) 👐 `peewee.ModelSelect`. - -& 🚥 👈 💼, 📨 `list` ⏮️ ⚫️. - -& ⤴️ 👥 ⚙️ ⚫️ Pydantic *🏷* / 🔗 👈 ⚙️ `orm_mode = True`, ⏮️ 📳 🔢 `getter_dict = PeeweeGetterDict`. - -/// tip - -👥 🕴 💪 ✍ 1️⃣ `PeeweeGetterDict` 🎓, & 👥 💪 ⚙️ ⚫️ 🌐 Pydantic *🏷* / 🔗. - -/// - -## 💩 🇨🇻 - -🔜 ➡️ 👀 📁 `sql_app/crud.py`. - -### ✍ 🌐 💩 🇨🇻 - -✍ 🌐 🎏 💩 🇨🇻 🇸🇲 🔰, 🌐 📟 📶 🎏: - -```Python hl_lines="1 4-5 8-9 12-13 16-20 23-24 27-30" -{!../../docs_src/sql_databases_peewee/sql_app/crud.py!} -``` - -📤 🔺 ⏮️ 📟 🇸🇲 🔰. - -👥 🚫 🚶‍♀️ `db` 🔢 🤭. ↩️ 👥 ⚙️ 🏷 🔗. 👉 ↩️ `db` 🎚 🌐 🎚, 👈 🔌 🌐 🔗 ⚛. 👈 ⚫️❔ 👥 ✔️ 🌐 `contextvars` ℹ 🔛. - -🆖, 🕐❔ 🛬 📚 🎚, 💖 `get_users`, 👥 🔗 🤙 `list`, 💖: - -```Python -list(models.User.select()) -``` - -👉 🎏 🤔 👈 👥 ✔️ ✍ 🛃 `PeeweeGetterDict`. ✋️ 🛬 🕳 👈 ⏪ `list` ↩️ `peewee.ModelSelect` `response_model` *➡ 🛠️* ⏮️ `List[models.User]` (👈 👥 🔜 👀 ⏪) 🔜 👷 ☑. - -## 👑 **FastAPI** 📱 - -& 🔜 📁 `sql_app/main.py` ➡️ 🛠️ & ⚙️ 🌐 🎏 🍕 👥 ✍ ⏭. - -### ✍ 💽 🏓 - -📶 🙃 🌌 ✍ 💽 🏓: - -```Python hl_lines="9-11" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### ✍ 🔗 - -✍ 🔗 👈 🔜 🔗 💽 ▶️️ ▶️ 📨 & 🔌 ⚫️ 🔚: - -```Python hl_lines="23-29" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -📥 👥 ✔️ 🛁 `yield` ↩️ 👥 🤙 🚫 ⚙️ 💽 🎚 🔗. - -⚫️ 🔗 💽 & ♻ 🔗 💽 🔗 🔢 👈 🔬 🔠 📨 (⚙️ `contextvars` 🎱 ⚪️➡️ 🔛). - -↩️ 💽 🔗 ⚠ 👤/🅾 🚧, 👉 🔗 ✍ ⏮️ 😐 `def` 🔢. - -& ⤴️, 🔠 *➡ 🛠️ 🔢* 👈 💪 🔐 💽 👥 🚮 ⚫️ 🔗. - -✋️ 👥 🚫 ⚙️ 💲 👐 👉 🔗 (⚫️ 🤙 🚫 🤝 🙆 💲, ⚫️ ✔️ 🛁 `yield`). , 👥 🚫 🚮 ⚫️ *➡ 🛠️ 🔢* ✋️ *➡ 🛠️ 👨‍🎨* `dependencies` 🔢: - -```Python hl_lines="32 40 47 59 65 72" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### 🔑 🔢 🎧-🔗 - -🌐 `contextvars` 🍕 👷, 👥 💪 ⚒ 💭 👥 ✔️ 🔬 💲 `ContextVar` 🔠 📨 👈 ⚙️ 💽, & 👈 💲 🔜 ⚙️ 💽 🇵🇸 (🔗, 💵, ♒️) 🎂 📨. - -👈, 👥 💪 ✍ ➕1️⃣ `async` 🔗 `reset_db_state()` 👈 ⚙️ 🎧-🔗 `get_db()`. ⚫️ 🔜 ⚒ 💲 🔑 🔢 (⏮️ 🔢 `dict`) 👈 🔜 ⚙️ 💽 🇵🇸 🎂 📨. & ⤴️ 🔗 `get_db()` 🔜 🏪 ⚫️ 💽 🇵🇸 (🔗, 💵, ♒️). - -```Python hl_lines="18-20" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -**⏭ 📨**, 👥 🔜 ⏲ 👈 🔑 🔢 🔄 `async` 🔗 `reset_db_state()` & ⤴️ ✍ 🆕 🔗 `get_db()` 🔗, 👈 🆕 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 (🔗, 💵, ♒️). - -/// tip - -FastAPI 🔁 🛠️, 1️⃣ 📨 💪 ▶️ ➖ 🛠️, & ⏭ 🏁, ➕1️⃣ 📨 💪 📨 & ▶️ 🏭 👍, & ⚫️ 🌐 💪 🛠️ 🎏 🧵. - -✋️ 🔑 🔢 🤔 👫 🔁 ⚒,, 🏒 💽 🇵🇸 ⚒ `async` 🔗 `reset_db_state()` 🔜 🚧 🚮 👍 💽 🎂 🎂 📨. - - & 🎏 🕰, 🎏 🛠️ 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 👈 🔜 🔬 🎂 📨. - -/// - -#### 🏒 🗳 - -🚥 👆 ⚙️ 🏒 🗳, ☑ 💽 `db.obj`. - -, 👆 🔜 ⏲ ⚫️ ⏮️: - -```Python hl_lines="3-4" -async def reset_db_state(): - database.db.obj._state._state.set(db_state_default.copy()) - database.db.obj._state.reset() -``` - -### ✍ 👆 **FastAPI** *➡ 🛠️* - -🔜, 😒, 📥 🐩 **FastAPI** *➡ 🛠️* 📟. - -```Python hl_lines="32-37 40-43 46-53 56-62 65-68 71-79" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### 🔃 `def` 🆚 `async def` - -🎏 ⏮️ 🇸🇲, 👥 🚫 🔨 🕳 💖: - -```Python -user = await models.User.select().first() -``` - -...✋️ ↩️ 👥 ⚙️: - -```Python -user = models.User.select().first() -``` - -, 🔄, 👥 🔜 📣 *➡ 🛠️ 🔢* & 🔗 🍵 `async def`, ⏮️ 😐 `def`,: - -```Python hl_lines="2" -# Something goes here -def read_users(skip: int = 0, limit: int = 100): - # Something goes here -``` - -## 🔬 🏒 ⏮️ 🔁 - -👉 🖼 🔌 ➕ *➡ 🛠️* 👈 🔬 📏 🏭 📨 ⏮️ `time.sleep(sleep_time)`. - -⚫️ 🔜 ✔️ 💽 🔗 📂 ▶️ & 🔜 ⌛ 🥈 ⏭ 🙇 🔙. & 🔠 🆕 📨 🔜 ⌛ 🕐 🥈 🌘. - -👉 🔜 💪 ➡️ 👆 💯 👈 👆 📱 ⏮️ 🏒 & FastAPI 🎭 ☑ ⏮️ 🌐 💩 🔃 🧵. - -🚥 👆 💚 ✅ ❔ 🏒 🔜 💔 👆 📱 🚥 ⚙️ 🍵 🛠️, 🚶 `sql_app/database.py` 📁 & 🏤 ⏸: - -```Python -# db._state = PeeweeConnectionState() -``` - -& 📁 `sql_app/main.py` 📁, 🏤 💪 `async` 🔗 `reset_db_state()` & ❎ ⚫️ ⏮️ `pass`: - -```Python -async def reset_db_state(): -# database.db._state._state.set(db_state_default.copy()) -# database.db._state.reset() - pass -``` - -⤴️ 🏃 👆 📱 ⏮️ Uvicorn: - -
- -```console -$ uvicorn sql_app.main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -📂 👆 🖥 http://127.0.0.1:8000/docs & ✍ 👩‍❤‍👨 👩‍💻. - -⤴️ 📂 1️⃣0️⃣ 📑 http://127.0.0.1:8000/docs#/default/read_🐌_👩‍💻_slowusers_ = 🎏 🕰. - -🚶 *➡ 🛠️* "🤚 `/slowusers/`" 🌐 📑. ⚙️ "🔄 ⚫️ 👅" 🔼 & 🛠️ 📨 🔠 📑, 1️⃣ ▶️️ ⏮️ 🎏. - -📑 🔜 ⌛ 🍖 & ⤴️ 👫 🔜 🎦 `Internal Server Error`. - -### ⚫️❔ 🔨 - -🥇 📑 🔜 ⚒ 👆 📱 ✍ 🔗 💽 & ⌛ 🥈 ⏭ 🙇 🔙 & 📪 💽 🔗. - -⤴️, 📨 ⏭ 📑, 👆 📱 🔜 ⌛ 🕐 🥈 🌘, & 🔛. - -👉 ⛓ 👈 ⚫️ 🔜 🔚 🆙 🏁 🏁 📑' 📨 ⏪ 🌘 ⏮️ 🕐. - -⤴️ 1️⃣ 🏁 📨 👈 ⌛ 🌘 🥈 🔜 🔄 📂 💽 🔗, ✋️ 1️⃣ 📚 ⏮️ 📨 🎏 📑 🔜 🎲 🍵 🎏 🧵 🥇 🕐, ⚫️ 🔜 ✔️ 🎏 💽 🔗 👈 ⏪ 📂, & 🏒 🔜 🚮 ❌ & 👆 🔜 👀 ⚫️ 📶, & 📨 🔜 ✔️ `Internal Server Error`. - -👉 🔜 🎲 🔨 🌅 🌘 1️⃣ 📚 📑. - -🚥 👆 ✔️ 💗 👩‍💻 💬 👆 📱 ⚫️❔ 🎏 🕰, 👉 ⚫️❔ 💪 🔨. - -& 👆 📱 ▶️ 🍵 🌅 & 🌖 👩‍💻 🎏 🕰, ⌛ 🕰 👁 📨 💪 📏 & 📏 ⏲ ❌. - -### 🔧 🏒 ⏮️ FastAPI - -🔜 🚶 🔙 📁 `sql_app/database.py`, & ✍ ⏸: - -```Python -db._state = PeeweeConnectionState() -``` - -& 📁 `sql_app/main.py` 📁, ✍ 💪 `async` 🔗 `reset_db_state()`: - -```Python -async def reset_db_state(): - database.db._state._state.set(db_state_default.copy()) - database.db._state.reset() -``` - -❎ 👆 🏃‍♂ 📱 & ▶️ ⚫️ 🔄. - -🔁 🎏 🛠️ ⏮️ 1️⃣0️⃣ 📑. 👉 🕰 🌐 👫 🔜 ⌛ & 👆 🔜 🤚 🌐 🏁 🍵 ❌. - -...👆 🔧 ⚫️ ❗ - -## 📄 🌐 📁 - - 💭 👆 🔜 ✔️ 📁 📛 `my_super_project` (⚖️ 👐 👆 💚) 👈 🔌 🎧-📁 🤙 `sql_app`. - -`sql_app` 🔜 ✔️ 📄 📁: - -* `sql_app/__init__.py`: 🛁 📁. - -* `sql_app/database.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -* `sql_app/models.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/models.py!} -``` - -* `sql_app/schemas.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -* `sql_app/crud.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/crud.py!} -``` - -* `sql_app/main.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -## 📡 ℹ - -/// warning - -👉 📶 📡 ℹ 👈 👆 🎲 🚫 💪. - -/// - -### ⚠ - -🏒 ⚙️ `threading.local` 🔢 🏪 ⚫️ 💽 "🇵🇸" 💽 (🔗, 💵, ♒️). - -`threading.local` ✍ 💲 🌟 ⏮️ 🧵, ✋️ 🔁 🛠️ 🔜 🏃 🌐 📟 (✅ 🔠 📨) 🎏 🧵, & 🎲 🚫 ✔. - -🔛 🔝 👈, 🔁 🛠️ 💪 🏃 🔁 📟 🧵 (⚙️ `asyncio.run_in_executor`), ✋️ 🔗 🎏 📨. - -👉 ⛓ 👈, ⏮️ 🏒 ⏮️ 🛠️, 💗 📋 💪 ⚙️ 🎏 `threading.local` 🔢 & 🔚 🆙 🤝 🎏 🔗 & 💽 (👈 👫 🚫🔜 🚫), & 🎏 🕰, 🚥 👫 🛠️ 🔁 👤/🅾-🚧 📟 🧵 (⏮️ 😐 `def` 🔢 FastAPI, *➡ 🛠️* & 🔗), 👈 📟 🏆 🚫 ✔️ 🔐 💽 🇵🇸 🔢, ⏪ ⚫️ 🍕 🎏 📨 & ⚫️ 🔜 💪 🤚 🔐 🎏 💽 🇵🇸. - -### 🔑 🔢 - -🐍 3️⃣.7️⃣ ✔️ `contextvars` 👈 💪 ✍ 🇧🇿 🔢 📶 🎏 `threading.local`, ✋️ 🔗 👫 🔁 ⚒. - -📤 📚 👜 ✔️ 🤯. - -`ContextVar` ✔️ ✍ 🔝 🕹, 💖: - -```Python -some_var = ContextVar("some_var", default="default value") -``` - -⚒ 💲 ⚙️ ⏮️ "🔑" (✅ ⏮️ 📨) ⚙️: - -```Python -some_var.set("new value") -``` - -🤚 💲 🙆 🔘 🔑 (✅ 🙆 🍕 🚚 ⏮️ 📨) ⚙️: - -```Python -some_var.get() -``` - -### ⚒ 🔑 🔢 `async` 🔗 `reset_db_state()` - -🚥 🍕 🔁 📟 ⚒ 💲 ⏮️ `some_var.set("updated in function")` (✅ 💖 `async` 🔗), 🎂 📟 ⚫️ & 📟 👈 🚶 ⏮️ (✅ 📟 🔘 `async` 🔢 🤙 ⏮️ `await`) 🔜 👀 👈 🆕 💲. - -, 👆 💼, 🚥 👥 ⚒ 🏒 🇵🇸 🔢 (⏮️ 🔢 `dict`) `async` 🔗, 🌐 🎂 🔗 📟 👆 📱 🔜 👀 👉 💲 & 🔜 💪 ♻ ⚫️ 🎂 📨. - -& 🔑 🔢 🔜 ⚒ 🔄 ⏭ 📨, 🚥 👫 🛠️. - -### ⚒ 💽 🇵🇸 🔗 `get_db()` - -`get_db()` 😐 `def` 🔢, **FastAPI** 🔜 ⚒ ⚫️ 🏃 🧵, ⏮️ *📁* "🔑", 🧑‍🤝‍🧑 🎏 💲 🔑 🔢 ( `dict` ⏮️ ⏲ 💽 🇵🇸). ⤴️ ⚫️ 💪 🚮 💽 🇵🇸 👈 `dict`, 💖 🔗, ♒️. - -✋️ 🚥 💲 🔑 🔢 (🔢 `dict`) ⚒ 👈 😐 `def` 🔢, ⚫️ 🔜 ✍ 🆕 💲 👈 🔜 🚧 🕴 👈 🧵 🧵, & 🎂 📟 (💖 *➡ 🛠️ 🔢*) 🚫🔜 ✔️ 🔐 ⚫️. `get_db()` 👥 💪 🕴 ⚒ 💲 `dict`, ✋️ 🚫 🎂 `dict` ⚫️. - -, 👥 💪 ✔️ `async` 🔗 `reset_db_state()` ⚒ `dict` 🔑 🔢. 👈 🌌, 🌐 📟 ✔️ 🔐 🎏 `dict` 💽 🇵🇸 👁 📨. - -### 🔗 & 🔌 🔗 `get_db()` - -⤴️ ⏭ ❔ 🔜, ⚫️❔ 🚫 🔗 & 🔌 💽 `async` 🔗 ⚫️, ↩️ `get_db()`❓ - -`async` 🔗 ✔️ `async` 🔑 🔢 🛡 🎂 📨, ✋️ 🏗 & 📪 💽 🔗 ⚠ 🚧, ⚫️ 💪 📉 🎭 🚥 ⚫️ 📤. - -👥 💪 😐 `def` 🔗 `get_db()`. diff --git a/docs/en/docs/advanced/testing-database.md b/docs/en/docs/advanced/testing-database.md deleted file mode 100644 index 2b704f229..000000000 --- a/docs/en/docs/advanced/testing-database.md +++ /dev/null @@ -1,111 +0,0 @@ -# Testing a Database - -/// info - -These docs are about to be updated. 🎉 - -The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0. - -The new docs will include Pydantic v2 and will use SQLModel (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well. - -/// - -You can use the same dependency overrides from [Testing Dependencies with Overrides](testing-dependencies.md){.internal-link target=_blank} to alter a database for testing. - -You could want to set up a different database for testing, rollback the data after the tests, pre-fill it with some testing data, etc. - -The main idea is exactly the same you saw in that previous chapter. - -## Add tests for the SQL app - -Let's update the example from [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} to use a testing database. - -All the app code is the same, you can go back to that chapter check how it was. - -The only changes here are in the new testing file. - -Your normal dependency `get_db()` would return a database session. - -In the test, you could use a dependency override to return your *custom* database session instead of the one that would be used normally. - -In this example we'll create a temporary database only for the tests. - -## File structure - -We create a new file at `sql_app/tests/test_sql_app.py`. - -So the new file structure looks like: - -``` hl_lines="9-11" -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - ├── schemas.py - └── tests - ├── __init__.py - └── test_sql_app.py -``` - -## Create the new database session - -First, we create a new database session with the new database. - -We'll use an in-memory database that persists during the tests instead of the local file `sql_app.db`. - -But the rest of the session code is more or less the same, we just copy it. - -```Python hl_lines="8-13" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -/// tip - -You could reduce duplication in that code by putting it in a function and using it from both `database.py` and `tests/test_sql_app.py`. - -For simplicity and to focus on the specific testing code, we are just copying it. - -/// - -## Create the database - -Because now we are going to use a new database in a new file, we need to make sure we create the database with: - -```Python -Base.metadata.create_all(bind=engine) -``` - -That is normally called in `main.py`, but the line in `main.py` uses the database file `sql_app.db`, and we need to make sure we create `test.db` for the tests. - -So we add that line here, with the new file. - -```Python hl_lines="16" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -## Dependency override - -Now we create the dependency override and add it to the overrides for our app. - -```Python hl_lines="19-24 27" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -/// tip - -The code for `override_get_db()` is almost exactly the same as for `get_db()`, but in `override_get_db()` we use the `TestingSessionLocal` for the testing database instead. - -/// - -## Test the app - -Then we can just test the app as normally. - -```Python hl_lines="32-47" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -And all the modifications we made in the database during the tests will be in the `test.db` database instead of the main `sql_app.db`. diff --git a/docs/en/docs/how-to/async-sql-encode-databases.md b/docs/en/docs/how-to/async-sql-encode-databases.md deleted file mode 100644 index a72316c4d..000000000 --- a/docs/en/docs/how-to/async-sql-encode-databases.md +++ /dev/null @@ -1,201 +0,0 @@ -# ~~Async SQL (Relational) Databases with Encode/Databases~~ (deprecated) - -/// info - -These docs are about to be updated. 🎉 - -The current version assumes Pydantic v1. - -The new docs will include Pydantic v2 and will use SQLModel once it is updated to use Pydantic v2 as well. - -/// - -/// warning | "Deprecated" - -This tutorial is deprecated and will be removed in a future version. - -/// - -You can also use `encode/databases` with **FastAPI** to connect to databases using `async` and `await`. - -It is compatible with: - -* PostgreSQL -* MySQL -* SQLite - -In this example, we'll use **SQLite**, because it uses a single file and Python has integrated support. So, you can copy this example and run it as is. - -Later, for your production application, you might want to use a database server like **PostgreSQL**. - -/// tip - -You could adopt ideas from the section about SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), like using utility functions to perform operations in the database, independent of your **FastAPI** code. - -This section doesn't apply those ideas, to be equivalent to the counterpart in Starlette. - -/// - -## Import and set up `SQLAlchemy` - -* Import `SQLAlchemy`. -* Create a `metadata` object. -* Create a table `notes` using the `metadata` object. - -```Python hl_lines="4 14 16-22" -{!../../docs_src/async_sql_databases/tutorial001.py!} -``` - -/// tip - -Notice that all this code is pure SQLAlchemy Core. - -`databases` is not doing anything here yet. - -/// - -## Import and set up `databases` - -* Import `databases`. -* Create a `DATABASE_URL`. -* Create a `database` object. - -```Python hl_lines="3 9 12" -{!../../docs_src/async_sql_databases/tutorial001.py!} -``` - -/// tip - -If you were connecting to a different database (e.g. PostgreSQL), you would need to change the `DATABASE_URL`. - -/// - -## Create the tables - -In this case, we are creating the tables in the same Python file, but in production, you would probably want to create them with Alembic, integrated with migrations, etc. - -Here, this section would run directly, right before starting your **FastAPI** application. - -* Create an `engine`. -* Create all the tables from the `metadata` object. - -```Python hl_lines="25-28" -{!../../docs_src/async_sql_databases/tutorial001.py!} -``` - -## Create models - -Create Pydantic models for: - -* Notes to be created (`NoteIn`). -* Notes to be returned (`Note`). - -```Python hl_lines="31-33 36-39" -{!../../docs_src/async_sql_databases/tutorial001.py!} -``` - -By creating these Pydantic models, the input data will be validated, serialized (converted), and annotated (documented). - -So, you will be able to see it all in the interactive API docs. - -## Connect and disconnect - -* Create your `FastAPI` application. -* Create event handlers to connect and disconnect from the database. - -```Python hl_lines="42 45-47 50-52" -{!../../docs_src/async_sql_databases/tutorial001.py!} -``` - -## Read notes - -Create the *path operation function* to read notes: - -```Python hl_lines="55-58" -{!../../docs_src/async_sql_databases/tutorial001.py!} -``` - -/// note - -Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. - -/// - -### Notice the `response_model=List[Note]` - -It uses `typing.List`. - -That documents (and validates, serializes, filters) the output data, as a `list` of `Note`s. - -## Create notes - -Create the *path operation function* to create notes: - -```Python hl_lines="61-65" -{!../../docs_src/async_sql_databases/tutorial001.py!} -``` - -/// info - -In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. - -The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. - -/// - -/// note - -Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. - -/// - -### About `{**note.dict(), "id": last_record_id}` - -`note` is a Pydantic `Note` object. - -`note.dict()` returns a `dict` with its data, something like: - -```Python -{ - "text": "Some note", - "completed": False, -} -``` - -but it doesn't have the `id` field. - -So we create a new `dict`, that contains the key-value pairs from `note.dict()` with: - -```Python -{**note.dict()} -``` - -`**note.dict()` "unpacks" the key value pairs directly, so, `{**note.dict()}` would be, more or less, a copy of `note.dict()`. - -And then, we extend that copy `dict`, adding another key-value pair: `"id": last_record_id`: - -```Python -{**note.dict(), "id": last_record_id} -``` - -So, the final result returned would be something like: - -```Python -{ - "id": 1, - "text": "Some note", - "completed": False, -} -``` - -## Check it - -You can copy this code as is, and see the docs at http://127.0.0.1:8000/docs. - -There you can see all your API documented and interact with it: - - - -## More info - -You can read more about `encode/databases` at its GitHub page. diff --git a/docs/en/docs/how-to/nosql-databases-couchbase.md b/docs/en/docs/how-to/nosql-databases-couchbase.md deleted file mode 100644 index feb4025dd..000000000 --- a/docs/en/docs/how-to/nosql-databases-couchbase.md +++ /dev/null @@ -1,178 +0,0 @@ -# ~~NoSQL (Distributed / Big Data) Databases with Couchbase~~ (deprecated) - -/// info - -These docs are about to be updated. 🎉 - -The current version assumes Pydantic v1. - -The new docs will hopefully use Pydantic v2 and will use ODMantic with MongoDB. - -/// - -/// warning | "Deprecated" - -This tutorial is deprecated and will be removed in a future version. - -/// - -**FastAPI** can also be integrated with any NoSQL. - -Here we'll see an example using **Couchbase**, a document based NoSQL database. - -You can adapt it to any other NoSQL database like: - -* **MongoDB** -* **Cassandra** -* **CouchDB** -* **ArangoDB** -* **ElasticSearch**, etc. - -/// tip - -There is an official project generator with **FastAPI** and **Couchbase**, all based on **Docker**, including a frontend and more tools: https://github.com/tiangolo/full-stack-fastapi-couchbase - -/// - -## Import Couchbase components - -For now, don't pay attention to the rest, only the imports: - -```Python hl_lines="3-5" -{!../../docs_src/nosql_databases/tutorial001.py!} -``` - -## Define a constant to use as a "document type" - -We will use it later as a fixed field `type` in our documents. - -This is not required by Couchbase, but is a good practice that will help you afterwards. - -```Python hl_lines="9" -{!../../docs_src/nosql_databases/tutorial001.py!} -``` - -## Add a function to get a `Bucket` - -In **Couchbase**, a bucket is a set of documents, that can be of different types. - -They are generally all related to the same application. - -The analogy in the relational database world would be a "database" (a specific database, not the database server). - -The analogy in **MongoDB** would be a "collection". - -In the code, a `Bucket` represents the main entrypoint of communication with the database. - -This utility function will: - -* Connect to a **Couchbase** cluster (that might be a single machine). - * Set defaults for timeouts. -* Authenticate in the cluster. -* Get a `Bucket` instance. - * Set defaults for timeouts. -* Return it. - -```Python hl_lines="12-21" -{!../../docs_src/nosql_databases/tutorial001.py!} -``` - -## Create Pydantic models - -As **Couchbase** "documents" are actually just "JSON objects", we can model them with Pydantic. - -### `User` model - -First, let's create a `User` model: - -```Python hl_lines="24-28" -{!../../docs_src/nosql_databases/tutorial001.py!} -``` - -We will use this model in our *path operation function*, so, we don't include in it the `hashed_password`. - -### `UserInDB` model - -Now, let's create a `UserInDB` model. - -This will have the data that is actually stored in the database. - -We don't create it as a subclass of Pydantic's `BaseModel` but as a subclass of our own `User`, because it will have all the attributes in `User` plus a couple more: - -```Python hl_lines="31-33" -{!../../docs_src/nosql_databases/tutorial001.py!} -``` - -/// note - -Notice that we have a `hashed_password` and a `type` field that will be stored in the database. - -But it is not part of the general `User` model (the one we will return in the *path operation*). - -/// - -## Get the user - -Now create a function that will: - -* Take a username. -* Generate a document ID from it. -* Get the document with that ID. -* Put the contents of the document in a `UserInDB` model. - -By creating a function that is only dedicated to getting your user from a `username` (or any other parameter) independent of your *path operation function*, you can more easily reuse it in multiple parts and also add unit tests for it: - -```Python hl_lines="36-42" -{!../../docs_src/nosql_databases/tutorial001.py!} -``` - -### f-strings - -If you are not familiar with the `f"userprofile::{username}"`, it is a Python "f-string". - -Any variable that is put inside of `{}` in an f-string will be expanded / injected in the string. - -### `dict` unpacking - -If you are not familiar with the `UserInDB(**result.value)`, it is using `dict` "unpacking". - -It will take the `dict` at `result.value`, and take each of its keys and values and pass them as key-values to `UserInDB` as keyword arguments. - -So, if the `dict` contains: - -```Python -{ - "username": "johndoe", - "hashed_password": "some_hash", -} -``` - -It will be passed to `UserInDB` as: - -```Python -UserInDB(username="johndoe", hashed_password="some_hash") -``` - -## Create your **FastAPI** code - -### Create the `FastAPI` app - -```Python hl_lines="46" -{!../../docs_src/nosql_databases/tutorial001.py!} -``` - -### Create the *path operation function* - -As our code is calling Couchbase and we are not using the experimental Python await support, we should declare our function with normal `def` instead of `async def`. - -Also, Couchbase recommends not using a single `Bucket` object in multiple "threads", so, we can just get the bucket directly and pass it to our utility functions: - -```Python hl_lines="49-53" -{!../../docs_src/nosql_databases/tutorial001.py!} -``` - -## Recap - -You can integrate any third party NoSQL database, just using their standard packages. - -The same applies to any other external tool, system or API. diff --git a/docs/en/docs/how-to/sql-databases-peewee.md b/docs/en/docs/how-to/sql-databases-peewee.md deleted file mode 100644 index e73ca369b..000000000 --- a/docs/en/docs/how-to/sql-databases-peewee.md +++ /dev/null @@ -1,594 +0,0 @@ -# ~~SQL (Relational) Databases with Peewee~~ (deprecated) - -/// warning | "Deprecated" - -This tutorial is deprecated and will be removed in a future version. - -/// - -/// warning - -If you are just starting, the tutorial [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} that uses SQLAlchemy should be enough. - -Feel free to skip this. - -Peewee is not recommended with FastAPI as it doesn't play well with anything async Python. There are several better alternatives. - -/// - -/// info - -These docs assume Pydantic v1. - -Because Pewee doesn't play well with anything async and there are better alternatives, I won't update these docs for Pydantic v2, they are kept for now only for historical purposes. - -The examples here are no longer tested in CI (as they were before). - -/// - -If you are starting a project from scratch, you are probably better off with SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), or any other async ORM. - -If you already have a code base that uses Peewee ORM, you can check here how to use it with **FastAPI**. - -/// warning | "Python 3.7+ required" - -You will need Python 3.7 or above to safely use Peewee with FastAPI. - -/// - -## Peewee for async - -Peewee was not designed for async frameworks, or with them in mind. - -Peewee has some heavy assumptions about its defaults and about how it should be used. - -If you are developing an application with an older non-async framework, and can work with all its defaults, **it can be a great tool**. - -But if you need to change some of the defaults, support more than one predefined database, work with an async framework (like FastAPI), etc, you will need to add quite some complex extra code to override those defaults. - -Nevertheless, it's possible to do it, and here you'll see exactly what code you have to add to be able to use Peewee with FastAPI. - -/// note | "Technical Details" - -You can read more about Peewee's stand about async in Python in the docs, an issue, a PR. - -/// - -## The same app - -We are going to create the same application as in the SQLAlchemy tutorial ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}). - -Most of the code is actually the same. - -So, we are going to focus only on the differences. - -## File structure - -Let's say you have a directory named `my_super_project` that contains a sub-directory called `sql_app` with a structure like this: - -``` -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - └── schemas.py -``` - -This is almost the same structure as we had for the SQLAlchemy tutorial. - -Now let's see what each file/module does. - -## Create the Peewee parts - -Let's refer to the file `sql_app/database.py`. - -### The standard Peewee code - -Let's first check all the normal Peewee code, create a Peewee database: - -```Python hl_lines="3 5 22" -{!../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -/// tip - -Keep in mind that if you wanted to use a different database, like PostgreSQL, you couldn't just change the string. You would need to use a different Peewee database class. - -/// - -#### Note - -The argument: - -```Python -check_same_thread=False -``` - -is equivalent to the one in the SQLAlchemy tutorial: - -```Python -connect_args={"check_same_thread": False} -``` - -...it is needed only for `SQLite`. - -/// info | "Technical Details" - -Exactly the same technical details as in [SQL (Relational) Databases](../tutorial/sql-databases.md#note){.internal-link target=_blank} apply. - -/// - -### Make Peewee async-compatible `PeeweeConnectionState` - -The main issue with Peewee and FastAPI is that Peewee relies heavily on Python's `threading.local`, and it doesn't have a direct way to override it or let you handle connections/sessions directly (as is done in the SQLAlchemy tutorial). - -And `threading.local` is not compatible with the new async features of modern Python. - -/// note | "Technical Details" - -`threading.local` is used to have a "magic" variable that has a different value for each thread. - -This was useful in older frameworks designed to have one single thread per request, no more, no less. - -Using this, each request would have its own database connection/session, which is the actual final goal. - -But FastAPI, using the new async features, could handle more than one request on the same thread. And at the same time, for a single request, it could run multiple things in different threads (in a threadpool), depending on if you use `async def` or normal `def`. This is what gives all the performance improvements to FastAPI. - -/// - -But Python 3.7 and above provide a more advanced alternative to `threading.local`, that can also be used in the places where `threading.local` would be used, but is compatible with the new async features. - -We are going to use that. It's called `contextvars`. - -We are going to override the internal parts of Peewee that use `threading.local` and replace them with `contextvars`, with the corresponding updates. - -This might seem a bit complex (and it actually is), you don't really need to completely understand how it works to use it. - -We will create a `PeeweeConnectionState`: - -```Python hl_lines="10-19" -{!../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -This class inherits from a special internal class used by Peewee. - -It has all the logic to make Peewee use `contextvars` instead of `threading.local`. - -`contextvars` works a bit differently than `threading.local`. But the rest of Peewee's internal code assumes that this class works with `threading.local`. - -So, we need to do some extra tricks to make it work as if it was just using `threading.local`. The `__init__`, `__setattr__`, and `__getattr__` implement all the required tricks for this to be used by Peewee without knowing that it is now compatible with FastAPI. - -/// tip - -This will just make Peewee behave correctly when used with FastAPI. Not randomly opening or closing connections that are being used, creating errors, etc. - -But it doesn't give Peewee async super-powers. You should still use normal `def` functions and not `async def`. - -/// - -### Use the custom `PeeweeConnectionState` class - -Now, overwrite the `._state` internal attribute in the Peewee database `db` object using the new `PeeweeConnectionState`: - -```Python hl_lines="24" -{!../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -/// tip - -Make sure you overwrite `db._state` *after* creating `db`. - -/// - -/// tip - -You would do the same for any other Peewee database, including `PostgresqlDatabase`, `MySQLDatabase`, etc. - -/// - -## Create the database models - -Let's now see the file `sql_app/models.py`. - -### Create Peewee models for our data - -Now create the Peewee models (classes) for `User` and `Item`. - -This is the same you would do if you followed the Peewee tutorial and updated the models to have the same data as in the SQLAlchemy tutorial. - -/// tip - -Peewee also uses the term "**model**" to refer to these classes and instances that interact with the database. - -But Pydantic also uses the term "**model**" to refer to something different, the data validation, conversion, and documentation classes and instances. - -/// - -Import `db` from `database` (the file `database.py` from above) and use it here. - -```Python hl_lines="3 6-12 15-21" -{!../../docs_src/sql_databases_peewee/sql_app/models.py!} -``` - -/// tip - -Peewee creates several magic attributes. - -It will automatically add an `id` attribute as an integer to be the primary key. - -It will chose the name of the tables based on the class names. - -For the `Item`, it will create an attribute `owner_id` with the integer ID of the `User`. But we don't declare it anywhere. - -/// - -## Create the Pydantic models - -Now let's check the file `sql_app/schemas.py`. - -/// tip - -To avoid confusion between the Peewee *models* and the Pydantic *models*, we will have the file `models.py` with the Peewee models, and the file `schemas.py` with the Pydantic models. - -These Pydantic models define more or less a "schema" (a valid data shape). - -So this will help us avoiding confusion while using both. - -/// - -### Create the Pydantic *models* / schemas - -Create all the same Pydantic models as in the SQLAlchemy tutorial: - -```Python hl_lines="16-18 21-22 25-30 34-35 38-39 42-48" -{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -/// tip - -Here we are creating the models with an `id`. - -We didn't explicitly specify an `id` attribute in the Peewee models, but Peewee adds one automatically. - -We are also adding the magic `owner_id` attribute to `Item`. - -/// - -### Create a `PeeweeGetterDict` for the Pydantic *models* / schemas - -When you access a relationship in a Peewee object, like in `some_user.items`, Peewee doesn't provide a `list` of `Item`. - -It provides a special custom object of class `ModelSelect`. - -It's possible to create a `list` of its items with `list(some_user.items)`. - -But the object itself is not a `list`. And it's also not an actual Python generator. Because of this, Pydantic doesn't know by default how to convert it to a `list` of Pydantic *models* / schemas. - -But recent versions of Pydantic allow providing a custom class that inherits from `pydantic.utils.GetterDict`, to provide the functionality used when using the `orm_mode = True` to retrieve the values for ORM model attributes. - -We are going to create a custom `PeeweeGetterDict` class and use it in all the same Pydantic *models* / schemas that use `orm_mode`: - -```Python hl_lines="3 8-13 31 49" -{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -Here we are checking if the attribute that is being accessed (e.g. `.items` in `some_user.items`) is an instance of `peewee.ModelSelect`. - -And if that's the case, just return a `list` with it. - -And then we use it in the Pydantic *models* / schemas that use `orm_mode = True`, with the configuration variable `getter_dict = PeeweeGetterDict`. - -/// tip - -We only need to create one `PeeweeGetterDict` class, and we can use it in all the Pydantic *models* / schemas. - -/// - -## CRUD utils - -Now let's see the file `sql_app/crud.py`. - -### Create all the CRUD utils - -Create all the same CRUD utils as in the SQLAlchemy tutorial, all the code is very similar: - -```Python hl_lines="1 4-5 8-9 12-13 16-20 23-24 27-30" -{!../../docs_src/sql_databases_peewee/sql_app/crud.py!} -``` - -There are some differences with the code for the SQLAlchemy tutorial. - -We don't pass a `db` attribute around. Instead we use the models directly. This is because the `db` object is a global object, that includes all the connection logic. That's why we had to do all the `contextvars` updates above. - -Aso, when returning several objects, like in `get_users`, we directly call `list`, like in: - -```Python -list(models.User.select()) -``` - -This is for the same reason that we had to create a custom `PeeweeGetterDict`. But by returning something that is already a `list` instead of the `peewee.ModelSelect` the `response_model` in the *path operation* with `List[models.User]` (that we'll see later) will work correctly. - -## Main **FastAPI** app - -And now in the file `sql_app/main.py` let's integrate and use all the other parts we created before. - -### Create the database tables - -In a very simplistic way create the database tables: - -```Python hl_lines="9-11" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### Create a dependency - -Create a dependency that will connect the database right at the beginning of a request and disconnect it at the end: - -```Python hl_lines="23-29" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -Here we have an empty `yield` because we are actually not using the database object directly. - -It is connecting to the database and storing the connection data in an internal variable that is independent for each request (using the `contextvars` tricks from above). - -Because the database connection is potentially I/O blocking, this dependency is created with a normal `def` function. - -And then, in each *path operation function* that needs to access the database we add it as a dependency. - -But we are not using the value given by this dependency (it actually doesn't give any value, as it has an empty `yield`). So, we don't add it to the *path operation function* but to the *path operation decorator* in the `dependencies` parameter: - -```Python hl_lines="32 40 47 59 65 72" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### Context variable sub-dependency - -For all the `contextvars` parts to work, we need to make sure we have an independent value in the `ContextVar` for each request that uses the database, and that value will be used as the database state (connection, transactions, etc) for the whole request. - -For that, we need to create another `async` dependency `reset_db_state()` that is used as a sub-dependency in `get_db()`. It will set the value for the context variable (with just a default `dict`) that will be used as the database state for the whole request. And then the dependency `get_db()` will store in it the database state (connection, transactions, etc). - -```Python hl_lines="18-20" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -For the **next request**, as we will reset that context variable again in the `async` dependency `reset_db_state()` and then create a new connection in the `get_db()` dependency, that new request will have its own database state (connection, transactions, etc). - -/// tip - -As FastAPI is an async framework, one request could start being processed, and before finishing, another request could be received and start processing as well, and it all could be processed in the same thread. - -But context variables are aware of these async features, so, a Peewee database state set in the `async` dependency `reset_db_state()` will keep its own data throughout the entire request. - -And at the same time, the other concurrent request will have its own database state that will be independent for the whole request. - -/// - -#### Peewee Proxy - -If you are using a Peewee Proxy, the actual database is at `db.obj`. - -So, you would reset it with: - -```Python hl_lines="3-4" -async def reset_db_state(): - database.db.obj._state._state.set(db_state_default.copy()) - database.db.obj._state.reset() -``` - -### Create your **FastAPI** *path operations* - -Now, finally, here's the standard **FastAPI** *path operations* code. - -```Python hl_lines="32-37 40-43 46-53 56-62 65-68 71-79" -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### About `def` vs `async def` - -The same as with SQLAlchemy, we are not doing something like: - -```Python -user = await models.User.select().first() -``` - -...but instead we are using: - -```Python -user = models.User.select().first() -``` - -So, again, we should declare the *path operation functions* and the dependency without `async def`, just with a normal `def`, as: - -```Python hl_lines="2" -# Something goes here -def read_users(skip: int = 0, limit: int = 100): - # Something goes here -``` - -## Testing Peewee with async - -This example includes an extra *path operation* that simulates a long processing request with `time.sleep(sleep_time)`. - -It will have the database connection open at the beginning and will just wait some seconds before replying back. And each new request will wait one second less. - -This will easily let you test that your app with Peewee and FastAPI is behaving correctly with all the stuff about threads. - -If you want to check how Peewee would break your app if used without modification, go the `sql_app/database.py` file and comment the line: - -```Python -# db._state = PeeweeConnectionState() -``` - -And in the file `sql_app/main.py` file, comment the body of the `async` dependency `reset_db_state()` and replace it with a `pass`: - -```Python -async def reset_db_state(): -# database.db._state._state.set(db_state_default.copy()) -# database.db._state.reset() - pass -``` - -Then run your app with Uvicorn: - -
- -```console -$ uvicorn sql_app.main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -Open your browser at http://127.0.0.1:8000/docs and create a couple of users. - -Then open 10 tabs at http://127.0.0.1:8000/docs#/default/read_slow_users_slowusers__get at the same time. - -Go to the *path operation* "Get `/slowusers/`" in all of the tabs. Use the "Try it out" button and execute the request in each tab, one right after the other. - -The tabs will wait for a bit and then some of them will show `Internal Server Error`. - -### What happens - -The first tab will make your app create a connection to the database and wait for some seconds before replying back and closing the database connection. - -Then, for the request in the next tab, your app will wait for one second less, and so on. - -This means that it will end up finishing some of the last tabs' requests earlier than some of the previous ones. - -Then one the last requests that wait less seconds will try to open a database connection, but as one of those previous requests for the other tabs will probably be handled in the same thread as the first one, it will have the same database connection that is already open, and Peewee will throw an error and you will see it in the terminal, and the response will have an `Internal Server Error`. - -This will probably happen for more than one of those tabs. - -If you had multiple clients talking to your app exactly at the same time, this is what could happen. - -And as your app starts to handle more and more clients at the same time, the waiting time in a single request needs to be shorter and shorter to trigger the error. - -### Fix Peewee with FastAPI - -Now go back to the file `sql_app/database.py`, and uncomment the line: - -```Python -db._state = PeeweeConnectionState() -``` - -And in the file `sql_app/main.py` file, uncomment the body of the `async` dependency `reset_db_state()`: - -```Python -async def reset_db_state(): - database.db._state._state.set(db_state_default.copy()) - database.db._state.reset() -``` - -Terminate your running app and start it again. - -Repeat the same process with the 10 tabs. This time all of them will wait and you will get all the results without errors. - -...You fixed it! - -## Review all the files - - Remember you should have a directory named `my_super_project` (or however you want) that contains a sub-directory called `sql_app`. - -`sql_app` should have the following files: - -* `sql_app/__init__.py`: is an empty file. - -* `sql_app/database.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -* `sql_app/models.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/models.py!} -``` - -* `sql_app/schemas.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -* `sql_app/crud.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/crud.py!} -``` - -* `sql_app/main.py`: - -```Python -{!../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -## Technical Details - -/// warning - -These are very technical details that you probably don't need. - -/// - -### The problem - -Peewee uses `threading.local` by default to store it's database "state" data (connection, transactions, etc). - -`threading.local` creates a value exclusive to the current thread, but an async framework would run all the code (e.g. for each request) in the same thread, and possibly not in order. - -On top of that, an async framework could run some sync code in a threadpool (using `asyncio.run_in_executor`), but belonging to the same request. - -This means that, with Peewee's current implementation, multiple tasks could be using the same `threading.local` variable and end up sharing the same connection and data (that they shouldn't), and at the same time, if they execute sync I/O-blocking code in a threadpool (as with normal `def` functions in FastAPI, in *path operations* and dependencies), that code won't have access to the database state variables, even while it's part of the same request and it should be able to get access to the same database state. - -### Context variables - -Python 3.7 has `contextvars` that can create a local variable very similar to `threading.local`, but also supporting these async features. - -There are several things to keep in mind. - -The `ContextVar` has to be created at the top of the module, like: - -```Python -some_var = ContextVar("some_var", default="default value") -``` - -To set a value used in the current "context" (e.g. for the current request) use: - -```Python -some_var.set("new value") -``` - -To get a value anywhere inside of the context (e.g. in any part handling the current request) use: - -```Python -some_var.get() -``` - -### Set context variables in the `async` dependency `reset_db_state()` - -If some part of the async code sets the value with `some_var.set("updated in function")` (e.g. like the `async` dependency), the rest of the code in it and the code that goes after (including code inside of `async` functions called with `await`) will see that new value. - -So, in our case, if we set the Peewee state variable (with a default `dict`) in the `async` dependency, all the rest of the internal code in our app will see this value and will be able to reuse it for the whole request. - -And the context variable would be set again for the next request, even if they are concurrent. - -### Set database state in the dependency `get_db()` - -As `get_db()` is a normal `def` function, **FastAPI** will make it run in a threadpool, with a *copy* of the "context", holding the same value for the context variable (the `dict` with the reset database state). Then it can add database state to that `dict`, like the connection, etc. - -But if the value of the context variable (the default `dict`) was set in that normal `def` function, it would create a new value that would stay only in that thread of the threadpool, and the rest of the code (like the *path operation functions*) wouldn't have access to it. In `get_db()` we can only set values in the `dict`, but not the entire `dict` itself. - -So, we need to have the `async` dependency `reset_db_state()` to set the `dict` in the context variable. That way, all the code has access to the same `dict` for the database state for a single request. - -### Connect and disconnect in the dependency `get_db()` - -Then the next question would be, why not just connect and disconnect the database in the `async` dependency itself, instead of in `get_db()`? - -The `async` dependency has to be `async` for the context variable to be preserved for the rest of the request, but creating and closing the database connection is potentially blocking, so it could degrade performance if it was there. - -So we also need the normal `def` dependency `get_db()`. diff --git a/docs/en/docs/how-to/testing-database.md b/docs/en/docs/how-to/testing-database.md new file mode 100644 index 000000000..d0ed15bca --- /dev/null +++ b/docs/en/docs/how-to/testing-database.md @@ -0,0 +1,7 @@ +# Testing a Database + +You can study about databases, SQL, and SQLModel in the SQLModel docs. 🤓 + +There's a mini tutorial on using SQLModel with FastAPI. ✨ + +That tutorial includes a section about testing SQL databases. 😎 diff --git a/docs/en/docs/img/tutorial/sql-databases/image01.png b/docs/en/docs/img/tutorial/sql-databases/image01.png index 8e575abd65aaf37a33fed5bdae4029955dffb090..bfcdb57a0743c5fdcd453007987a19d878af1f1a 100644 GIT binary patch literal 69755 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 literal 78949 zcmdSAWmKEZw>KP0aVw?8rG*xXTX8FeA}vyiySrZoyq1 z=zagsdY=#Htn++)ueCykxn}mvmf3sHZzkcN6{PX7$*}Z@wz#l9C-~~Wd zQe4G-W(NV(P*Gp%K0s!+|9Sl3^Rse;wz;1bU3TNsPe1W;b{*^SnF5u0TM)0(<=OMi zjl<21zfF)@|D?Ct>7GNQ`1*+U1(jLK;T7tKCn`@qb0XJ0yj=F0ocEf{_acvm1w|)Q$HSdlj>n`l+E?m%NeuJ3|mpD8yc^2^D-v(9i-MS2X9X65( zVpc8|01AqKZh^VeLaX?C8@Dd_~{an%tyie zBH6#)R=C#Ogs^a8UI?=ke;F9+?KL>t(@h!DQ?1XYla6sZmeEPvWe^q38XS}x9UH6A zU|~30WYe)nao|6i*wy@p2XagT9J>29ot>Q@8QI^yO}ISS)=#(z3JrFA=#MOTF>X$5 zjfKvELK?zGOZf1_ZT+llU%Kf3U3yihl!Hzk)6gjx!AAA>9U&tQcpz$EwR870!&xZ4 zuhpj3Krjcbw(&}kMhPg%r)9JG{Ri>yjYlvp>Pk#spTXKBE zUVQ|ou~epWLn^m9r^lg*90T&C>B+^##jGIlJgL|4R_fy57 zcK=nrb3grr4RUW$l3AT?nkT>ZnVnLrF3uP3i(j8SNciJ(65!)>aLKrsIZihTc|eJp zwc)n?$i8)r*1&V0#YftHP2OG{+OAjSGOh--TKlI5FWLFPPT0cEji}4Q0}u9@+pjy= zR`|QhsX!wF7BHmF+Cn=KJ~Txl-HZyZdUWIs8YZ%da6iSoR}n_bgJggG&hRCbRRNFiZ&8oavx_1(2`QlIGm_<0%^xweLYsUoc6w!lmZg*j7`o^>9 zErolExnEP|h@+{)mp9_-m>3&2T7bwoRnv8c3h4Sbw1v^@3s}qkoVLB51}5*L&FeM3 z#<}K|!j<7W3}aD^z~x8LeU{eUC+yAdT0Z!i-pq|3B`xkF2f2y#4Q+;>W;LGK@SRHK;O>GQxHo^z^>iKku?S(5<*=< zPG~g5AjA`wlkU5;3^c14b6p)4Tjt#2UW>omAFPPkyoy2V(#r`FXRp}a^c-wl<`flJ z11`E=NjsykRw=P+>1gz-F_%9W6(n_tevrhpyolLaELjzxAn4O*^pbR6@EoVi=ajkc zLwl5vBN8om9%m7>n_V~jP5z?;pWQZ1cYc@jS1%ZNX`MzgDzGI>Sc-YhHD^P_>@l<% z9=#x)Wj2F$yAVe*o=kFg^DJrzzLh{Mn!<1QvX_+ntqfrEwBOHMwr}|ku;~}>Kb24aRK4dx019WfYx#O9 zKDS~{@8p2ModW@>L7CL8$>l!?4#tNN7BuAVe9UM=eXsp`@@<#KRr+7@HFX7~W8Zq4 z%*4+M*aE}78ydBo);HcLu$=SR2aELuRZNYUjWF!+FKc|ISr#O=RiNJ(=z$n&SU2Ce zAkijtJ>z+GR+Br{`1IG8c~TjYOASW)77*vbmU5Og;Vsd=5jAWCcFM|jH_*p+u+xu* z+wPu480U*O;+-PC80@yaf{K|aQZJ(H8e@7wfO#J*@EUhv88TtUM+xBbsjVE-xo+df zW2eJc9>4UZ$%8$YqY*<(jL0L{mOG`?ixTQ{=9ps(shoId%+&$UUUuEV&zoP40%3Dh z65u^u6l{t8UP8K!@d{Mysp2t)lzYX7$+%*-<{^l@el!*n7c*!JM_qeS`gz}#$z54c z7g|yemW1r@pI^DZG^7D4z~w)VDS4fm5ZF{TFO)Gye_PfM4M{!ddNdi{g*;l?xdE(D zMzFfJSc;UICqVV`uj{f*U6U*CZklKR7-9?6nq?okm%w1T6bq}SO$*MaqHaO_p){=M zXE`TH9y^1sB%0~at&@h{Jw%GaOS4IO!M?(=417Gf@j*)o5vUeE8Fgb$+Glq55HcaB z1z}foHLJN3MNtT2LQ_@2{#y6rN^6%DMa4Opbb6HXON&%6mdB3i+#YI+yibhclKfjr zN0JzkGg<~}kASiztEUrrsI1ZKD^W4(4zv3me6QCCp8KHq=rv-dgQFCvgr2c&-wP_8 z&wg>eD}u>4bc^%FgD=BwO>Sv)19CXFQ3c1y?@@WVcT^3|RDJC#Al?h>9$U4Vvw%_h zx;YoCu|9Gv2X-KBW*r~-al?U`h0+3~&Zi5joB?D!#mwFHXPOyHv@cxQ^pVu<+&Pz@ zLEDPC8Js_UCr<=)4a6*jO}bEuW!)ydO)8y}xD^Npo!E-#g5ppZ@E`UK_pu3QwRRkN zTm)k3fi_->UV7qc``kqZiw&Cf%{`-h7iCK^9e4Ml1dc9YM4P%RI5xTWqQUT4<|8@E z{_2rDXXQpWua0~j0@4Km>CC)K;Nl#i(h7@vDv7A31aYiA_sDKsg=B`;*Bo5gC(jqB5NJI&Mdtfl1rT4z&57X4y6uyVDh@=;a)0gT`l!u1hJ+V40DL=`P@;RW{V98Ywf;T~iKS=r(Xgpcf3)RFsbJ;S z5U>={^ji!!KW!WmzC3?|KB?CWWGt-;aZx{{_VHe)qAwOhky?N)v7cmTcXnpgU=I&C z`!NEAyQ@2uGpmpKw60&quw5k)dxvnie-@*@a(@P9y$vFnyGorl*4C(=@4^ugT5NIW z6cOZmeU(h3IkGEQUxT%9B`?1*)<1Y#*pj`IX8XGQY}dS`s+iu^ayPl7R2AMQI6#{KY=t@_rd;!ikVhIK<1lqS%N>!|3i#(OJkekdIbc;*(G<&34}FXn!>`*c8|=33P2u8AaN z>#vbK^JCsIFd<6QjN$U$qEurLL}Bj6A|SXVK`@0T@En~R4ZY8wJt7vnvwYRWz`B|) zhv62A;p^K{)x)O^vfCurpC=|PWt+yu@q%gl@7=N|%vWcYj9P~H#?5a}3X zvaPBHTcG_pT;d7_>T%QT&-Md#@R#K5`2&yO`9e??o#n?J~3St*i26*}$2A1?$#45Gpf zGP(WgPZ5JRHx7muWC)DWvNa`QsMhdlM^`#IAB#rMGP~<)NVJd5jE3ua%G@pQ9EDN@ zg2K)54J%HvK9wMDbNKMy+a$X;bzt5Xd%)&-UyM6ap(j(7V2$+k{O*ud7T+c0>`YIe zKNd5;3s*vR*|66ab#4#Ur$qMdA<2g=X1CEUa=T^AOf6%Dg~f0=UH72dj;w`}>(4&Z z?qR}ZX+e{Y6{g)z_(_aGt5tVb!8W^&LW<2dv?u1JM&L0yNhn2KNd!A*_OM~efN}|{ zuFAl#r;BIfEje0JszdKI9%OXyizgH}_K@f64C2Dvo|Npk#r{L_if&d+oYu+}%P-69 zo~h5fQ!Pv2Oy<$dbQ9Qn4PFcL#ddTkLhrpR(99)=Gdv1(Nqj%ZZ^%8FSBXJd!=qcP4MKX|2X<2p^>oz7pZ8xuId|46&9 zsu6912;w#YAVWq|_}YG`?{fIyeORAoy<(v%7DA zF^ly*_0I7;+0_yangWX-L^HqzGx{Aga_8matI1YRSRUL++}0qepv$kG%~OZ{cd*N8 z^vP21HleH4b+p&{BK5JhD~Cp9BcaJH-f5S}c_>{35xYA@q30$eW1`;Ly~9?1GWiK2 z_BZQZaT=*p3XGV4q!Z`ivwHZs?98HGdr2T6;X|}9RefZ0x<7oYy9f*>i;pl_cAhN>dfb zcdF+P?l11siRzh=n?G^fr=mgK@6Y`nJirR}Se+88-0H^x`gkk(Tyo|k(76h8d3)JI z?xG{!pJ*{;7GWiK|6&SMS1IxD3zY(ZO+|{TG3|r^Ao)zhi|MiYD@@Qcp9hM$^=Jki ztyV{BQQ<1adL)O`ymkAN28wa(51Xejm1Mxq@^VyPG05-3?-PnSn|AorS$mevGpw2q zcMj33*v${zeL*}bhgr1^^r+Xoc0wz^I5#Nly}9lt^Bo53Jfx(#^^XnG!34J`{=XUH zn8Wnn0eJ0cRD&J{xc-q~fzCyS9?}&6GwB{M>#&*Vh0>~1#`}Y_*@@ZN52@Vl!3?`( zq8NBi{a5?A^>HHW~{_<61@|W7fjA&^OL%#!9{wZR& z{_}mmK>jUEgh{nrpuQnpoQi_)b_Zg_NYmYX{Y%9v#L&RNfGeFNeK2LvDq97RgtK(u z?f}tUSr-!bSAXDUrSf`suPqS1*&R-Vi(1qb3A1VAz*UWXRGtt#w%MMD?2KyocxLP_ zT!+W;CtdlWOKG{oSB!WJVG`~zPvLt?_uI}2jiD6Quhxn3wma%t=dO@mC{V@Yob~+k z=YO=%9Pi(jw%Qu^i66R1om5#`_r0M}6jNgm(CKvD>g) zzXbFwcgG?BG(GyusJh%OZ!eJFp@An~(X{YTVYMbO;C%lE*w;6(JabBMW-kOjQf(vW3c_$vR7u*Y+KB$B-HC0%jyH3R=W)AgF6mjAPW+57s>As^o zuMepMN@dPVD9Aq=y`y%@1CQ%Ppk$^VHI{nK zzk&j|LA{{nNhH=AbC|u!7t1K>VlxP6iq?_^jgjdM-~cKuCMOrygoYw-u?B zC%;$H$bF7ww({J5(G5nAXY*kHXf~lKYZpTOb=`>Bl^T>d1u{EWZn!gn*xT>bx!F6c|lf2>1*%FS;K?GE?VgsVYH};&eb0?d^-^J*z%nl}gS{!mLdkj=Ht9ITC8W zA73y!v@YTHEUZ9d^@($lHtlt&)ZY=yRA2vANzf0q47V7dx2G za{CXc>lQ<{IaB2tPiMB*5vTKaK7q3OK7DvOrRIkTjHYi8ANOq)4LK z9@%}Ont6Np(sWm}5(QksHgrkwUEM^y$mPoyYM-^SwrS&2hM#8!rIyrEVOmQ>2 zcY{tdF<&vObBxa&^VxpnDC5}JKjqVTy^e-_ImyuZ5W>+YHyE)=Sqf%m=$fgTCT3>e z5;Ik6_l6Sxpb5Tt69%`Zx<8Z%bhb-&VTtQg&UX}keeu;ZlZgkAjokupm5{i&h1(Bb zWdv4KB=QQnWY0BW;o`C!or*R$yC6q0^FAf3_1|t!ux`wh``-C~ner8|Z-)*5ld}^T)}xOQy%s;=bWov+o7Nl*VpasRQwk!#%2X{;{N z%5GOPX7IJM=F{v@r2zt968gl``-LO$n&U<6y)#V^bj9WpFGVQ0nbBXJ?i!D+$*0KE z*Sl>?ol%S2%evF5hWPPN?kmxYbGp&dF{YD-yVUEO8^~riXCxU9`8|@43$;+Z^SMbC z*v4p1y`_Q)2&k$7Nt~Y)f5dCW56zi{IzrfNalV-1zxLU}AnR~B$X9m*2`8N3k_UxW z8FpMg9f)xAXJax$ib_RUsc-h|aK5j*9BJ6hew)qU8_rzebH~Hy{0X7ad|`%`nkOt) zBV}vlS=lG-C@6@Lmmh0Z{liDzJ`7rauYsO4!l9qg92`AkgMm?3NqmYyTRv$=4!)H9 z+luSA&IBIsnuiE{74bpN3Zas84Cy*KqW*eP!Bg4wg#6W-%GdF=73}aRy6=n#inOpB zOX?P?H|Ku+eb_&Bb9&>&1mEVEACXgP3dheIVF#S}n*`2)fd$r`R=3Hs$19hNEa8lz z*ma00g86HkQ%e593LC!M4KaaxVaNTv7oGdv4bWrZhqMJLVcXVo=2Ri13-mJyhhaMg zAd=Ka1Qi{B;j<29w(ljUfGKYBbF#}>tgR(q~ghgJ2x>vrlKdL_lCww_%g59A2@@J4`6`EB%e{bJLi@>*v$ z$YonDXNLx`3ac$1M0xpmnkXFhJe2MyeQDZawe^$Uwv_6KLr>30&uY7kPcv&bxu}qu z_rENMO|B|N8;;k}gP$6Sw(aE9XLShh&V*vbZL>jc6VfWQHL``%=D^Vm!k*j| ze0wW0Nkk7GU4WH=Av8wp+7E<;#Gs&JEUY63fb-tkq&o8SM820}@-EwxnJF6<%^By} zI98IyZ#pYA4QOF+XqI_KRC7mfgn&IF)JA2K2 z)Nv~$MkVA06t^W&1aq>V2hH%Zo1!NJ2#4E|^-Smrj@8N+eQokv#jM5( z4}TjTdGB@PY3XETiW@J|MWp1(g-_V-HdFh|6`MK-&u5>)O)y-IWu$S0NXi7P>5M;{ zVOxgii{tFc7K+ytZVHHdY0aV8Yf~%Czd=92er>vGlVlGcoVid=t!B$CZ}zq@<0_x2 z>f`dl(Xv*|Y$>A=r54)6R}7v)H3{V{fY_6Bf^Z&z9V@xJf^UDX3S3xz)+*+KL|3d{ zh0AG@OGs%DNX4{7`7erI>OY*Ftl;8@20~lTBQu47qb1rv8@+-C3Xo>g#$<_*5O8nh zh+UK!cwQ1YSM=j#>tGQB$?4STFz0jRdY^MD*OlsLi#Fb@ZAVgaW)O(E$Ncd;Vf&cr z&2wUnj!XV!wWKAH+K+wx$7~&c>W%~cVhWHNpnNX zpF@i_*XBC5@XTpE>L;5^Y@oQgy4%X@hIzoAwZ}Awp3_%T52Ez&{}JTA?j*eHg5xn$ zq2k2a{P>*ooKoz4BO>(AzF+%EO~>|fwogV73-Dfyk82`x)jr~a6y^wa;?sH^)mh1T zkJ(RB6iWzjgqlQKq;$#8X9VJ6zuF%j(M-n5u{60(07;33yiggTeHeeTugxHWh1)|X;B zUcoqfG4rJ>|9*$?Lju#dd%^FWL+XX>n4Nq1EPK3zau_RL0y!)>iT6WIgB#t&USa51 za;b7QCBv~8o+&l7C$Ry`eR(p2Z{nU#{>pYnu2DRA3KUsiZM&g3lZBd_{kv(WsrYN( zt7_y4uGLfqx}o7){GzBK9T#u>MeooNhTnug;%rGd8W|QX8#GC_Thp3C6EU1Hksy&9 zI8UCq1}b^2#d|9Dz-z52OPYzGOIHajyFX!=`pj+(sICDI+fGK^czSt$AC_=V; z@iE3k^BY&!o^$xQ>j-pK;P&)kKg6?;f!#(l2MVqK@uTr-GJVz&+LXMqv<=GYu)zt z_8O=0W>VYhdZdRkOhm(Gzo=I#%420j+JbN*Kwa-j9kvb-B>+XyOHLlOl`Y152`?Nw zmC-qSY@C8|kZAY>c=AExE?8`W(vwE{2We4qNpf|7=dRevu zO32edmedAJPhj5swDtb$nCf#Q`-(oj#6~_L+!gJ z*MoR-Oy7}@U_`h*1IE^#`+C{aylW}K;2wp3WoC~kK1a=+5%CKo`ee2*fkZjp75e5z z%&-{>)cDl= znC}dB`{geR*3cE8gDd`_)XlF*4DK_~gG#L;;cMbmBoaD3k`wmz>rYt|<5@O7xSNgn z&1Dpec5}w{M@pUkEOYj$*bPLz>vC#A_7Agn0A}?P6J%ds9fh>iC|KQol#9##Dif^P z;8r5q#HO4t3OtlN7jM2q+UNcjeBhFenN_QLr456|2suaEe0K_OhqwevysvZIiIV(K zvv9vJrZuydgSFg|<#Q?MyZGE(o#v^RWl=^(nRZ8NuB;HxW^HUQ4@}>0=Vt3TnUl&) z`YKIH@|u4;k>?&KjNwT|QSkh_1hA+=S6!Cgn19E|#56emrSumLIa&kkM1{W;q)($U z8=|G7lXwnFJtTF7Yz=E$v}|kBmwoyi{1@pmt9L~zxT*2N!S>9q-tgMp{gWeO#0-xq z+t`3rm(2(!%X7Te-)+o(Fr&5=m&Bsy{B(4IjQZYr{Y4>8f$5{dFQRTh@hW5wel__= zjrA~<4U{+%+HI2Z%!fJL>HypDq|yisS0(fXH20_<>|zwD5I(f^eWJ%(#Ps7^iVB)~ zFODVGqUi*M#DmmUJ}w@(?^k*nl76*)fU@q#9oTZ^oR9nM@{nFYz7cJ_Ml^wkLSROd z+xOs}IYFD54X?c%$zmQ4fB?Jgfw&WznZ7V-vc){T+_Vj^oLTUEe?G{s>>Yi)e=?Zl z{vMB4K~cXCHXCFZN2`{hw0sZb-jzIGXP z?K&+xH8?cPy6-P2O_@G)i5plFYA_^Cku#H{Co-!N++YHH3QirQmop=>i2MsV6JF4n z)2aGD$T=+R4d5@7`u{1Y(7fJ586J>RFZriMZz7E!*nYlL>w)?M{r8?y-DqOqPsycS z)I~Ve|FpV(`CpVCJzPR~c>eo>OfbTAJ@Y?^=V1?K%PQ7ALiix0d%%{p0|}#M{&!-% z&q;g+hyqxDi~ciyAsfA7s#6rC}blLWZ_U+pswIMplZ*S|yCRw{6r4FlUl(3JhOfi!bH&WI+~q5y)ZqC?zHox?wbb<9ELiY&RmVB>1h{JJPOuV0TZrtAHX*30p5 z3mKKKwMG3eky`WvR|22h-l*q#3H2 zJvsAx2}H1PV&XQ%6GllBEou|Ri-gp5o~1O{V=yR8WI|p}on&-RBvD;AuVMKN53#!= zY@#;cTOaBtBinltq!qfKPD-{6{Kmx)UyR}Yec;gE_=4G#Tnu^1-ayF)SljVT#HjZv z*!%M!lb-+<67{*$yg?1;6qnWpaRNKC(c-V~8v_xarjjvR0Q6rpYaRHiEwoM7E%`HZ zX%t`FxIY5%m6#6aGFI2!80t|>#nmTP$3$rZvualP>de_M(M&jehtb;4EGjE6LR=bN1pp_Dg-~-RdcY?TkQdLCo3!h+;o3ib$@(onEnRsm@c=fRyuN^`b zTKc-{YM=8*pygS4P4(SwBRK|tGUgucftmi*%NElaiHiPytygAF|j0y9(>bZ8YqqP zU?Z#tW1BMz;!P-j4|^)XrUOY__V6DPpVCt-6t_}>_z+JP|MY-#C z@@F`6^yb*s&380oZUu>2LGT9rp{+ETnTqgCcx^ck;v=G0P-DP@Wkhx$LYQl;xXmKK z$&A~#=WaT-Ixz}#+rE>a^Jpt3H@xpL>39)5`+Fk|EH>>^X6)&>;Dt?k4SgLqf0Ap) zc>>Si?TyylY;A_km0#JV(Z=vD&+K40P zQAimnb|nI_vlsIkVmsVXz@^NEx6Q-BvpwHZGC!{<0Zy8{Us$tVAqw;;NTd}z{Yn^5 zis^;(4YVfhf<#<7Tj=ki8@k_V!C3r4a}LBD2Db%EkpdA6WtSLq9omE@OcqPPdXe$4 z%Z&9hpYVMmdoH2HPJ!ruVpqSLCeVL)&rytAfZI<8@T7Sep5h-|wO?G< z?O~>Vi0)|Z3#Vx|yWH^QDpl+9Nfww=k)Eu&ZYUN`3RquN-`5z<*!uNdxa6__|hb*f~ma z8>@0HhfEdzv7E8doBo8A6~dgHV6$Hf0}##e+V}R;Pw1Xj4r#)28wMZ4SlsttPNTzM z0_(y_Uy{>Vr*#Y3&Cw48ET8-dr_ZmEY(V&>mTL{QHHWQu@wMSyDuuqY0LS`fF}{y|(c*=vDZ5hSyFAT9N$=!?-Am$treZC^wU%(x#Bw;Xr#$ zF^p(nE_d0)G@A(;6B~9ZS-T^5*M>?u{`PyPGeP6Y3n0r!rkdIPl6W%E?n(g1*Wi41 zIkS)YE!f$dYLmZ-n9FOv9;Ys$-^e)<|!6bLX01n;f zn`hZ}{%;+gHtoJp;Q&k(QM}(-%z3TuUdiw9mQ1TU{}Z!)d)oL5(3Ih~YYI+x8EX~_ zVoqdOa9YjH{u$V>D^TBo!?jXz!4i?Z`0{`y#Wzg1XExGqEPT>^goz`$?gq=;matTv zFZX!$_9RR`M(CoqtGPogcIJROq^9q?)RG#dINwN1Ede9OTKW9$r>Pm%h0Y$id2l3U z@wsGUC#!g%r5((_02Yc{Rcg39XG!TW`Rb?Hn`yq-Evy3R4w7H%#sLZSE{A-EVxHC0 z6_ZD01&ZPiBEL7Y%G`?0sxuFd?ph<(Xi~Hv1F7-tKd2ZfXDZ^dTW+&_ptp%ro|9rA zN3w?Vy+ncwqoax?R&elYUi_0xh4;sHYPbBESl&HH-9#Pzl*L6-_|_zL?326v?7yh^ zs^11S;D|i(F|u1LwEF`o)~t)09d7zvDg+^HSKaL}^tGwzf)&bA24Y8HBAA#ej{&&3 z*R=t!UC|wPH}v?IYdM{}3@K|*gK8|knnIsazO;pGX6?NdhTOzn+2>7N3do(|6j=Vk zpgB^gWzms^D~Z&d2nH_0lPe6emos|4r2P_X3YWjLUo>{!QkR2Ua{N4q(t)444W2ep z3ZK8h!KbE&+P_fpaa$s|>70u^4xr)2zmxp3fv7HCUE9v|rK_IEww(9mLdbcTn3tI8 z9`kjsnZy%v2P#F~4Nlj`rt&62Lh+Y`m-!#^5y@wMWuyW&7gIRG4R3$QAtG5}j@PF# z$>-bF$bG5gFKf~@$kljheM8THCb_d6a(-ET-f(z~Dd$OMx`lC*#-m%b-9$j}looHN9b!S}Pqx*|%#05=Io82fpsWlJo|aji zKeVK?zHejR_IG_N4=-D{VHf34MJUYrc*EP({%FZJGV2fwuMTLeGR@sU%;$+2wB4IF z{*=+xB(pIII2sr{vz%?dG!%uC zj7Rw=+7Fa%?)h`u#Xw$XV7%mP6yhAmbVzA5oK|N9>a{#%$oF;Q9)eCEm7M8A&lH7w zLa&anlQUCzVovzP6i8ky{1%_}dhYONVO;<&%Xm1O@aJ^aYZ-G(%}9hrzdC0+2H+vS zOA2e2!B{Wy{6n{pY=rm@W`Rp;&EKlXK0fWNa+EL%??NFoOss6_m0Fy2hLf5N>Z(|M za!|#_EpD483=Fe*<}QyGEiNo01>vntbRJ@BZ zZ(pOUYYi*3U?ujS#5Dn1V+&u#B@U(5x>ufSo4D-BLVuRPYri4B+ioXUzG|S!VQ!+R z4m6(k?pt}RUSYRF{b*w%M>cQwb)^!2%sh~p0=#FUevI-onu^`kWuxDq%0sEl4zuJZ z?fs@>yQ=m&i8z2}<5Wa@semZ6IwPn!h&D$;ed!>Tb^NGIS|xMt!8-4M;_#1kLJmym z9XS>?AoZP>6QvU0r}|V(t$X5?84gUyveb*jG4-;hjY@JEdqzK^W3hjiNqT#COQ*c7 z#VPtT!LDB&(aNl@d+9l-+5FXZm|NP{4%7`$f88KXBKIj_ctd>EI(`UTK$z`N+BGHXuxWG=xivw@>rpWU+-yR?2YXqdqV)%kQSps@EK3w8tH z7)stj*EK$~XA$5GbF7h5O&&RTxzyIOAH%kl#QdO^`};s7Y#z)scQ;hch-6j9E{~JC zbgVP# zUp7!aq0|4QHs6-3roI}T6U7{iLe_NuUXZzuaH9J4GXo5YO~YVwIqk;=2Y9(^C1c8a zDV5RA{30zZgemBJcQo_0dV@X6>xbKG-_9zt`dkgDvW1&s@Yox>K_U`ta~Gf`%|>_M z;IAAGmA)fd(RehPj5%LGEW}<`!A~Z0$(lU%2EuMjel44BWd7Y`()#WIGPut_@QOMw z29o3rrF9RwgDOggE_{?`51<7ezq}m|qDY#D{lGr#Ze=?VcW_fu!F+vE0e4KLD}sKq zc)o2<1O#(@TQbficfnZf38Fm`x=u9oAz|F_vNKpTG$*Tf%T7mTtzNs^@Dq&l=q60b zKd4l4g@DA5nLes!;Pe?z4mC><;%fcdB1vzbTY|tfu`*rcDQbs>n1f`SF^Jqz2w3j4 z=+&%EE&nkN6xCG8%W3N^*l{`8_=d;fy1-OY{rw~_2%p1T^$|fN{+N)|-vOTau?uBA z{s~Q~nvwvprlBWRI^qjW(iCUh%ve1g*(C3FtqlzViu2ix&$&pHq^1bK{+4JuHidE64-c;%upTQNgbJ zB>6T9>=n~{Z+sLT>;}!$_9EykeOWjiWp{9PpbhNDV%tp>dYSc4O!cH1;mW1U$9?^5 zf)o3};hMvh_YP(cY8i(hqg-^p^+=>}HFF3o3y&5;c-ZH2ZFfuzpXW7()I z_44(xx5mKE?iC-*6e*q6s7C*l@9z?3FxvDlML4l|tcLJ+tt9VWd8~m=noY&MMepn8 z0-JPY5csS9YvS}*La$Y>5W*{N>Wk% zpAuWT_JHe(xESu&SvPRE!|nWOBRWZ;Ya!0lL5Q98VQ?=s94U5?Z9aw@YM%xQ3@UOm%Z;e8LOwIAamA>>-HBENZ}%_7Obs`YVjD9#jTm5+;(UgN7W8sP`sw89-SE^6Qt*5ZdpZ^Vzi*0R3Qy~C)^1tsu(0e=~_axn{Jo%tDd;iZlybn|;H@yThw zDE@)-RK)U`FL%geRwfEAKO-qQ=S}hQpkjJ!H*7D*$vj1F8lfUKP9=+qN1OT>qq7A& z9n7Gu>cv{HzSsa|D-UF^dGT#owcMrww0#~2V@|MZGKax-KsjYsuD}j4tm?hWT1W^8fm53GG9|HhfHb-k5G?%6DO843RB1`vX!NB+* z81}!%O#cg>{NEJr^D+DkmJG*~WFp;U4_AoB`LcL7(lNmi@^`*rI&3V-(zi87)=9xX zUM7PAt5bcZKKw!0FfKd&Rmy!(U}ItnRejmqXvEtat+-Azpin-9V(`;C=82x&9_j&O zq>hof1F4Oyn-f2U=Sk5(1fH#5{7K8}gBejF0kgoglSl5h2CQi*NA9*pTuDVXox9-p zj7{1WSyuW}>{n0tuE5mmT|)vH4&u#aQDOuHrtWw|eJwPm`;ItZp(9wr^2!@MhA9t? zOJ&MCTf**fV!aOvt*)LP%6!f~AD7~D114><{{U`zUWKWdg~2^CTFRjGC=N3=vp`!a zJN(+%M#ik|7;TSUL-P+w@i%Pj)YNLpBQ=Bd@BfB%Nv1y2KPy{{3onHX@tP_GoKveg zo`cpsSsJSdkEF+6*jaMTo7A^G(zEpFltMqsrl8;`iXj+C&aWivMZ~wqJEHqGG!fz; zao1l;(-YYC31~J3=0QXoMd$-Ijjf3)nd3j;6PTDDooWdMmfE*M&)%-weD})I&kUz( zHH!6qo1H%u!s)6bAzHY;)U`^6wmnP-)E9)VTydUcbzgfaK8BtPrDSgeCAi$y_qToL z#M5v$r}MEeU+TzKo+i-Xlo8zezUIdvN;4G;++ICGmI%}f{=-;lF(3n)=1y>P4`%Wt z>x=M8@iAKH){LK;yAOFKWi|3mudWW2J1_&937cK|`^-P(N3epNvFylX)Y(zX|A3>| zH!&&&0x)p7z0)s@Q1`)43?1V$c2Vxgy*w59ffHP)^jdt?72I&y%f6hi_$PVEWhkVQ zJO|xKN$RV92VUOva8FAJi*Rg*V?pr!A>@HgO5!mcM2_IZR0EIO;0fuf;uNmXHWvc0 zgLAq#6Mto`G0)mxGcOoS{C?IP<{WE|9*;mn z@ekGxo*8^5%9W1kxRT9+6mEI*wsdIfR7G^&AtQ#Q-jbB8_YSZ4!;qZ%0T-)Tz!3G4 z0xz?4iagrOn-$J~PDpy66Z;{gou;XmJ~0E*vGkMEU6L^d(HCgD_Fn!`b6_uCWUCzB zr0+0&V#=-5VfIsYs(#QG=`6Jgxpq&wS=*IcZF3JqcJq8sgtb<2$02hR%M_~{$|c0# z)HDd}nbHFKp9IKDR%5PB5Vtj2L5;g-A7{-j4c%F#$jZ6K;iJ8r-dw61kR;I$*8N9P z5sOcO{-@=e<(a&3qG;k((d?+WLSj4YDGI%*34M)k+0jFvueekp9wYF5|8o~$I6wkz zd-T+_q8}Q8&ok(9?t8i?B>dHCarqqRHb&%$*~CX7|4ii>4((UkN2hv!rmT_EO}w9X zbQ{B{Is+1me!alNWTJW|UhncANA`v7`VAfFyFU?Vug`CU6|+o$1z7?Ou=xyUGxFC} zTMaDD%-H^<5&6Xn`IarBA-qEDQVLd&cz&X+*sko7QS|lR-xa4I` zY^lqNti(Fz|Nh9FK({M3=bJn8^U>e*q{98JdBFU$2$r3v6KCw%~xzl~8e{4lF=?zsBw#|cm!%HCR9Tb}eR1XTy^)&#@k#)DUzdj={?8`5v_}m-v zoLSSn@2@GMxC6N^0!Lmi@|CrV>bQRZp32MTtmz{z8&I*OgyoV!QdNzkhQhoX*!ZXW z|Coe(&q}4I{N9=$?DR34aNPx4L&e(&1PK4SV@!@{42P zn$%nmeJ|1S%F+0fFC@?p#v5`{nk`s0#WjELj%1XQ=(UpFIRg*-(l`Rv=g9sKXI~xF zR@c0X(-sO8r+9I9*FteC?ohnAyM!X8xDyujVP#j6z z=y%Y_`a$18F>K68oD%ZYR7|LRdQ0+b6JpTCP(t}^%-%r8DAmB3LLw91YDUy>u=ji8f#bVgtEWwG60Y(ZDe|#KE*S?eMqdR<11%F(B znt8bI)f)&&wcCE8%Me9)S<0z^!Vb_FJTJTkZs+6%=&aV2Ha}mE6o38+ zN6hc?WhzfbKyW=zCjQUwpYYIx5_)cnX1F_O^b!ZOSwo}|=6+RtJF6Gxd)^l$zYByv zMyC-pmVI5;?m=u7{%S14tH}2xdn%mccM%vi;CSac!nfN`&iJ|ppXVzj$`XlEhSkkN zp$?)(o}~Yl8LnFSh@bbFa?L_;sR^g$EUJIx?2@zUK5pM?#?kdg>!eAOr4Je`A-;(D zdm^_%MS381$#EO9I<6)qdC)UV80N5YZC~cG3Fu|ZxmhOCs~ay=8P(aZXXZu=r$&o_ zlarWq!4v1+*OOB5v9VnPqyYJR*+l5_FvEn%rJREf<3gIANc-ODMrA12^oA0@XFX5U zULJ4R5uj$I3y^k{vmFsCjRST(z-h+zk6FG4vB(*d%Q&|i$tzkM9(USCSwX4$(do@? znwUifY&e6kUqGogb8x%m_Ake}A2kJqNh!uNluY!y+4bl|@#$vXaJtEPKhD$dY{3Zr zoY|gOZoXfZM7`WFB@6v(yeQ+N7;kA_xJxJ^itOnwp%K@1g+M$7z=&z`Ie*juHxOx( zc&TKxn)Gr?poiej_X4r%vLQYV{>@Nr#ow(?N`7C}gSNe361}_XzMgNp{7YAX!+aE9 zk#`e;UbDjH9+V+FfxpqJ_v>pN6*;-#V4J$bAm?r9#pO(N5KRk=| zxh!`Y977mu6ESUedd*z($U`-`+wZM^2j=~%La&J(N^{-2nh;^}Jb``|I`5BvUl%F5 zu7jZ|h>3x*d8V7*vk_2m8^6`nnZ~4pFM~7wsIKS;M?{PC4I<=WNULvb5lzCF-RbQ^d{CFe+3ML41F^)#k)j zjdC3>ltXuV3C(ZJQuUW1BxE6mk#f2FNQcoG#bp zfv%pUmsj)V9Vw1~pjBN-mc}LPZkp0Ptws2GGFLFH37#Eb?a+I&#LF?&@W?&DlZMwm1Pg1-LyS=rlq?8Q0e?-_c3!?m<`yIpJTZ ze&<|usgZI7QNdE0D{Wm^laSvfxN(Lt?T*Z^?`*riBm0$ct{0-Jv{KXGqdXBNwh4Od)kLAR$o0=X&^A2u%YA$56|96tK2?1gNL>UGp&T zaKl(nEdG?wRjP#}+84b2aOVCr{nHJ{YHl@LU$muCxfF2$HeU@7>6 zCt|g*K=t5`YL6)u8HCGkLC2x3=YtqiXpB;MI?hX6jMjh8by=fVBqBy|FuTK#8Q=*F zI(6Nab;}i(`@LEc31_M426vW<76{^+p2{~n3nJ0{tY-drr8V60?BW4XxVHc|89AdJ zqQQkF;IwgbUC#}I0+p=4_J;(0WR8ei^pzvUn~D^?hI$t6=NoSW82I)xHSu+3k{P`8 zyEo0k!+C@)s6myjVH`+fA=%^>S&Jp60^3f0rVCi;PJQLR9uD$ok(GkcJ@J46qs2nL zC)?(84N-Ci;gbnlccE^O>b&jCEL@ISIZd@7)?vsg_ZVYJ7G> z67i!iR|zCuPf9z>SGwcoWL!*=J@))Vw=#dX?qWR?cU5^NUwR$16~Js54m#9a!0xZy zJy>r3U7?6LwMB*tlnQvmft)#AZ%pmc!h_B4NgqZ zIEzP20BO$qEWDr8LF{X6+k>o|cyM-gkWT zap^qmVE@uoiK3J}*QS4dRZT0re<*#HbR@L5%pRXqg0_dyw_!dt7R^{f%HT_|9=%?Cx+rSRp%N#yR-7nh*Udzqx z_E>YEq*T%OAHt!}RFoMD)|FsyMo>E@$W;lxRJ^Kf*=}~iybSj|br6RmPv>oprzrfz@BmKzQH5W%OG*(Io*cowkyvSPB!xW&!-{2o@#X11=;bZd;CUuXnLtmK|qpng!e;u18`gI2`!G=D5?y zcP77Ml^m26CXS%ca-0$esM2n4cv0V~bMw2a@{|W6Y#!v0wS3Ex2opl(r zwCz%M<4ch~X>B(kr@)*TD#Ebj*2Wkva?v0puK1!)5qxqyH6=y7?4!fs>*XUHMqmrn z^cabqIhF73u}tD&vdyFe=T@;YW&P4QWYYp0@{%@K4X* zsCqF89q$n%c|Yih4hPS3ICxTX;0|oKBW}R8H$4cRru;H;mW~dmh|@^<9+Ez&zE2`K z79?VS2G9O*Kg{5{-3vK?Ca2SFOA@SRStZdL39h``sbV^m^4VjxYd(j!623TBeER^K zB2RGt#@o>86SQp^g)TgszDpB%f#!}S& zfUTA$LeEGT{5B~jOj4iuEtni5pSGUyb&Kt`25h_`arbENW4foxRUFG=tOMMg`^i{Q z4&~wc!-wcoLaEE%_H-wxp%cNm`TXr}N~oTfao^{Lc>?V@`8A40O{VFvdXcv}NycfX_{1^3Q&(_6r5k^33m8A(3zCSXPWRjX#^`PG z3JbT4l7&{TU*hg^baEEZ!{6`ZXN8>G&Cvd@%jP2jiM zC&*pv-@1LavyF1MX!ii~=@OT9YY~k4XignIhl8O&C*>9S{n)u*LT}RQ%I~{K#AYyX z?aNNXh_<-2PNL9Pzb$P&A5-yR+o=d|VRF$%-if!2sm6X5KN(!*& zzqN{Jq42mJjQu7_YcT5xU^xIhVd-gCquHPRqM`UzVPd%M$kC>GJoGTXGE(lXM#X2( zgfh@NqB^lQG#h*eoBG_01l=wYZ*kzBvi36GOEs=BEo?|y$W6Vw9 z{r-OG4mRi{B|&{;4v^iWuzC``{H+_{2SHMsX7THnZ=aRES_&h)0#kpji3io$LSkTvL3?6 z2df!5Ix^=;mwrJvl=X_XG@z1A>sVa4$t zkj5Gemt=3DN#QAS-hC3yYU=8!6nejl<$2IWknj}TpwQSiphYPHQ37enRXAg0=%Q}) zrGzg?3#nYhe5Ew3_~?0TrFyzWrYhU~`$z@*-~$V5NCr`cm7ntD8bQgDlu#-@dggX@ zm#VgeV6d5$^GrU_Su(zclJUX6v?4|92rKOVt2Bv}unT&j?S)^syjNQL^c3I0A_Je@ z^p%mZrxmdy^Bw2eC%cr0ILlg^wvqS=!02^)Oi(tFt71n?rWCjFjsNl=4(|B+>5Bd1 zGw<`u{Bn>5`HLjV*T?TIO2mc<9$k&mz;wDRC*2IXEEctL+|YTy{WCwUMR0zZAv9J* zPLdE0$MHF@TV%yc-3y0x|At)t$Lv<`^zC}iuH%4hI$JQGM2vbZ#hs8RxWGYMbS{Ea zjyVE*D6K24Qr^@xMm|#R$;N7E*zA^q$Km8W|Ji**+KW>lby#;N&R@(J*`R-02)$54 zi-;M>6n%2e-+&z?cYn5QSlwzRP+_g<+4A%*h~dFeA|i%YMO77`X^FInSum=jAWd|` za?giHL`{^*VeccG499i=VQEFc4RKCzH z9M6%qZ5Hw%#N(thP~5D+DSLRkj4QViKTX;e%`v#M&A_~S;JHi<&7(2kQ$sI_pO8Ov zVpYt0?^S$*GjhshjC$aIUWY1-Or$3*t~ z;@e(}sGZm~h}j8Oo5zj6%N8(dC-aDO`{z=$3OZe;oTLqm6nrxYO6V~~D zvDM4EmVA#ln#4G5_Mx*yvm5(Xew*KydBcOK`NNPkm`C#nR@K>ZwnMdt{KirUyM}(ia@|DZCLiwMRgTC#v|T;>($_xlvJKNjL`%$VT)Q_Ws(en3Yv2cqonZEf zbqK`1I!|rRkUUXeH7vhL?-o8ui@ybV)F55&?FE+?&t8)$o>k4;3#Y{0ui3hg);#P; z8R;;k60gS#52(@nVES@AFIT*r%i-ORSJ`0HfL7OfE!RFQ95(!9(0RqOAD@f?b1`GH zmV8LcXoMKUhJ5F{=wQ_*$~_tB9GASsRF~N+V~Nf^`;%otc)geyNtG>;21dO0D`7(% z^=y#L$$i_21mUevB;kaX!)n!e6MX}V12-zgiT*?k(|J4$0ZH2fIh#K)JW7?byT5AV<=xK2$4 zSY~Dh18qO>d%6b%-eoi-j}*yq$hpY|!D(&>v%`kBZ34fokNp7dCBK76o_jM48M&%8|o3NB;H!J=u9Na9FxwFYlw=6Gm6&vE= zaic8wAkFi>7tc`oP`km2!Rlv{iAdJ2RO>y3fI) z5;d2m81d<_uHeYE{NRl#Kp>{&%qs$Ne1We&Qut2blHH)mRA7E#{Q1VW!tpc8d%tT$ zQjiCuh5cdVyDW`wVWKKJa3YaPO64(d^#aZV+l4m!vU}FClrl@|o;{=M3_og|ZoQDo z8G~kCX_CC3u(sVkSZ2<2kCx3-0wK_j?x#^zm-pYA&qVBR&N(hW>wRXsm%`mnRa&!{ z>1VGKy7*!EM>b8=%E!@t#%x3r{(O7o!4y)~xRo?!yppaS^tyQF>*V(+JiVR{9h{Kn z{BRBIkZ%65#af%7ue?A=J6~pE*PcV0)g_JK(7fwF1UrO6;s!ohEatBY%hfhS9Y>V_C#ei23{QOLCohk|&b2 zl#z*H!5Z#!6a&GS&dpM?c{y>Q=ypXuR+Zym+^jY1V3)1pmjf-r0QNMWE{ zuUt}X(Zw!Dxdk_YkS8cw0~@Gsa{#<z)>a8{A^1v4|nGj>_l$#yQ zlTIB~zbh-5{V^=6as|)laX^a{#X=&CF{ImBh%Ve)>de!iYq4+o1Q3I|i=Av>!SG>Q zst1roC%>--QL5Hd(^Yy2sl8h983RB$=X-}or0)_8adi@Og-MZ9CC6_v0i*xL1>iQU zr%T1#M(5E^{8h{1sp{!^jylK98;PQmZ{vOkcw;4AXiH|@nXw{B9ZOYxp0pkd50E?7@sl9?udJ8M(*JGz1>t@{-udBGO zT&=7)<1=QC)!5>u^t5W8Zf>s8sZ}ax(C@;}O{9&jz&KfPnns7g2GJb@PGycgdqzf+ zAIKXr_#z@Mi?PecOclsYHTlA56#1@|ME0(b)`sE@_c1?<&PDf?hjv*+JD==qX{<+Z zoNW{&Nja@uuqnF2RTAx9Jb2 z(x35_`rs9Jn~`KNsH>G)sCzqp$Dgie_0Di2e>0*%VWx_rNU71QP&sZP9`h;BM*`Dr zx_@)!=NX%i?+2y|n~n^-gf#K>k3d7Q5bsA0V-!owbkb0&dnMC-=kra4F6k-uO)qsaFJ)M$6(CxJapYFU8e=ZjTnCuQl2Kt5)w2a>_>92>oE$e>TR$Kua7nWyv zKT;_!bF!@3?+u;mwtFxZLZ*i5*U5RAeqIJ5A=^NYqyC3 z*S9M|jUWhWm$yqtf_Jn1nYjH`mL-$YMn8?x!s$_>QfmfKam9@UigkAA{w`K6tYXDw zw?7qxF&|5>p4NOH-bc&GNGTu?QemRvQP}e%t^=y(Z_?J6lgYHH5VynlgLTii@ zs*;E|xN-%n!9^|^@@`&lHu@suZl{Mq_pB2!@6G*Q)K!y(F|!Pf@L;y{p>{FYLSLuT zAEnY_;}YQ?VCl$H2-=5?{G-B$)@g2FU7gz2*4B?tZs4LNSM9!@ivJlbZwouOPJ#N~ zXC=O2^k%y|K)l0ht5}-@o_d_-sMf;6VS7!jd_4(EfOF+Q(-7SD;YgDm zdhkMGRj_C^OWy$Y^o^j10qgN>^{75u;O0o!4~eNoo}Q8SP@L@mNZ_BZFF&TrvhmzE z!Qs&_Ch5x?(x<>Mc~SJ8@+61mjYhj4DG-`ZP_vNkjg{l`G`h3$mb$m z+I}KKd`Z^`3MfN;4cGJ16>U7ov%iR-_jO0hW=|*u5<@hgCv&s%!~Jc9R^~)i@6b3fJFZSQ%_~} z2$#Op1;wCWKL3lPBOBWRh_S`T{Qgr4Dr%taXV-kemOfCM86JH05sjxm`Cn#_n?CGE zjD#It_;dR=9Y!**z^%?<|I&mULjW-?>X{6-;5oKVBYd&4L7l(#=YK3KQbRWaEyFwD zhiiwvJS)b2Wx@u3PWsLR_AhOS9!J*O?~3~`mn08>@K4A7lTwtYLOK57#Ys}f5o~aO zYyS@6Tkw~^+@otvWJB?DLsCBgy>npIU$4!SA%8m@U;66;O5=!t}TzhJt9Q1hUE_xV;j&zu@eR|2mQK zGB5*7s_~y2^X@~jlvtm^h+!p~Ay`VZepN1f)moz(U;Yj>uj2zkEn6jT@@$dOw`Xajxh0e`!`AGgvJW`2Sp~|L`nXYQ8n}+z!p04E$pTVv6V(vhyU}_&SHDHw#jx zwt06Zz9l_e)Z?c=vH58C^tnCZSPp|Z8`8vcdH54zzVM(>R{b(OmR)~)kwACJ&H(vA zrXVMR-_ID`s?pRMiN^|ej&a^(duY((1_}7 z3dZhd8mldkh1S)9>nA1rc0z$Mig(spGy^7y(Vu0F`W`Ix;m$ysu@3|4I*QyaJn0&` zyUP>T(wlVte!Vv{&~CI;xUJ=&=YClEoCF(vyB{fYr6t3j`2KhR8hke@Qy&*59R6;?Q3wyV?+n!odMX5t9l99!LyQquRzQZ%XO_6npW%mH^qZ02!|7En{>ag6 z=!s~-eZPC+S9S40*t1cj(uXVlflw@t{jf@D-np?HyZ-yjc3j39%7Uwuhnw06IHKjx zp@#VgrvES@3}dK3h2H=dRV3yzChxK7ntVxtP5m*~++mUrTV07VRR|Y+=2#hD2Cfw9MHYpfj1By9t{Kw=JFFS9J&{*rvaN8WC%KcT`DKM@FfvfmyUP>r zvl`7Ld_BWVB4BDfsa!ptT~y^(r>2|B#|r{42pVG_CcOi!cq%%_b&yI_3Lvv`!C+#N z31=TqO$u^xhP0vEj&$w9Cv{x#HUL;d``)%pUX_d=w>VOh-uVRplLlUe(vXwnY>FA2 zLEfrI*~r!2M=}yVylGgSigt{Q-dO0D*%>G9>v&Q!hlfHCh7~P0X2J_v(RT9&eG0ZC zwI06%pRIrEeVvIdU7CX)Ym0~dhgAS*@Nf@|RCGkw(bDHHJOJBvTOQqTy0SL)F3Lef~hvw;?dA5VqH zUn%X`DAox^;$Xi1PL@RICHBRgZ%`^cU>hqYTn>B?Z#UY^S@db(mmD#benq|zBY%Z_ zwmpZW45Ps*oX${jAbP`%Tx%cvii_HJ97wUxYIlk>UW};(2ZN~g$Bzq0qLV36+P*tV z9-g97Op)tdS2#5q>Erq!AfL<;j?>j{iUx|Xl=%FV5Y7wQxcszKz+rNH(t3VCBhPVWV zf7qRU5fd-N`6PwkfJA?+G^rhei@bMCaK6PEV7VB?B&de8kwMG$WPK`BB5-GSq4&`W ztAg)}ERHruj~A#MXt2FV<21-ZOD5t^M*C$OcY42&J6oaWl?}g9e5OjTJ1N>$Fiobh z5aJFVE}n@27}vgrEW?Xy1m-hau3%L%{aY(scdiPx3|aEt-TfFTVFug^m@m8Ac+S_` zX~5X@hGf!9@!Q7-MJD~u=bV^?S&GKp#&=Xo$equ8BY)@W+a9s5isvDId+RRbPr6Dd zze3t{g|oY&-45?7sMJezdJRSValw_ZivIzfOGU7>pyS=~Lo+8=?zN>op6?xIF;S3bW+@^dZlXW$ zkGK0YmIyu>cnfH9(T%L^+ij0uG%c64tSDKeV1}M7wQo{%KcAgUNJm82`cSF3)?Qt%z`B=ZOmu@C5~{2pXO7rQ2t2FDdt6?dBU1 zu43j$YMt6IB5Kly;@~D7;zLPz^SvF>3~Ek=$j^{`GL=_rBavG+R04fvuxI2oI&N9);gx z&0(In2yv!r3W~SE(=C;vO&%v!asN7Ca30iPl3vzDPb3q9JJRS05d50-$)yi?KI2g2 z$eV6Z%4@WXjWPFCl#z<8*%;0Adr%`EFXeZ$0jIo=%2ByrreDx%l=Eo|+mjZ`X>C@ZBKgf>l+5$eE6C#3i2w!CpwE{?IM;-VbU_s+II% zzQ<~-ViM$iZ_pn9$HFyR4@M5Rrx|YWtHMG(TUQQUAIIopz#lxedt=%JrSGFStakKW zn-GRiY5}>rovK*bklIfI+yRc_MsC7HOEEch?4Qt!U~&tw1aFWgla%kj;6oEFD?*`vcl`jmdI*HD;RQso9C8 z4tE+IOY0zmC$i%zJkUY!<`cKi18${n$3=s^RGZ?8_rxMmX6Bft@6*NLpF}mjTZqT* z@LU3N0QZ1{RW9c+Q`Rs8slu0!F=8Xu_WKpNw?DTcehNNbll22vLpaXbVo|Im0Gp9I zDHRO{V|?CJY)_H?h-cu(tx-0KJZ^}!GzrGr z&8O81RDb9@FcD26nERr!_#jz&cX9!h)r7V_E+HahK(qCtn2=xX;kqNg#2k!^h+~B- zfBr10p@F+9)qmy5bM}b=`bM8Hce7HWieFw{$+T?LY;D}@h@kATU<>6U!z@mS$QX;k zeZ;^(0JLJ=ZU)X@-u^^PVA4&xzxVhMn?ZU!Z)OI|>Up_CoLMLlzQquA(g8?|+drHw zk1QnrYZgFW{hy-)z;sh8Fh7_LY_y*xWQV;}7f1ev8CcSw1i+MN(D|LuwR{3HR)2PL zyVtKlSo3PQ{|GgzhRdVfXdH3BL7U0T!0|VcYM{9^6@jYgK0={IeV4#c;?*^nXO4fO z8kXobc`!q(+82ef4V;8I%aG}Ya7V|J;!xinDSHe(l-d76kCpDlXhqchM;|}f-tQQ~-i7xuW@pf1hGK+D{)kp0BNxv6N~z)`{||Yr4lB?>k5lJa zfH{g4^>xqhfW;v*u#V^+5%f$X`HmT65&=0_fID83^ zQhfRLI_>#{sq-iN7IZs8RU_JyhZB2SShN6tGEAe%!y9ZIT+HykGUb<|b>X3(K788V zdi5bz#aI2TLkI>dG%f~%3Kvfb-^-c;`g@tBS%icx*!4-0t4x8$bs`g zX_-tLX#(RpzR~SIcpe*6Ag(NNeSSQM%b6RAkeyG$w`q1rjqR&$f@=W~ zxtD(|>$@{jMjg(M)H*D{tnpotD307~Ury+b{us#Gnq{%5NiZ$>bvVu?)KcTV!kH=f zplD$2$A5=tcs_b>7Ub=+dy7(XuABvq7>bDVdsGl~Gd79y=gKwQ+Vsm}Gf@|g?MHSp zm|)i5Sh zNBE8Wl8dBgo1IM-=ipt(>$4k7lyTpf2J2Z0X6H97LQ`2v9lE`b*^D?#L=$Gf4AJnJ zY|}O=eK!O`q}HK%ZAUf1J;Uqfq8kY68uYya zZOBM@v9j!O{M<%|e@E{Qs7sFF#oU6YmnZ7~kp$&{f#_p7d|4X=@44QNx5eZ#m|bmm zYCbU1P(t~~E0B#RAN@jx1|cVk3~s+Mc;B^MsTM7{rKsoT5T_M`p*-fyvH4OH8~j^F z_crdtw;2_?q023wO`gM7E~glC2x-ozOh{StjWq4NHw^4VSQ8iF4L34y*tURZxk_gZ z1crNGnA9QXSRec;2ndz zkCFlY0uZ^mF8kuAttEE%vuC)R!9>MW*mTrtG#X7^j*gbJU8$lA-ye)9YyGsZUGzz1 zuZM_4lFq{778^z`IPDkWR0U3DhRdoW3`lCtWtO6_>64Tw$bjkTL+vt zyGvw-=s_j3%9h)H21;n*9$lg14$U2#L#LMA;#Petsql93z?#MLa6LA*oi{yMix|=_ zG;BB+A=^0d4NRVfGz@o~I!0VAb%_64AMZN?7i73Mp+ROT)!ad-48Xjs5wn9Oo9_EC zwUW=$Zf>v_59^oRDTSAC7}(fx>5W02GW*V(IK)H8A`zM-&tWmVad$$&fc2%w%aPjG zG6gEZpI~y-2_Yihcf=&>DXgELS7g`^Uc-u=N!P-uAb5AFGqx-|RXi@bGFcl!8C?vw zYftpX$e%>3vU6Sqs2vcCk+mu8`2i4Mq5PDfD{m5#?a>vwv$mnpl)E*8X0DPZXf}!1 z)jXsA%4hx24<@rU7uSz@@WE769bT0b4-9m0D(~|u(H_$Il`%`+(9)x6X3dec?Rn)M z98iW}6uU%1@fY}eboGqcNUTTO9x0Z#-clxO^KXF;uDxRML zQS~Q|6enb8C=;Xb)&?brRW!3Qlj1j$s19gyYNam6^Vr|$ob)Ol4DDD@D&w4VUVtWy zqQ6!>PB>*?sNC{J>fZ51)-3`c-G@I#{WtE#s=feZwKR2jwE$ z^8E@^vbORVtUgX_3RrY*Uni~%+mijErmkFNN>3^x62Ye|ZNMI0+;;>HWx8p(F%M!Ku3aP@=7IV}ydgLji(=ytxyKI>9kaL2PP8yonH`J@;7TN|r7Wht( zqTi=?#C>%Pege>2^QB^*^=02>chzpV(BkqA_7-)Q{ej~RjRWeH>v555Iz#Ld)E zcxSr35{h4`qAX{(MNm=*^f0F9D~Ae@p+bjaG;JIY;{GHL zjaFf$56V!E_r992=LShT(`a7bI}69n+hVopSfLi4ovVrOjw7`ySMsNi-JJ zX~WF?bDhQ#^%%=lL3)Z>13U-dJFHG|X}@x;us{3x9;%XoZU}XTI`!p-2Bm4(*kYwk zr_a>%K5M<|Y;@e7^Gq4f5P<*P<~=c6SZ_BA*HNVr_lw<+7s|F@vNA;GLwM1V^2$Hv zh?B|ah9rnr?v;xZBSRPD#tG@K=4Sd|alkL&CR7RizrCRT6C3>R#VWXW={~za0W!|@ zVtQDX&bO~}qlwv~f6=UYQPK_uRuFam-x~POuAqLg+?J+I6J5Q6NbEHpuGjnYpSKiw zpTO|QLaUca`;;S|9huMXiu|UsE%h)R0r?-we;KK)4(E?>CGT|m55&B?`GkCeLidX! z`Mz$XAiMjR{F~dYj)}|x=FJI1!wi}zYNu1wty~ccv;8deNisdz@v(-F+xkXx2=t0g zVI}7#>;~`QVgfF74BP9$Ck1xX+GiH$DtOVC>~<8Docn(cUT@C+1WO6d=U zJ-G6S6}l#sYbtzGOXBS*Z~>t+7AQt{Dq3^li57NBb8-`y4>sI0mZIt%)3k?rz!@3) z_{ZyznC7>2Wp06g{Ut+<4F_3_@+BE>P22yA3!v08E&vTK5OCtz@QR~pQySlpiAjBJ ziV@^o{4^t)vn%49_R(n!y;f7jZP+rQew1Q6zv0Vrt@b1Yj+Q|FHUveQ;E7vaA?LCz zyx7JNk)g*GphpLr;D`JgS;gggoDy*JKGrc5d(Dd`Uy6s~AfHG2&3@eDrSw;4d_*8A zLO8JTmL6E;jsgqs#(Fy-Yq4S@WU3@;`M~> zn(9ARrd|c;#aXa?4~RKz&nQ+@D6DZd$uVqHcS&RN_-*UH0kfTc zEyMX1^7wW{7m9Y{2x7#;-6@Qk{QKctrH(PpX}lOxIZD0;Dgn?9@A$p0g_EX&2Q{{W z#W}^q#U9>tvMz4iWF19Ix*IiQrHKt@*B%7SB_)(v8!xO#9lBr?0h=QcO+NCR z9Zj6UwZ$DouTKb_DVZuWCN}G%@8qmq7`A05&UZ-OGNWUrpWBSR9z!DoA5&pp58v+w z*Qm}t6H#IbJak~YDeC&F%=ve9IECX_`!S-BpI9(sn!Z!gwg#S3x71uN^*n%MDHEc| zn{U0Y?v(50T^S`MWMFZqBzjBei7{k!fOv&6%5l>iGKv$_LJMTA}zr1gCid#M#-#jTv5%l3aTlawP z<5}-YBvuKfp4Bt#&*@sZTVW3{XR^$SeQr6^+|+e<>?2%PA;_D`ld|~51W6XiVl)uo z1ALHw{R#;HGZWI|Y}8r!Y43Ybo8QyzRx#60Bhf7j!}tXw!Wsjw;F1c6lxyyH%BWPu z!($u-l>XTuW{iS4SbAv^p74@CV#%sVH+~@Q5*;obSADbItB|-y34TP2y1--qAjj<= zZeJz08YM&-01WEZTMfMS& z*jCWg*YPGdQuboHjh$cynU+J?)6*1C%b6<1_~vRu!Dk%Nn{U8r$nlBH&jd#vgF&t= z(4|vs4IgVQYE)BZH?nTr%}^+-9d2yyGA1N)88r|Io79_@Kz(Iu_R5^yTYvNs-` z%JZ3ma@|+pxQ1e;IAyF{(N^h(BvJ++OhyoX8;oZ88GO{B{Ojr+rIK&NPD@2VdMbKX z3EH6wxFIu7@QR-R)bI^0awE+N4#1*LXwaF6J=1G%R}n}qb41R^m$I^=7eE#rww0JS zSA3Q&&F;_h{qVcOS6DSgk0^lt{ab;v-zgOW_7mVjm;I-pjH@xmFnC&c zN`V5=E1Aa(b`B0Yt*YNJNv1INb$CT5==+z>K!>Y%Qa0yDP1GzfPLCn76Tics4wn5H zH0^|h1eh3s8-U*B9i&{F*FPu@?(%AW#!g!ip8HzK<+HY|y1F#J3>AgRnBG@Tp$ydQ z4NYK0sNsg@mgW>GxrX|I-9%g+Y+QUi=otaJ%e-DQ6c_1Sbx={Mi!_U3zD48BYC-3X zG>b1}cfI`7j?bMC>s)xL2buqKb4~{h*@Z{Mu3Jm9RyMsM`#iyi|P+rmQw4^-1P+~_~oHvXB z9GbQq&p0+VX*^u5MC}ThkKGnR_1sq14~Rmb{6MWYb&J(p1mvGkN~Dig675!7rfN;} zOJrqfl@w_>njO!)UCptU=Atn^_w!^aXuE#3rOTC4$Quqcc|m#(+)EQVI*oqEtu33e z@6^I233)MTDq1NGC&=uW%>_Q2m9hX;IAa^uAA-zC6*rdk8w%A`a7GG!`Wj!Uxg2!4 zi7sqApxIqeu}nNA>q69rg_lj^L>xH{nMx?VI@JXmOu{4m)}M~2zr(U9(h#}O0C!!@ z)3yjAbaAQZTmt__39gqW`Q2E(Umb5u&ULd9)o4tXF`UTxlMQgX0V`OSbd;3rVP(3D zL@$qnP=pTg*lh2~3;=iH?OK^#Xd&qXCcsk#yH^)GN$CzpuIY=VLN~Zd8=#+AtmJd) z8H&y6$P*{s1-w(-ca7mqP8}zf30nQnj@$T#_V&yor93zO(q^;vz8f`v^%e^R->2KR zCKoZ#=u=o$+ru3NzuXItbS*|nN5|J7VHuMzSw+@jD&;jcOy=r;w8QUFn;c zmIW}T%=6ZN%OaiX$Vy7`hlWC7ximk;`s^wUf5+|q@~fACb);(vrOzuJ3h zm4_R`6|S8Y!!~(OXoiLToztCW>)Mx|*g7GdQ)8Z7@-Uy(py6@)QI&(etAZw2_)>Du zo)h?@{XTl6){;Qq8$#7y@|e7_&hF?&@52kBz`X;ShfNOjbb=PH|72|I z=P*mx;xI&5=@@#XJ!M{=Ze}vTR-GL|2IdOK5=&-}dPjkap)^z=4rJz(drd_B()IiO zgv*P>Lg%L-c9^77A2f=J)evkLjmx1v3#aL_z2iv%)8~P!Vw)>G<~A_twS3x0c%gpx zh+GM||4u{2W~F`C6xzU5hX8u6r&eFwrjj$HHaEGoH4dur*FgC89WT+eVao3B$?ZHn zC{+V+pYxsH^ho*0?KPoa&A>LP$&(I)K!)bm>508gskJAL`wolWP6m-MQKTGK{~LL4 z8CF-btqWqoCAdTI;O?3P*93Qmg-dWJIKkZ^cyM=jcXxMpSx7JPowK|5x!*l~_v!tw z*R!5yTFsi}^^SLp8dY(}WYXusMavT9L`9#=WX{RpdHeYmenmW2ol$ep8zFqNIAXVi z`=m5`VUOY0DuX7^t$~$g)H>H&t^QJPM6kz83+IXRO0Ph%^dk9yPP4~C>tZc?uo5(A z>g%$f&DZ%MVU;Rlz~AfWvn=e)67g`uUfRe^pFJ6;-}+L*!gHd~Xnc8w5ugC40=MBqR z3lI*0ENtIlwBXt@SxA3YzW4gor^5h&o8=KxC)R)aX$!5CD~sA+rgXgQx2|4te|GTHwk+>L zutFjrHWgp3Ste|3sp_Y9#mMW2JPmBDu75@QVn^|R^ICytZm)gB}B^C5d!VaKQ#%o zn6e!5_qMY8%r@1K)R0CL=#1rz;?7k(%dYIFawW^@9FKXp(5o^zPbLeUwo>uSw;Im> z=ERAg^+gW$A5LQmHsv4NDy_Bh`>WHwu7YX5AdRg65m_NVco(Y?U(I_ED~un1NZ)su zw`R~$YQq*IV*BY&9KMqT6abh8ZY^ZGAtXC-2Oly1eCt2XH^C9VgN!HafvW^j=$SMC zxzXo6@_0eM=#8_4N~r`#au4|`1bez7>^&VP=z<7j-D{~amQ=+x-&teCunf0=a4XHsKXX+Cp=nA z7P4PX*x-SL#3GdZ6f3o+L-S9NT#t!~85O+?6Cep1Y)z{YV$)?LB&c0nToe@*xjsZ! zhttr|^bZYX*Vp@*h!VmGPm1m^j7L|)k&{zKYq!B+_RxYLP^79-?i&KW++?GclvIa4 zxJikO+?P_4fG!8o4ydW>`2qzFhrBqTDo+7-`tfIA#%-^WDQ-^Oyqu?OOFPVp!@!9B zc7w2|f`NSnvy24Fki_IHPJ2glX7l5?La1tOMR*sj-ogFY{r67I!P(X{8xkEpJK~5} zYpx-m3>~Xp^Jka+6I(&mKZ+_4AS?IFGDRf3fA@};a1eZCieuCveq?)!TYTT}TWIwx5Q(O7?1os=HW7JyF_Qb<3o zBVb_;8+{^>|4GU0dd{a$?^fxR58b^x{2>DBFhA~cp?yyc$GZI%<~q~kG5KJ<`WTTE zb4X1SZIXo6hBo$3%{q5c&_BjTO-cT)TGO@{SG99};mlz1Tt@Rbs47TM9{FkXZn!^U z^6A*u6jP^PrK`8RT=vUhUcS759mE!3CuVjN!|~1DBv(qc)}4EXJW>{JC_X-Nfd)6I z!ep1P@CW9U06WKqz5$O@ zVbkmZ#c)P~7|!~62m(z44n^k5U)p~TBYl{+Fr zJPQZCWq;L&*$tx2dj_M&W&OfKr~DiB3fzL^q2*j#nq)_#vE6U528w-O^cNPkDPzme zTd1TOH?|@rg=#I-tjsxIBSPW!{ z-%TdoH{-m;z}Q>Huy22%lXDfNZa;V7oc@n$Te!^c_tyRWDr zct@&r(l@;5cr-k*(*v%^+^Ag{5I6}=!3aJfT>j}($kVXx4rW{ZIT zP`S;UC!IFjycu~G@f!9H$z+P$@`etiYl$}>LF-fHdt}ARtIiUu%d`5EQ&5*7xQIoZ zjDghOsi=`H;eO#vpHG}EV8yweWysMJeUIT}mUJb&2IP8;- z!Dv|1g#y8OkYn?k+QTl?*W;_MDU;7-c4c`gBd=dq3Wx#rhjoun-aGC$r?ByLJlVppq0oL0%8JsDYBez@S zEsf9X&W3NpP&9b+H}dMk0nZZEXVW30;E{uI))dz?yr&AMoQKilnPsFuLk{A)AWcxp zS+`Zd@3*g6I*=m284vs~sP&&Q?En4>_dgsZ{tpj-_1rhK{g#M-_3+QM=f8aQ&$R5n zeD#+-cl7`80Gh|%s_mZ-i<%TxCy?(0GBtjXo5t|BL48`+6_4hi$p9_tM}pTOQ;n{s z&MHjk8u}F*0I*P_nIqm6(JME_MwM4zztqe~pF& z1^<{eVR$%OCKs{lHl8)YQS@aVR(ovkpycL9pkDv}LQkro1#SjI5eo>l;$Nu+i0@y4 zX5FoV;$q#4&Uei>i&Ddh0zECNUil?f(Dy(j3ZjUs$$L!pGYCJDnJCyF_)+Ah+5Bt8 zaO+nLz=*SPsc4S=pF1w@JZ4<1d9udGdl{3BmTqWhXsPeCZEyk<`?jQMewPMs zd|-O}=)*uSNhG-?ANS4SlzCkX_{aXSd>$evta&i)HduzBhK@fZD$Df9$h%+7&BOQX z-gAO~if|yE`R|JIPr+8#NIoCyz1W^_*tcDf!F-v_Ae|tIthK0OWyJ;F1=v6MUnPX; z47U66#>6Z()tOj67DK_~)E4$HsSvhB%655`Sn`>{`!suC?h{~}l*U&P zujWX&DMx-+I;GE(lZV<=BG!$>@~ z?JcboE=J(<%VcWbA_enRi2u_`2n+mSj_uMa$Q_>^OM@b-lP9VZipD6u5&K-i5_w3< zU4N!q8o7L-fjeiDH?M%^Ku}?%FN#@@M+y49{kTPV#y1(I&#_CgCcU;vN_>yg?!Cve zpx8yg=Z_+1hZEz(_MBAY^F@$3Z$`7+p2>ZF;>6@J?6nbNvvQoW{UEoLkZ&by=O@Gd zmOK&AW%bDTI!Bqi>ugcr!|JXT5HLquYw_gD1}2-)Xdtr6@I(`z@U*)$sy9NU|}1Akpl0i-^c;G-pJ%j6WERye>)wk2ed6 zWh>=xqMv(N@0KL;uoB?J?#6vOV9~Y!c@uBsSRV<8V+&Eb+=Ll=ASbH)9vT0hxUA@}z(Xp5BhOb*N6ty1JaS-6H0s&j0tBdZbI8{zt-U3Fq?-SUMg#cwLSN zSaAa6r+QOv1+wmDKj;-|Mv;k(yXrV@f)L2Isc70%diQm-FqYL6N zHQDtk+z8YYWYtJm+f;k$A8f%Ki&BI+gpM8&d5d1uhx$x)sD2s9qP=GU*y4%^$vaR) zw6yv4DQg|B-?Wy2(^r|jJlW5e;G#Qe02!zzIUu^VvZJeWgGwK*A6)5`dY&HGGZ3R* z+mi@x+LP_%X|b5HSqzu1aTM0v{IQ8#Bhd8&gCz&V4%tikFexcT{avau?)_t=h=&hPt|lfXhGi1l{7@e^fBy? zF3gzI;{x(x+CYm~P3M`gKk9XKC&ivE`N!6bhK%9%VOQ)PPu8x=#TU7_u}4u-X>~j- zm8sDnPMW53`2wt*WACnx%AX%zH;QkQhCMa~mpN*$#pJlZRYpUo_~bZjGPh4E>pL1l z*Ikc(X!_;HxvTgMkm9PjR=dkze(}Hz?_Is^orExiTU#EA3uPE+3s3Wz61&&iJ3dUl zAF2>7OVdSMA%I{tGA0^g(17IqI9HW1Roy$&Z?!VO2W+wlCF`aU>QL}ViBvs=A)MNB zpUG|5f(kC987z=EC6Ro*kXB2Q6Y3fjn1@v=z|U;WC%0@v#;Ik)tn$RADUqdD1r61$ z`Yl-|UzYG-y5OB!oRXh}X%1sX*Kjje9B$gZd4{Fw0%=?!W*l;D4$>xKxuQl6xt->k z=<#cI44Hq=lanHK-(sxhSX{sRJmdL&6O;=aP#Pq6JWPX zK3i~Cli_4-ya2s;VjOLL>N@s>}OIcq~SS{46cB65hS< zfbVbxBU7e$kh71?G0EcL(C+ZV41+gMiyXEB2Gfk=8BE0z>`@{@$m1Cav zu6MSSh>d|Mm9L-gxQQ>W#|!8V>~O79lcc(;y-h9*p^*tBCQ?b7HDW)p4I5nSZ@5=! zS;J^gy4pdj7P6z6tkI;c3O?3JO<}0p7xz)n$9znyi^d0Zo77|ly@t|elahrYIE~~O zI8dlGHzcZHb(_q#5+yi}e(=yki4240cTC=8+U~r%XGTu`-t~C?XJ81PRxjqD(}7!0&( zS^We8Q*6Aa%Uxg`-gAte=%lEw)#6*T&Z#Q-u`Jmi4Mm1wK`phI3O^8302jj91KZPO zW4Bt36U|B*Xr!oQAly}VkJJ?@PX75jn`GH+(zQwaX9qr6J|d?OP}Gq&GejaJ?`=j= z(!D^g2U|!%X2PJqgoJQRbdWHqKpRf`5q2jW92_|e_)KuHpI-f=NC=2aowp+V8#G?*F97wQwg7({;J@DdN6q{V zK>t5@1|pN*Qu5y&ynb~HJ`?$o=;1U{z6Cb5tMjkZ*v#N{yij^&_j&uSsT~$n2MW(9 zn0DDck_w8ptfY^|ANkO7x3hc`hQBU1_^H7c`*ZVR$r~_^u7$cdq<1}A5#;yoa$XMm z>mHaMpB0#OP`kk&vez`EJohd|$M;Y27HM$)650M$nJY&pe*gWS=sBD~I+@k=Bb&dB zV?e$)|H9$_ZO-e}AK1m={Il!V&tKecvYR8Qj3#~?aE9|7DTbS*94>-vBHu_tN7#WZ zj|9i*2xzFdI1G?uC2K0gy-_KZ$lK$#gOpRK`nO;pZcfNZR4lylhUL)@9PCqlq>5ad zH*i;W{lvQPV2So~XQwUS=1tBZ1OTt#|a-Yr* zApyLgg_#I15s-MI;y5mh9@bBhm>#kli~ae0FB6FIB8L+PzpENH5>E;s+a)OlUdd6A z@P@9NCD9JIC(X(X8aAi3Oi_{EUInh+lVApF3BRs?c|=KW_xTW_ES51wSX4@;w}Eqd z^h(gxnkJ_W5+pcyzwZ|SY((ocy^&lI->R^>W?mBEV^~h8_lMN3EtTbd));+zo}CO$ zr%74izUEGDP9#0%$Vkp;jZ&}lyCDs`Zd`!v&RSCxt0$An6OcOZoe-NkYY>^vR!_Bn z=6zZAK~%XPoZL#s$XYB!+_2ldD}(E;L7t(*j^9-HCZh~Z;#05I)7C1Zs>Fx`Ib<+d z`bMk24EKG1I$M$IXmvjE_6zO|)W&D%mpv=(WQ_6?YJly+g4k4v4e6Mc6ZRNgu=Tyc zo7qiHiEv3exGc>}xJqej(gv6w#m*Jr{H7BJ)6!|LIvh?|0Kc0zq>y^)29|+4hjYN5 z%5+&p^I`_3xyI0IRJ|d{zap|*G;Q88<9VJk8-?HXTF>-r#;)ForSOj|(I&fx1-B^y zKV*cqU28edp>mY`_ol>q4WH~j%AB@0aB8(PbEA^N)MZ`or?^;e<0JAE@lq8xhKo@1 z+Rfg){&G_l0Un@pd0p%G%Bdk+UM98{`xJ&g+Amo;J#t8Aj#+7OGYH0sa(9Tj{HX>I z!?Z!VeYLXp;9fUty5N=$BI;lLPhuc`Vlf)JfZ=AWj_IH@c$Ms6F`Ig(I?rhzPh8R) zM|k~EK=JY)o?RL*S<)u>Zs9ij0$VbznZ4x=khBvd191(B4)W5M1B zHut;)@||W2v9P7H+eQ`-5xI~>ee?PENB`v$p2{vqLeqFf(RUK;eXuIUx}#1Z0}FRh z3~e{c=`LHSFI5Iurc%9E8_VofbxEvL%pOW&qe*-jgJ9A493M)Ico*}ba~L1OB_7xl zbL5id#Y8@I-?uI>Y^Hv(x> zwKiujg}Q!G^kp>go@ri@pcA>IZ>%sHu9X69Y_?FGU7x^Sp1=B$9gS_?IL{<$f)06B61_Uy;`jQkZ*&f?A zRawf19%RsGk@o8^VR3hJUNiq0V!<_m!cN@rc6HCGN0eT}^kX-fb4k4CUYt6T4zGJS z*Q4mm!Zb)uJl-h`_kxWS@BCV1w@a&v4qgvUh#JhHb|ea>&6m=qMtMR!&3lf1S_OWW z98BQ5-b9SgW6N5C!?w}NX9HV&xxzaw1b#$mx#5;u74-2--95ISKG3u^n{(iSu50vU zEUn)aMk6Nb21f98d#jSFjnwLud8G~S@aCgVT4nP=zZGxc$^XM{6D*O#;gYg#!kJH2 zNeR>6-=9E$B^WhuW`PujQSZ9z=_L6sss8Albc-=c-J8lKad=NzIU5P}O4V$SDnBC-Upz4nxPVzuUjh42ygdw390?9=bwvaS30mbb-W zVNz5yG;}ypR3CaSpVw>}%C`tiSwUzoN*s!G2E^!vzpXJM$8GzQ z*#$A1_kM!=+#sSInyGSD$d&F7ys&&BY2NXS|GsI=b~N8JrLe4q08mTMlEr@-3grnPBQbW zo*mJ89kmhM%u6?}K5@-iWvs{lS*4|+PBl9kSQ9-~*7WlTI?U*kFX8-Ic`HG=41`o5 z|A0RyvZ40+&o^|DQzBE63ND*|%Q5DuAg)$7<+9n>7Ksm`XxlGUXE)^JPe+3+;dY__ z0&wE1+j7iyc!3gdex_ed*OWa4&$rog08QS0IV<7o#cBA_e23gt9!4De z$On?KAl2-bI`}_P`2YPFL5KCGxb@7)VJ?qYV}9!p5-CldUubdb&8cy556CGg(Sj`= zxo1Fji)$?wcc=U+ugi@}A&Weae_X0eqWnjD`+vu>IWi;_wF2eLI_@3#Wk|ZK%MY<} zarJp`hz8%goS5_cq41 zr1&SL!T%~$OlDA!@TWi{9Y#jsJn7XXsZ%8cI7|lfJiY0MjxeFsj%~-l0+3v)cGn04 zClcF#s7V%C*g z0^Hy$P{apu%^m5Rg#>9zq zI?*L1`>W+QC?V9m<}LRrmAiz_DZwHF~>^%6Pt;!-F;vw=6N##4JP$tNeBcIO}?^rUFHMP=8zZQwKBh};8b1oAy`*Q#p(72|r6%r9+lOLHS)8`60pWrr(uMdk8fLs=vX14vc_}u{hDj%b zj^-XY6IL+p08^4#S2B<|9QVfI1Jd&rXGV`sWG+vqVlIxum4cpr92aYgYe1*_2>IzV z=m4bFz$*OQ;+w18S0`bRV&S!;Q1yHPrkTeOLaL}U%&}ymOnYmBQAK{QeTzHK2>t+u za13swDCuDn0g*oR)iqR<_xoU2f{p%NuP{K)==i=zxXC`(Bdtc+Yn4p^Paqm4AY$8h zgZTX5i8LBJ!r*>AvzgVM;7VD`cz!(-@#S2~xXh+vg$U|VHHOk_nbsQp>C%PJGDC< z4*cR5st2P$U{|e#Zim;XXR}Iq>T_Q+ zAlDoouR<|cBeT{sbf^#Z!k+E-y2T6Uzi>ZI-@a3qjP~5K8=e&ao0-5mc0El>Z8_p# zlPT0cNM+{py7Fjl`Atp5H=CiLAh=r?bGmzyzQ=r+>`~zUA|LKzMRW1%ofzn;U1k3H zsmXrDUF~)N0`B*Po|Nr(;_r7aRuz1?@?Mz<+;$tPEmr)u-*vg{mn^h399OQw*a}}M z7K#e?bI-Mok$%?a4l~up2t2!s*I-KqS`qetpKXqmAdBcbeF+_mU1@O47-iF8OU^$f z>L>loF_=CyQA+^Y9t+tl<@3vLK>ht~rnI^3dpQ9|yrr^6@j7#DU7YgEup_SR6-vHq zggwHmai~QtAmZJLe7o3}_(@j~(W}W7=49Oz;?~Qk;}L^vS)1#iF0{}*;I8uiHR&Xi zo{Fd%>2+*1txrUW-IL%Ik*SNuhtvn2;Y0l{^tKg6vc}KkIQ3-HB-13dS~Yc3fnf6W~V?jhJyNy)-zuCN}3QvrYj)i@+6qY;a#lfS{Zg3<=JqW-5CGfu=^SJoowe| zl10OjR9e(Ja@fZ@FWijuW@K-%?K%5!sJ_z;x*LbKt%XskzzN$=lwepX;-$cdoF*ri z!TFAgD~$)^;n~!((p&Ze!4`1MQ2m9Dr^WE7K^dR(>fTDT?ymuwzX$uK1as7E_#uo5 zwh}kS+Jf?6X7Wp`ejo^jZ+8)I{btpN|5D^P{(D^CSZiqXYRKVw8@!see)8j!8+2R) z5LY?%BkEUZ6ayYxu`wHJ+I#}F^z?gu%GiUX^=Fjj)Tb}~i<%OzSG`m4qr5`Qe)=i*g$LTG z{9#L`+h9j?3Wa;TjblRRE)RHl#78LLe>Zfj=iEe6JX*Us{u{!y59qrgb_~0JOLh`ki&MSm20lxYA6G|t|QG;+cICr(wm=!DJ1b&8@`i9o08>UXxKv^&I!#XA$*g&L8*o1CUQ@UiSv zyA{sIFyW1%Wiz->(SriIZkP>{Kg?TUN#l(Te^I%j8+-SPohXn=2HwO`xtNV7(_$fh z|4aoPq1JIx+}yP@W44kcn8hvtHmj<9bL7?s7{A%9*aaA-@i1w;{olqcs09H zCyU$DrfXP+;f1)XdruEKt4#ifr=3G5*`qcwugLAWfS0krbr%byY%yu0!2op4I;X~? z@7~Ret1b1Ks~y8|3J*KZc)d$Rub7%eb=j}LGp1Y-Q}{)mOB%U&4>+3GN*moBy4Lja z$lt}2(`Qp@%B36+w_OEt*Sdyf`LN~M`d6E4_a{C`t(ZR{MESH`Ge}Bkwrq6SS>sPB z8r;zZo_?W&&uRen2Nkb2w;4l%q-jNOtoRQ$%>%nOKuhqM;&S(@I`Bqnsn?i1hwp|3 z<2{S`r%xpBe=|O0DcnHlG}^AvdKbpqStJ7KvjLWSl1cBiJ)hMi_Y~4o_Mpt6d`5%~^ zh4+{gMoVUSa*2b>A;_`TQ!zvxvM#q>#_Nx}5AN)G$oTrF0>S&2`ho$~g+GoiMutP0 z{p?O^5l`nf!;>h9JpH+@hrT-+VP>o61AgBGO3|D;&~3A0F6T*bKF-j7n*4c&gZ086 za@(u-oq0R`!+xiVN6N+g%@;bIN?%%|!;3{gi-|oDpm`9D5tcYMc~#3P7y?Fc$6)y6 zr?U`g(Rxy0Y!DRmw8TG2)~+JwirMBwIyG|kB|TqXdo zf(Z|Gk0a8s%TTVSLrNcP869)=30ZsTp1p=yL-u74&u*jNGqF-yb#@P&!iOb(;m2+S zmTy1EV>oc?Ib9N@D5rO+)+6&DVr~tF!(#1*_s>V2=MS|f0@uiEr89a{J(Q7^3OnW; zo(i-k3ZH~M0KhlYtrAv;e?)4_& zM^_!AyUlEJO=CX50|)?*)>K!FWRCOrNRd&&3gWapvE03AU@>qpGhkkL!(sKfVM3JD zMtBnsa8$FRxb3=wYHMo_KdEn^%t__G)(wm7isYe9QismAETUeFq7-u`m%~iTcvc_d zd_HU>GX$fILC1O$o0@_mwaaVJ7DY-GAZkrjk#r*LtRe znd&%c`J>+8_Wol7VoNjxwD=8N)`@{^xgB!0r@B}r3A{mWX0z%mT%q)eOzh4W5K^jV zxzWZp+oqR-W8^8!$aEHH=5}}7tRP$Iaxt)Mur<5&TAKl0POT6(&T{vl7cJ&;yj6Fp z6ycC#xS+RZsBfO6i&sPUX$K8?c;Fm3=jPwTu;8K)RR;niN<|OmCiyBgE8??4-;5{dncJic7S^va9R#c{ROcz zCMtS#-fVPSm1mPDJ%d3NI)AO{3BE`5a)On?O9Mc^)oi+GxD)hgdE?8x&PqpO$Chf^ zH@`0;eHRiVu52{bK3_Op4`f0TEAC<0@ddt&(Da;h;C;B;Udtdv;9hdUsjHOPM>~EA zM7Pn6Km|BC9iw>y7V0s{4RZoT|G!TUOHCGw_O868{y^G_jV57^BP^CE;bb?<|}vg1*0 z)@ii#8O8P>ge14u;B=M>@mwb*LAnZ-RKU${#q#{_({Qq|y9G2fVmCz|m~1^)iZ|Vd zm@mG(6Zdl3$zLC_C zoGiIlVEnTUQ$2AnI=iM4pEF4ZGTP{Z4Nm(60>lzWGz_X3#0f8V<$A!^U$y)ewqf}jZF|GkWa zpt?er6NLq2J_tOUMISFAq6apM4G9>dakzIieVHp?YvJ+-H)|P2snTh^$vU!f-ku`H z;I8zk7@}eMEy3UDC7*GMD{=hb$wkb-WnWb`P;~N4czFm|pH-YgZ=f1}If@DM{M7tp ztfH=XU2iGO4Hpwaa^^X|F3gOLZm7A@eGn>mz2;B7tq->MUf_v(J3NM8WW}mQs&gmx znK&j<9D03o2cmmd!?@2VW6F8q*)m_@tC)aiE-Hz3Y2A$kr|j_dxAbMO)VSzw_F^vb zUNnSQr-6rHk}F@wz|&I*`7zm}6kDH!H{45Ic1LQG?SI;+HUX5u*0M?pWe0$6J@H@O(-+F^59(~xDyS$B! zQwU+Z)6cR%ZdZW-#6kJ#lUg;QU2=IuUFin|!4P3#VetEm{@!F^&7YXfLtlHbUJ?aM z_uSF+Ay{NY2~M{{f;y6~c8Fr|DQVvkeREu6P70TkYu&3fk8oITY3vby@PIRi)R=tS z!8WZvm<<}p;P$%b8_+WHG3t4RTYkRmQna~5vyUBY$YJRf%Cc1A>B%Vs7bwe%bs!sSG)1KncEw6Cy=Ag#B9 zt#dwOIY+v-K9R*-6KZ;_LFh79Z5A@&+g?av+l1A(v4t%GjyP+W#Ypw}7tD(hVZXqR z3^yZwP}pb#a}o(aqq!(HKZiMO|M_0H#OOb50s5?E9opPk_Cj<_iRFrUx9kr4+;?}e zzku1<3LeIO6m}dAhS0fl&VD()N$+`f|L6y&aQd-I1{Ga5kl!(pL35qp{kDS7=i}Zo zO2?D{>> z*nqAysu1Of+_A%8u6N2?!3)w7oEO!+Irzz(vGWrbsczp z8)br<4HEtr9>ol4z*f;I*^+{)dnWwKl84%swlCVx!#ZQ)H`q;6wOQzZ1Uci!S+2_D zo9(Mc*@wHXS+>%g#Ew>+7o(GnT2x(M_Aqm5W%0F+oU%C^lDqo~=6qWayyFJIXV!a3 zNSmXbQ=bO&M}Ftt3HMAEOj>tu>-!vE0Kw>FEfKUt!4aO)S!kkB*fx;>kXm_YZXPt) z+X=3l5z@4BqoO$31%z{VA>!CJL=dmAgBIW*#$HfMd_!Kf^|^A58NDu2A?hm4MbxSH zO`NpEnQk#2y@&#;Ikll5S`H6z19ME^n$r*oT26y>Y_XX#NJu8&d#=vJh_+RkC{6*l z-r7&c$1?tndd&-WraXLW-rQ~~JL#|vBMsAAHh7ql4F+;F7ZL@J&>u;&z@A{O+-)3x1n%uefppM}=^nXo0=R)Vf)8%H(=@~A&*oRI`H~h7w?gS1%go<#rAFtr zdU*J81RFW}ESoQOW{Y`0+~KXWEC+oKHU}`dfE-#`tmTmBMgItH2k@Zn+Qx^Xe=FvS zjqIz$chYmrc07x?KMz8hA+qxcp_+GP2JT|pt}#I3e(URR)hipfelFqV%y*l~1IZ^* zU9&5M!bq+5@I|7#i>Ma$o_jAtr8CJtGGFF_*zX8_FBf1Fvr8EQodn;{YOn$JbzEVv@}TItp0a)J`z<4!Come5 z24tz1? zBSt$)VVhyy=c&6;Uib9v@_=fBb7nQ*l=JZbSkPMM>^>qvnHZ|=wuq0J!}`?^rSfT5 z@1k!{jvtWlhg{;%_{8qY)vxguGpItKw+zCJo*y9%v3?;>9tKRzo?x`mHC~A-j0Q_| zLkQexj1P}S%?i{u02;qTNGHhguDiISz%Xd`b(w&%FsHEE3J~{Hk}=BXe&^S&kCZVC zeTUKpcDQJ{ce9dzWih1koXlKk4udwpyi>JIbUC#GP01+?c6;WJtt#n zXp0&x=4N zcfNVmagBdX85iRY>oFWWOrLVL4|tK*ezr-cB2K>6*F<7nx=r7#^o4Vy)gA4YrUcAd z?6}9wvf(m$SErdOdhmd4)|R{1os!a%UjBCNw)TmWxZd7yZ$A7mCkZpPoAlL;x5w^W z5*qqQiDOiIG`+i%@8z;8Hl#`X@>#L?h5(^eqZf2@`gqxQ^;tV7xX<@>*3dC#v{}0& zYF(uQ=-^6V?<{IF@J5`|CMk=y} zT<&~4_O9`p>O_2r3rK#cx?65Zi1Ae)Z=8OIMZfGcm$1&Z_WpB*nJ}b|O1p3c9+JtE z;(I0dlyjS*hZE^O7Iv%IBLz9=Z@tm1nu(f4)G{6x5{tFz^at+*nK$2a`+`^1*$rf) zjnHt}KGadWUk+6~=_Hg#eIrXKr=Lj)xOukas*l&(O2FO^G2S>tg7qk5zzmu9?uda8 z!@o3a>HC;GM$MLhv<71HPf~Ax3oikDs8QB*8pxu8 zQfbn?y_|6~NdB^9ix?8x+xp$Ztf{XGFzDR7y?Vo5##4^R=bUHs9$6!y>Ka85b+^(Q zcZ!rT`r8hiwzbLn^@B!N7)O$6DkpZH@lnFPjSw+U+|cg&a?-Fsl7H9@OGw+(PgCIJ zh1qO+dRf3ka~3UgAj39(s5G@icat*db&blyehYSiHTUSEX_eI~J7-z#-LIP$xg&tn zD_7bMRi(@E%C}*nOGFWLH27&0$ob-o?!K7W@6(xlBk7i(3u+B<>x#&gl8Y zT}P-6o(}D*y|PFd_QLHBYCF0N%(MHE3q)MZ>D=<9^?FBu;D+CIJLovlhw|)07_JZI z!W_ZFQ9M7-xcjNCF&M}d5;Mx-boqr-NJ!KJ=O3>wyQ%53ynyNF4ilUS z+#)Z7e!r_U%Puj>Zal+U_2QWIa}=A1nwNm=jRMLzHhGePr`HE}c#Ke7dItP`$9fyX ztN3CQeHpv{c{3N1TvGN}IGj)2euRJu(@O@{PMGo0X!kk5a?7K-Mhs_|YjcN2OGfrL zTl{jyFEIjT6HRM&)ASZ!20`i>=Y>zvLxK{(#?>4vt@d^1cSnFr9;{1!8EKMicmDLV zsRX&z-*OeKOG%GgXE|V{Zh-UC`5FR;{sZ5iX$zyVnK74X+!P?{kMTgNozMG@W9^(rE&g@YkFd>3l|&*H>*adKB`SO{pioEM%CqQ>pub zVJ~~ND>JvtwT6qTFTenY?6pTfFMF5h?_SUao5@ktcnudn${wCMY3D0+bM7@Zo|Zf9 z=f?PhgZeXo4ilYi_8yjViE3XNk+87=$H&Lz6%W8Z#h5Z}kM%id7(ve~+Xa@^M?ziH zs(jYnptGcUj>l3XtZaP$@G`yQMkM&QS2QbG+v7BrFrAl-(){P9#q^-Z4FY9fvD4}! zG{0$j@LjUhkdd#spbtWR1B(|+pL!^9e;sK_SV$hb0HO#MM!$%#IF;%?eHp(Mo<`a0 zA5C+7PHjRm?Ebz#w?OwC;_3QTSQx`w%6Q`LKyA^~ z>sExqKu|&3WC%maA4K!Kvrv2oVq!tREHJu%%L#n@U(t~Mn@;{+>H0@J|E6^PBY*#h z_}_K%|HA}6S?}&|=kU}1X*v;XJ6U4nU<*BW{Hm->(yhG+YCqk5H%g?RQ0Cfxp3_f(mq+VabxGHUh{ zR-S^ikf668-!k~UYfqkE%?R!V+c@l)T?<^BO{#)1?Mts=_zTMqTZCIXjv>^s#S@o0 z9aV+4i@jE~%u#T*OGzx!9JW`7-CAna zZn-I9slL=^-a%;kEq>tE$UI19S^`>6EKfl%nfIx&TfqySa>?+8J1d)r_kowmZ>F5O z*E8d~Ww{is;I1ZK;FhE!-L;eqq|Z1%`g7cGL+`uBbGlgWxZG-0j}QC`VEEInF2CwP z9w(v=?IfnQ?OPTtxO1o2kD!16^6bYC5_H-6V8#$fDrQ0vaJ3#qQTHmX8~^?enLS*n$Sk0zuL zGJxs(SL{N~#s29Gr?0oU+SQkpBr{b4))CIW(4#2v%3(FNVh)kd9hsX)%!8e4$PCRAPD@#3hvF@xj_2HY?Q5VNofy?~Iqz zwlIq9+XdF7hW#&2EJKmB$)6QzC5 zqws5;6<7ezYWIn2MDUfTzUNj)wH@cirat);hWOt3DjOTFm2#lUrI{yqX?GrkZcLQ4 zMJ1->E??K7MZ2yH1qUmYT3#>tin}1d2~f->pSkvR70$l-;Y{|l)-Yvo%J^KhlO>v~ z%8B=i%Cl?I^vXmDn8a7tF_I4p9d5I!2mysLMBSCylFBZ`e5cQ~O}UJ5cR5|Gf=_Ht z&vz?qYjVOzDZ;)zq+V*a^Vb~7N7@Ey!5*9E()Wnb=IBjqe7wOUt7!T49p@FbX9U-$ z%N>Ja9Cp7?b|_KukIaP)i@MLx0As6#fkxY^`4|UtoSBw-&f8h2+owh!trTn~gR7E< z9->bUzYSAHCxX&arGhrvhi#w(8MlH+;=Yi%P8I^c?h=Oe$^T|L9TjDfvBKyKni=(0 z*o5Oa z68B% zuTS6m+~!xYw$-XNYtAvpm{ld(h@`_upflbB9bx-Cu8Y&}u1)$ELLhXZU>iP}9_;V= z8TUGwXjQFGf}8~{6d{viw%Yx-)G`P^s)e>REvWu9TvJi1=j+d`EU4-u3;KYP!8bQk zs$zfan=^dAXbR_EKuO6u%&f_hVm<+D%K_fymMeYrJrA=Sli39DE>=xf+u4bU z&bJ}5ZaL*xuF~$DiW%R0x_zqPKi&EC+|T~zAI$dOK!z83loQ!17pt|2p5`lV-_th- z2gSc<{yM}-M<=I&!A1;yKm!#w`6tXvSd<;O^SL30NSp_X!Du4o`#=6DPF&2xgBJY1 zao;4%muhmVofrI~yXCZQe(P@0!A9viQ$e4$RGe*Z%!22}MSaPj9OJ zj6_)2zZ%s4++)~(+jwD0Bg8wum=69FX(g_JXo2*1`XF@0Fm7FmhN<1q^&Yh>*VE@4 zxcaEohvnM}L?4{N?FSQ?c7cd-XZo%xj8y_*>pLHUDbD5wp_>lpBV&50YW0RiNL6I_ z5(YDE1-aOY$a3U|v>WcJOkVboG!pF~)-CEYt;3qO&Qu5Z6{y!P)$M!sl48<$ZIMwU z3a?f?8K`YltI*-q1(EgzHu#b&ACf56Q1Wf-e?og?StjU20(Zd|H9qzIlsB``oJ7Zd zrK*fUOpakg-hjq{_IFCzRtdyE0tZ+vhecE-vWAKpX6@Ylc$+lJ`Pi^RXZn{;iPuhF z7H)~!R{sDM48MGcW04#Zc5f=jIh|%p^>|&!7F7vygKoL65RMlRw9WaByO;H?*%=#( z*_X+VWjTB)IiyVbWf$yELS~|Vvwqq=!km@MUAC5v&kg-*e(Y#y^uW-(?~IXdfcsf5;a28lTtj((<>eRV4a-D#zo15&3O||G|JoK2-xwq#DqMGiL`seWm``;v< zML%5H0{nF36*z5RYxm0ciVP`!x2*(=HH3JL80MMXaRIAr;JG`Z%D;UsUadv3RdQ;1 zP3yJXS<6VWTUDx#zutD1od~$K|1ouHh?kjE&_0e}6sEM#X5n4>W|Y5WM>$Tb1uC6x zF+wUF-ZeUEDHcnms;rf)PaD4>_!_Kq^m}zyRx;&4-iiVs& z*BGvAe49*{1Gbq`P9?xjR_whu8Cc~D0~;FOcQj?Xl>WztxCMH7c`p`pPwIFiOU@bw zN+{Opret|{dQQQ*qMdiDcdQ5PFO#+)-U)nu^MyRpfybgijGPcB#1XwK5V-b=V*JQF zJHDSWl}^b=JZUgM6t5Ff$T-NjLAvCNVeDzl>t&^0oH+20(0A~wlA*m{PN+2Yy8 zz&{eI6qie%cEgbq-L?r+W%R$)ZFpK9TB@v61jRhWGw~{S?p+^5eowA*=IcM+p*q!Y zX*YvvfnG$dcM?dc+HG|Y85_%pnURA2vN8%YLAYr)M?9zbAH_DuBNLwODx&&QZp~2k zT264g!SDHgGHG_TzBRr~+puI*M$r9m;DunU8Txg@fqs~KYiAFrdo}`QsjXpgg6%{mU2-unyKwv3~Sa^o1cd0+RZc>15dUFE_eEPtRlw;`crEeV^UU4B}zxQ z3Dm|T^F1XQ*Md-l_MJ@kUCL#)YQBLuZ}0~y1^aNpJ9c(*Ui%8Z1sGc52pG^Ra%Qf# zw9jatFjY2Cy?V$?Ta!Xs2szsiUiWue`=`C}d(sNOR)SWB9j!FnkqtL^uZvV8>G(+1 zaMI$@sr`F9Uk0M-^4%-6k?2ix)jHhpcZJGsM@DdEw7f7PtUu4S>m-f%e_q$JdWIZY z7mjFfwp-x!=eTf{PhprYz>U%UwtaFUc~_sN&WO1W>>mBq;uAnjS-yU3t-tc0Dk|Q+ zpFXbQ!uvpmUKp$5MC}+!0YQmQSqgaxx4S5Ye*3XyI3}4;R6^S|2(in^;bF<8n&p32 zPyxv02NzIGxR~&wO?C*#pRA1q%h09DVDzYc=Vit&k({SOs69I}CSX&0r(>27N2)`~ z%4xNokp!RWZ>6ZN!9^S8t%Z?0I8H(P&IJ?cLz{xLi1d=fHYf_iGczqvob9OL*04BL z6PwWnW1^|AAg!~Se%wRXTK+WxZ?DOabwPl+MEnnI98^8&GQQ(TK4^@4TCMnh#aw60 zmfEcvfH}wsKO49Cpkh7qA0fS351+;tvHDioz1ZA*f?j>xzbqiM7;IqWFy4K1`37n? z{mdrW5}k(b9v8fI<-2gObF~E!^F??=q+~M)w_=-xo$^O9DsgZ1I1MMLwiiv(ham{Y zT5;#9sh(mM^-xmB&0n0emeOLFo251JxQ+nVOK-Fs5>#<9cYEf(DXQ1G@e)r6!aUeQJdtya;W`qzms3HE*vtz(|wmI*Wi98kPn}MEPZc)Zld6H3|JIVx@!I@cS3&^2lbhx*NQevJD3i&H^ zUdy+VEnK=|zZcE5q^m_9kSV>}L*6w%jtpcDByE{@<*dmr=|ydw&l6uP=k?qRs-#SK z>*ksl&izvNN<~_n^IFRO1H9gxi!xHMBq7SY6`YA?)BTM>DrPFMd;v`<3;KSJb@=?ob%7*e#N0u+Nd>>6a5Xp71a- zCN!l|s2r5CfP66st*FgLD05(2VO+evz&_f(l%za<)m^^qiz}Su;%Fv3D%eR3a{|#g z^_U6y_Y(w1aq;;P=b_}zIZVLxDXeb3wT-nTQ@>XF;P4GqpsPxo@xvp zNcqpxe*dZkH~}Pl4ty>9@p*z|1uORE&b?+wF5$XZgq>Gi(#<`=N_4_I_?IGVC~blK zex+PT<F{V6G$h!7<4YX3G~Yj$tgW0GnDN9&f=8@M>~>W^(^0(c+-r? z8d##sCgzN^z8OuHDF-0D<5;sW^j!sOhyRMfp?=caUkgGXE=7`(+tg=1PWJ%9xDy=( z3TAf7$23$@rey;T7O37vGa9T77%r#odstaxEXHuAhpX+7s!eAaB3Xzp;8 zztkR$|3_rbLlkF*^!sxQxhHg#5CLXY>M z=+n8=I8?8E&w6I@-)rm*m=#lD;(2~0nULyBgc~y4Z5R!)y=R~FZ%kLoJz;~H1{`n9 zf16o|wdoE4mk*G<3QAXA5v#&C#aXE1*))ncwM-mq|3gors=7v5G8tO{WU99o-+e{O z_JsEla>ZS?)rQK#G8|~N=JRM|4DuF3n9{^%Hs4Y266tB|bq7>XRSI2@XW{=&aAyda zS;BIliQs3lV9qB;Jp%)|dAu)UZ_QJpYi}Rbt%eBGCQ45P%>DvfPy&udotgf4jT(>l zp_821e%5KZJDz57V+0jG1g65oqQngXG5lVHGbe0!9&JzC z$L74E*L?34lCGKJn;oIIhy(sY5imFIJ7T}M$F5W0@%|4^1X4|%{VVzVS2p+`Y2m+X zoa=T^4NLxK{+CgqChxZFk89(fPK+RmgCLlz$okJ$v|4QlVZ1=7kpBMMyu6m+T43-W zIH#VPN(0lzudmb}%_#(f{8xHg^t(w&-i8L5q5RFf;l8(i{M-6>9r~}i?EjnhP(zd= z{LS9~gKXX=(Z8#*Q9Eo1j?8F|_r|V_jW-UJ9!B`(1$165KPhkjhrNXJpceOwvd70^ zI~M0O0Zx{v>cU)GeeSn}Rll3%_K~YItNhzn{s5v8RJ~S5D(*Prev&%$tn_5)57f-D zNZ8giwyY4bP3FA0g--(;Zfu;8&il8|n(TLVB!;JjbvgD)SSuhNc0*zci^Xc=R(~Y~e1dSVcJ@|%jmtq4glW$RfRd8Z**G$}R^lh&VHD{0j7h`QWL z3}xXCAxV(KnSFi(%bjD@pKk=6etjz6SW;m$_LOK^sQdFd!dXJSIz&{Jkb1feTekyC zgoQ5EmC5M3Q96t_;Zt%eR}!9UzHXylxH{Y7g#wpghg!rPAC4NYA)TpJThYS+grKe3 zn}5d*qaE5bHCydQztgH`lKS|_bzdZEjBwvm16YUZIES@WSn!-pUPT9W>t0b zMEAE6tF%n!pGSG<*3gGnoiu5=ie#%F)#R7rT~%&~QyT9Chs&5KYwk7Fc~S7kS}_yU zxEu&Z(aX6BG6AaZV)V>sayG~W*MUE$=wGQcuGP@DoX5@uE7-czl_hbh{RuerLWG9P zFk)UnvLkDYN$>Lyf@M2H)$U}tRit>#2JCot5(~qCP>}n@3U;x%r+@j{gh?r+L9&;$ zn-Z2XETaDQcSfb=y0~JYvk!qXxAJ(y3*`rIJA{H1vPK=;2PB?r>A<@U{Fyo6tlM|g zp zi@qVM6t`2rXS7-w$AltyeERV1)}LQ{>84{&aeT!NP_wE=gwYu>G`fgUGLxK)Njq63 z3Pr2K*Aot<%3`F(k|4Pm2bC%3oIm&7R*n4@lUCiam)%9l>?YXt2<%et*xm8b2B zf1Y%{=BWiLiMLba>ib~P%n`*QpOGWA0hOvlM1u8s{zWN65$1IG?W`6HrOt*@0JNwD zC1={O)~av#D00lj2nt);4BuPvBh3=5XHu1@i zcKBp(Amuf|RM7l*u@-+_#*L7ysY;(wh*EjadY=+vp5uAML>(-mk-nkxj$M3G0|d9i z&n9WPCieT8IuC_i+usut_Yeli0|{F73_m7dzMdHh+__jb%Zi}Q`;~ppne1*wmw}Iz5ZO#^a(5A1X|?x!V&J_k=uL?a+XP~T zXB8#KgABw?uUr<6GtrUNvEmI3nhpF6R0x&+0B~?=+Y6=sl8DbDfp{~v?vLg|Hj0w@ z!i*W{hPErZJx21)b@Nw4eYnuh*Nl35s)w?Z5OzTYZ7FqlRiIv(g*I{XVfR#@R%TA zD&pTKKtjqbP->Av+Bv%ntgJvovGh@yK*%i^ktd{@P~_)P_4`G*CsMV3asQ1-B&{Zf zW_oL5`rK!$#%oOkkSPtUMMZncV7X|=!Wd;JoZZhm|Enavn4#=on5iDQyOe2n_n`93+4(H|}HsGD|KqC&Fz{n6TG8T=8l^MpmS z_ZR%VCI0NlQTvjmr=n@D>_pN(dYbs~huNDqtctqOXT!hV|I$e&Y#ysew@kh4_k~+? zR{m!OgK`BjUHvPbc*!0X*xa8v=f+b9XafluDV~bw8}Yp@dG!l;h})d~71*$tjr?#8 zhY{F4Zg7dXdTu<+00w7(gxQE1qbS7Idc zrTz%NTieN&Oa?g$-JkRR@MD?Gkv<11#}PoqPOv`a2;lM6?@wAkjJC>VP7YLkxAADj z^q_1{o&YYDq(*JEO*ua?%@}gHBdHo~_4?JMwrbq{&4TIX`%~&!DxVpIkkR6XN(Ywr zLtXcpMNh+7>opNa_Tom)RdhGz+V7KtnWCU*%D>1#oUP7mswdsJ+Tr1sIYcy}0I0FE zxZi+;jxHiGQR%mhi-9nD!fhW^OUM1Y?8jYHKi)13Wc|P3AbDE3j)(PH z*}y>JPGFN2?pmlL!gcP@KpF2}tTN2TRs2ub-d4~nq`h}_G<$-N&@3hT8_O?q|HaxX zKw$mpBe;D3|5pS09~A)g|55{7Px9#C(05elv+KUPkeomA4+u-C@=WDoGzPGCytrd3 zm>NpT)L!}?ueiEl?5qx4oKY^yO4tSwdB6&LoJlB$lLq{pPBO@)R{Ize@O?Vs<6B`= z{;vVoXyg(Jv~T>$>pn`D9e8sMxA~HPg?`#4Vg?_Jy~Fg z#D97&I0_`j<+Nf!W%8XUDV$M12f=!&A5w729m@!d4hp|M3L+g~11z`CBQ~O^Es3VQ zPWSEsU`ttQ%TjA^`_>kh#Q~2`@j9iAKaaL9&$e^b$y@=ov9|Tz<``#yNUH6~piq@T zzx%hSR_my%P}*mU8QWv(fjOq18n3`gq9dNk)9-}U$8bv3^BYIAqRkLDr4w~9y51(Q zxFGHz>?3mZ@t#?FJyW>%SMH2m@80w$eJu$#I|h|#JiztN4d;&Co34Rb*>|b;CvuE= zSY4IoOxe}OFN1s927qOtS1VN_Tn3a*K5_0<)x29nWP(O2=wzBsNO;}`69VV_m)JlX z>PNdS1iASGaUQblN#okI<_8?qH0X27b9S<|<4BfzVnZLft~hF)BcE&%X~FGpRU9%| zt>I7#G^rq31>4DtNQ?Cd(Q6VcxuFwC#^*;sgFJ%i)tI}N=Q;rkMpxxmHjgMG34Cn@ zlGm_+BC0YL!?)vRgd&cPXfWDfDlzzVIqU~a2fyGYIu^rYNb^aA0qf6&+fz3an9z8w zcEYE}hFq}+br*SJ0H5%@!yINqyze*yDgSKfA;5X(TNxoePikW$L(&!-B`e83V%qov z^I`p|Qk1~QuKR;S<7C(gjS`-$QjD&hY4h7blLV}53Sx$*sJdvfRG=_+I3XzA6+2X+ z7*OiOXeA!5i@uu5AB2TG2zPHqlW}sy@=!bF2%qovg|3`9G0zE@WD`! z_>Oe;r?1JgE3Cx)k5}7|3;oz}3@P`mRV)+!YdB`^vM)%$mfK@k!;B6~5!ER{pH+IXzA1ah6v23f^6{!*w6coW*!h_!&%Z6f!oT+!d zCY&az)?7_8ion(t<}H3I*bq*02)5_&+Gl&Q)TwG(xA7NIephX9<@|H=l)z7xhV$48 zUQ5s=d34-j=IqGUO%e8w@q_a);3hz8vj(0(TD1u`(b~B5OOHMjHYvan=Df`T2?{n` zi8cZK`$fJLjcpSStl!fP9HS8)_u#3X$Q@y0z#F@bW6UoQ$*{CZ`}anOwOoQaY2;K( z%$o95`@wr^Z&R((Fzg~XNjp&*DAC~HQ$@P6Yqex+cRJKUB3r%E*BmP+U#97wpSDB_ z%Csd4q~Y;8E{M)J&S(D&IJhe11%)vg2oHHtCY!VJKrB;<1)kb~LHk?;#On)fFaI z$>ID$*3{$l1sR>Yt75!-m-ME0SFU3VSm7(9Iag0?`OUmHm?0piJHV&|oqWp0%t1OT z0GRuz&S469^hRa6dPC3RAl&!WX#+z?Q|=&4m8?IZ6Z0*THL_Xu0yFNY(wina095A} zp|;ap9}odG{nS<;2b!7X_Dq70*+{g;*d?e{vTHv6*z`#qB7gX`nCXn85R@t3f(eI^ z(zn(fBx->m_AOkgLhBoXj*D8kiIx_CtQd@5pY~SI^T%XD*)F3# z$KB(krMoxy#X&MeGJDTCRjlkGR$M4;T4M|J*-b}(64fEm54yJyrhF>9J0#^i4+koY zW4PV#EJwc1_KIxg&t%G0#U0ECp|+1CY#dA7)d+veQSUFzNq1}UVukfx7ONZ15);r+ z?132E<+#vw%yz`zV_n^X9|=A-vWz6u(=)A)KhO!3i}G5yxkAN~d&aXAaE*Sc3doY| zKj863V`{N*(gJ1#KlS}&9&(}fQ$6swK3$5@nRO&BQVdna@ifQMwMiW=N`fK6OrLHQ zCtI%0Rmn)dXW$(Q#~r2SZ-!-35gd;v?p$9{ly!eP5mpn-mY-bSA-FFZBlfKrPQ&wt zIlulDT!zDyUdcvyPOqDx-`fJ3Z@>Kma9=(ZL=*Dir7gnjO=OP(mw2zY15t_=7mZ9z z;xjWv8doODY##MIq}W7!3=Uk67VurZm6~(PWPdJF>x625aLFr>mSe7eb(U?Py*gj$ zRi_cPB9wo+ocSPHt6c6H#xj;?4)mR&pk}Ek&(1=_!onUO6M;VW!+-mB*KW1aa$_r(!nl*u z3H1-nKn<}5*X6<+^yibLm(*YW1u*`vA%y=kU;)C~55@3dVu4qi{!^IejyaN|h zF(>@@<8d!}(*M`%>i((I1DCe`#asW;Ai_chIuAyM33v&3@@V!l#Thvi+La?C;{6V6 z(V>K36`5nRyrsSUM3Jzg5k%V_dMO-w$qlKubyxuHRqe%OYEYIMAuxb08amV1(y9^p z2OtiK(t;<-l5tS&c3_&7oo_%K8&;Lmbm^}M~GH@?}_UaB`+368Vn{g zvWk>@@b4~f_Sb+cnZ41D({G3Q8mdSyFFA$1Eh9i)9&Fxi z$DR64t|RE9-Bq9Um3^;p6oQ{=L! z%4MKOwhty5uGH)^CxY#x&E&+4zZ7WnFOUA{X2t{u1aZa?v6BA32pLQW1O{8{iRsZZ zc-H?2(kJ5-gi^%@WI$qfZEglgOYuvRzfZAP-#ol*Rd#D_ip@fk5BUAB!5b#&Jo|n# z#Jc)o06Qman5MBrSaneJmzko5*kig_Dr9q+;*n|x!sl8(?sixVEX^csC%R2NIWmr__E++{WnI+HEn|`da09F?RK*(gaL5%3PjMOcuB9vYJd`;(6bjXP;-} zs@)hg1!b=vk81{5XY#pZ*G(%I$tcjKIBXtYe3^FKOOJ$$7Rytt@WB0_1`GMIFK{fQ z6?Sjc`(Qs!%*smZw9{xBGG&0!ETbWU35#&u%ZebymBD0g)hgY!IFQW5!r4mZVEydg zK=-XZiz@shxGI6oVzRZk@_(`%oi`^qH7SAc#pD3@&<;nN_H6T#p{od?f<{%skhVvH zS`**lp`_tdgyg*2$?7(RatMgUn9d=pK&pFcsB@A;%`jdC%pi!n#_Z9KEadFB5 zcQqUIjfCy1X+W=oNb9@pk}L3i_F}d2(aB6)TgJ86d`?1{i=W=tzX$FWPsVr1f*|oF zO_5RS4B2$OHidz>0yKqse`RDdXuUWPefuT4(}@Zs1p4?zD|4cG+(u?SULqUS`xYxs zHdSIW(pm@~q->MzjI3g-kS6VjG_9fx*5BkCNJ7M>yD=s<*CDhGrca{oU5t^}}<+5>Px-MCGayFn@0O z6H2gLcPByrhT6>UM&g5FhsJ34)rFA<<`1c(6t`O2m1XzQ`}u2Pp16InVV9^2t{pEv zy&Rudb0)8mkxM8wj%opDq%d{nfD~VuJYXafuKI7CC>ii%CeNu+g#Sdu2pwPP0F;{O zEYfYLdUU`t_xVg?$P)K&k*j`=PgwuVyhEK9*XqkLx}e#9&w+7-nl}eNy&lZOsgPV8 zcq1&}JLPJ=TibzhxIv>&)enKg^a6%IR`H3?pTD`r!p4vae5D%vQhKADw^5k-f>9fk!82zS2&QB>=D(dD>!5Zlf z%7n<=xyOkrr=Ds;eE;8YdG21>TO*#w-jDlwx+(f z68b&wJV0U(TUtQ4aXgDCV**9TIW14Pr*&ZRi>T3$5o=v;iKps~^79s}4HT@@HIB?< z%LF%1Xw}BPhe-72c#P((rvo`9_YPvhLvBOWb`)6`-@cmfqU6bv8)h<`1<~yXGgWxE zF}P2$}L_VFz29Fo)Eh@+xUBUGHyp5nrz@I1x4#~h5r6c!M8&wR&AxabI zZ1P-Llx&8rw|xnjR=rjN-9NFj4N>)KjK6lVggeST;oNKRRWKoLW&nJFmL2eBAU)RZpEUC@_+Ye_)^;I|tXoe5}X@Xs^a+O_myRK;f6h;?hE#Aj2{i85bWoS5E0h5 zlJK_~Cfs;3sAIjN7BIG4m$FV$ue{DOh-~H18$TqU@yWH^d>~O@{bi$~VlDj|$G~;+ z&yv&9O1TQT2&s5j8xI=_W9rR`%H@MIE29CWrMMaSqyTw*DYl4%-OA=dNV#$t*5cWZ z(~Ln5PAjfs%jW`$t_{0K%gfllG(-@skw<;`czKv~VG*hbHeL0lG|fj+6pX7<$%|0B z^Q}?gr;_y~#H_v&wDY3T_IBnFwJMAz&Y>~I4xuL?+u}Z*VLyb4g+U!MEIU{G?$J?9 zbk(qLqY#hPfowBR$RF53LHi1SRj z4)*4c7`1KL0;{%7Vw@^9{X-QUfr4=Fh@vw-nr${irFX_7IZL=uvWZ||fJx9~IsARt zLKokPj@~+GC9^jDf_@`p(P&`yX0Avv+S6Ch=A7i#t2thm6)AkaGQ<;T!oP7ARPD&3 z7>Hu;bmEnqBh_m*8St>n2fKb9l`~!X_+L0R)FZCB9l+~!je!8)G=JZiZ1#`&aNShgwp0rF zdA%?H4vuGnrg5)(;7uyBhg0i0kF^jKZ--UgTm9KGN7Ys19yqFX1yY7l51QtDvRzve z2bhH$W5g1;ok@-gW%XKzVP8zV(;mdo`Tef>tTG%+1=~ElIM>Fqhce7zqM=8pwr_-; z?rM4uIF}ACayI5I$nb6P8n5;4jt@ZT`#~>kqHeVskXG!b*9+VPUfXA7Bgw+Zm#9=g$@nQ_F5-S&&rZDF`*nDrg2(289QviB7~27p-R3IVzpW@Ak}%! zOadhOILY~Fna)^>re*#PPt!$GL3u^yLjwB^vm=KC#Z4_O>+9=&Su25^YvYo{|EdKj z;wE9a=twEoYT6-cf)eW^U37i#02=5iW^;LD65vE;O1lB?zT` zR5L5;seDC-pdWR07(F7QX`tb^w(S3y}~D7AzFxtZC`~H#$veF zFaFs{jOq9Jva{}&66PO<;`%Q4e=qg^w-vwwqP*9MH4?SCh}ZZRb6^R6>5;PqaH z$mCN#MrUbesZp9LPTu>Dnddl}dZw&*lFaLZ=m|^HWP(~mM zTMK`5@v#HQBlr3B*HMK9x=4Z1q5~|+9URdYe2n_VbII8^0?L2-2BvT0K!cxXr}V|u zJ2&2A+y9Ut`6pikzv4A!QXh|uQ$dL-`e*zg)yQ9J8W)Ek+TLOIEARZFXu&-4aOE;1 z!TKJXId>yrf4Z!rd#)8E=ATT6$Q%z^0}MnOv-SI91+5r$5`RumqLEGi{c-R|<3J-~ zUya`WpbdJx=P*WptT>@TX1=Wr)%Q$$q55_VY(zfLG~4D={^+mw@*1}s4Gxj@rnn$w zY*i15JIirxWN|KJA=aXNM4#$FxQwQI%G0sj7Q$oQE;-8fBya3k)_<<-|JHjk z24NuZEN;T7Y+`+KthCHmRe5fB6a8w8brM^o~e3-D8e{p_b_j5Pta{Z*R* z(dzPONudkj)*PqFe}>}IY1VkPpkYeXk9KJ}`J;TMwe|klJ(~$v3qe2or*y^KDn1uU z`%h1ogl9etNoJ9J74z*UrIEfrh?3gdt8s=u5iX7#(?~C*#AZ3hm&`;=c`r@pWun}& z#06Pvb*0+MeQ_Imvs-^YqAq#BIJPnk9r@nG)jK5#w}SoN3KhL%FMAW2;rr-0KX@Tk3FUT37n;U=j@J#+PL9fLeYtbw;kK35|;e+70sK>Z~Ov`YNDVB_3(ICy- zS+EB~>6ghcgR3PnT$N4d=oqt)zaoEJuf@u>nqRrK{;HHYd}h(CL98M6jK70%9W7ts zK`vM83sM%BRB;3&k2vwf*GHV8#YDWGv3RA9l^xClVD}5WLCn|#m|X5MKeHj2@T%

Y^^(*eiD{sbfJ%(&*CDpE(Ud6wW` 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 diff --git a/docs/en/docs/img/tutorial/sql-databases/image02.png b/docs/en/docs/img/tutorial/sql-databases/image02.png index ee59fc9398a4607872d7aae1d439fdb71c0a706c..7bcad83783af805276cb25bde4d3a4b384f92600 100644 GIT binary patch literal 69197 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 literal 83482 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

```console -$ pip install sqlalchemy - +$ pip install sqlmodel ---> 100% ```
-## Create the SQLAlchemy parts - -Let's refer to the file `sql_app/database.py`. +## Create the App with a Single Model -### Import the SQLAlchemy parts +We'll create the simplest first version of the app with a single **SQLModel** model first. -```Python hl_lines="1-3" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -### Create a database URL for SQLAlchemy - -```Python hl_lines="5-6" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -In this example, we are "connecting" to a SQLite database (opening a file with the SQLite database). - -The file will be located at the same directory in the file `sql_app.db`. - -That's why the last part is `./sql_app.db`. - -If you were using a **PostgreSQL** database instead, you would just have to uncomment the line: - -```Python -SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" -``` +Later we'll improve it increasing security and versatility with **multiple models** below. 🤓 -...and adapt it with your database data and credentials (equivalently for MySQL, MariaDB or any other). +### Create Models -/// tip - -This is the main line that you would have to modify if you wanted to use a different database. - -/// - -### Create the SQLAlchemy `engine` +Import `SQLModel` and create a database model: -The first step is to create a SQLAlchemy "engine". +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[1:11] hl[7:11] *} -We will later use this `engine` in other places. +The `Hero` class is very similar to a Pydantic model (in fact, underneath, it actually *is a Pydantic model*). -```Python hl_lines="8-10" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` +There are a few differences: -#### Note +* `table=True` tells SQLModel that this is a *table model*, it should represent a **table** in the SQL database, it's not just a *data model* (as would be any other regular Pydantic class). -The argument: +* `Field(primary_key=True)` tells SQLModel that the `id` is the **primary key** in the SQL database (you can learn more about SQL primary keys in the SQLModel docs). -```Python -connect_args={"check_same_thread": False} -``` + By having the type as `int | None`, SQLModel will know that this column should be an `INTEGER` in the SQL database and that it should be `NULLABLE`. -...is needed only for `SQLite`. It's not needed for other databases. +* `Field(index=True)` tells SQLModel that it should create a **SQL index** for this column, that would allow faster lookups in the database when reading data filtered by this column. -/// info | "Technical Details" + SQLModel will know that something declared as `str` will be a SQL column of type `TEXT` (or `VARCHAR`, depending on the database). -By default SQLite will only allow one thread to communicate with it, assuming that each thread would handle an independent request. +### Create an Engine -This is to prevent accidentally sharing the same connection for different things (for different requests). +A SQLModel `engine` (underneath it's actually a SQLAlchemy `engine`) is what **holds the connections** to the database. -But in FastAPI, using normal functions (`def`) more than one thread could interact with the database for the same request, so we need to make SQLite know that it should allow that with `connect_args={"check_same_thread": False}`. +You would have **one single `engine` object** for all your code to connect to the same database. -Also, we will make sure each request gets its own database connection session in a dependency, so there's no need for that default mechanism. +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[14:18] hl[14:15,17:18] *} -/// +Using `check_same_thread=False` allows FastAPI to use the same SQLite database in different threads. This is necessary as **one single request** could use **more than one thread** (for example in dependencies). -### Create a `SessionLocal` class +Don't worry, with the way the code is structured, we'll make sure we use **a single SQLModel *session* per request** later, this is actually what the `check_same_thread` is trying to achieve. -Each instance of the `SessionLocal` class will be a database session. The class itself is not a database session yet. +### Create the Tables -But once we create an instance of the `SessionLocal` class, this instance will be the actual database session. +We then add a function that uses `SQLModel.metadata.create_all(engine)` to **create the tables** for all the *table models*. -We name it `SessionLocal` to distinguish it from the `Session` we are importing from SQLAlchemy. +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[21:22] hl[21:22] *} -We will use `Session` (the one imported from SQLAlchemy) later. +### Create a Session Dependency -To create the `SessionLocal` class, use the function `sessionmaker`: - -```Python hl_lines="11" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` +A **`Session`** is what stores the **objects in memory** and keeps track of any changes needed in the data, then it **uses the `engine`** to communicate with the database. -### Create a `Base` class +We will create a FastAPI **dependency** with `yield` that will provide a new `Session` for each request. This is what ensures that we use a single session per request. 🤓 -Now we will use the function `declarative_base()` that returns a class. +Then we create an `Annotated` dependency `SessionDep` to simplify the rest of the code that will use this dependency. -Later we will inherit from this class to create each of the database models or classes (the ORM models): +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[25:30] hl[25:27,30] *} -```Python hl_lines="13" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` +### Create Database Tables on Startup -## Create the database models +We will create the database tables when the application starts. -Let's now see the file `sql_app/models.py`. +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[32:37] hl[35:37] *} -### Create SQLAlchemy models from the `Base` class +Here we create the tables on an application startup event. -We will use this `Base` class we created before to create the SQLAlchemy models. +For production you would probably use a migration script that runs before you start your app. 🤓 /// tip -SQLAlchemy uses the term "**model**" to refer to these classes and instances that interact with the database. - -But Pydantic also uses the term "**model**" to refer to something different, the data validation, conversion, and documentation classes and instances. +SQLModel will have migration utilities wrapping Alembic, but for now, you can use Alembic directly. /// -Import `Base` from `database` (the file `database.py` from above). - -Create classes that inherit from it. - -These classes are the SQLAlchemy models. - -```Python hl_lines="4 7-8 18-19" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -The `__tablename__` attribute tells SQLAlchemy the name of the table to use in the database for each of these models. - -### Create model attributes/columns - -Now create all the model (class) attributes. - -Each of these attributes represents a column in its corresponding database table. +### Create a Hero -We use `Column` from SQLAlchemy as the default value. +Because each SQLModel model is also a Pydantic model, you can use it in the same **type annotations** that you could use Pydantic models. -And we pass a SQLAlchemy class "type", as `Integer`, `String`, and `Boolean`, that defines the type in the database, as an argument. +For example, if you declare a parameter of type `Hero`, it will be read from the **JSON body**. -```Python hl_lines="1 10-13 21-24" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -### Create the relationships - -Now create the relationships. - -For this, we use `relationship` provided by SQLAlchemy ORM. - -This will become, more or less, a "magic" attribute that will contain the values from other tables related to this one. +The same way, you can declare it as the function's **return type**, and then the shape of the data will show up in the automatic API docs UI. -```Python hl_lines="2 15 26" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -When accessing the attribute `items` in a `User`, as in `my_user.items`, it will have a list of `Item` SQLAlchemy models (from the `items` table) that have a foreign key pointing to this record in the `users` table. +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *} -When you access `my_user.items`, SQLAlchemy will actually go and fetch the items from the database in the `items` table and populate them here. + -And when accessing the attribute `owner` in an `Item`, it will contain a `User` SQLAlchemy model from the `users` table. It will use the `owner_id` attribute/column with its foreign key to know which record to get from the `users` table. +Here we use the `SessionDep` dependency (a `Session`) to add the new `Hero` to the `Session` instance, commit the changes to the database, refresh the data in the `hero`, and then return it. -## Create the Pydantic models +### Read Heroes -Now let's check the file `sql_app/schemas.py`. +We can **read** `Hero`s from the database using a `select()`. We can include a `limit` and `offset` to paginate the results. -/// tip +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[48:55] hl[51:52,54] *} -To avoid confusion between the SQLAlchemy *models* and the Pydantic *models*, we will have the file `models.py` with the SQLAlchemy models, and the file `schemas.py` with the Pydantic models. +### Read One Hero -These Pydantic models define more or less a "schema" (a valid data shape). +We can **read** a single `Hero`. -So this will help us avoiding confusion while using both. - -/// +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[58:63] hl[60] *} -### Create initial Pydantic *models* / schemas +### Delete a Hero -Create an `ItemBase` and `UserBase` Pydantic *models* (or let's say "schemas") to have common attributes while creating or reading data. +We can also **delete** a `Hero`. -And create an `ItemCreate` and `UserCreate` that inherit from them (so they will have the same attributes), plus any additional data (attributes) needed for creation. +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[66:73] hl[71] *} -So, the user will also have a `password` when creating it. +### Run the App -But for security, the `password` won't be in other Pydantic *models*, for example, it won't be sent from the API when reading a user. +You can run the app: -//// tab | Python 3.10+ - -```Python hl_lines="1 4-6 9-10 21-22 25-26" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -#### SQLAlchemy style and Pydantic style - -Notice that SQLAlchemy *models* define attributes using `=`, and pass the type as a parameter to `Column`, like in: - -```Python -name = Column(String) -``` +
-while Pydantic *models* declare the types using `:`, the new type annotation syntax/type hints: +```console +$ fastapi dev main.py -```Python -name: str +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` -Keep these in mind, so you don't get confused when using `=` and `:` with them. - -### Create Pydantic *models* / schemas for reading / returning - -Now create Pydantic *models* (schemas) that will be used when reading data, when returning it from the API. - -For example, before creating an item, we don't know what will be the ID assigned to it, but when reading it (when returning it from the API) we will already know its ID. +
-The same way, when reading a user, we can now declare that `items` will contain the items that belong to this user. +Then go to the `/docs` UI, you will see that **FastAPI** is using these **models** to **document** the API, and it will use them to **serialize** and **validate** the data too. -Not only the IDs of those items, but all the data that we defined in the Pydantic *model* for reading items: `Item`. +
+ +
-//// tab | Python 3.10+ +## Update the App with Multiple Models -```Python hl_lines="13-15 29-32" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` +Now let's **refactor** this app a bit to increase **security** and **versatility**. -//// +If you check the previous app, in the UI you can see that, up to now, it lets the client decide the `id` of the `Hero` to create. 😱 -//// tab | Python 3.9+ +We shouldn't let that happen, they could overwrite an `id` we already have assigned in the DB. Deciding the `id` should be done by the **backend** or the **database**, **not by the client**. -```Python hl_lines="15-17 31-34" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` +Additionally, we create a `secret_name` for the hero, but so far, we are returning it everywhere, that's not very **secret**... 😅 -//// +We'll fix these things by adding a few **extra models**. Here's where SQLModel will shine. ✨ -//// tab | Python 3.8+ +### Create Multiple Models -```Python hl_lines="15-17 31-34" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` +In **SQLModel**, any model class that has `table=True` is a **table model**. -//// +And any model class that doesn't have `table=True` is a **data model**, these ones are actually just Pydantic models (with a couple of small extra features). 🤓 -/// tip +With SQLModel, we can use **inheritance** to **avoid duplicating** all the fields in all the cases. -Notice that the `User`, the Pydantic *model* that will be used when reading a user (returning it from the API) doesn't include the `password`. +#### `HeroBase` - the base class -/// +Let's start with a `HeroBase` model that has all the **fields that are shared** by all the models: -### Use Pydantic's `orm_mode` +* `name` +* `age` -Now, in the Pydantic *models* for reading, `Item` and `User`, add an internal `Config` class. +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:9] hl[7:9] *} -This `Config` class is used to provide configurations to Pydantic. +#### `Hero` - the *table model* -In the `Config` class, set the attribute `orm_mode = True`. +Then let's create `Hero`, the actual *table model*, with the **extra fields** that are not always in the other models: -//// tab | Python 3.10+ +* `id` +* `secret_name` -```Python hl_lines="13 17-18 29 34-35" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` +Because `Hero` inherits form `HeroBase`, it **also** has the **fields** declared in `HeroBase`, so all the fields for `Hero` are: -//// +* `id` +* `name` +* `age` +* `secret_name` -//// tab | Python 3.9+ +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:14] hl[12:14] *} -```Python hl_lines="15 19-20 31 36-37" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` +#### `HeroPublic` - the public *data model* -//// +Next, we create a `HeroPublic` model, this is the one that will be **returned** to the clients of the API. -//// tab | Python 3.8+ +It has the same fields as `HeroBase`, so it won't include `secret_name`. -```Python hl_lines="15 19-20 31 36-37" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` +Finally, the identity of our heroes is protected! 🥷 -//// +It also re-declares `id: int`. By doing this, we are making a **contract** with the API clients, so that they can always expect the `id` to be there and to be an `int` (it will never be `None`). /// tip -Notice it's assigning a value with `=`, like: - -`orm_mode = True` +Having the return model ensure that a value is always available and always `int` (not `None`) is very useful for the API clients, they can write much simpler code having this certainty. -It doesn't use `:` as for the type declarations before. - -This is setting a config value, not declaring a type. +Also, **automatically generated clients** will have simpler interfaces, so that the developers communicating with your API can have a much better time working with your API. 😎 /// -Pydantic's `orm_mode` will tell the Pydantic *model* to read the data even if it is not a `dict`, but an ORM model (or any other arbitrary object with attributes). - -This way, instead of only trying to get the `id` value from a `dict`, as in: - -```Python -id = data["id"] -``` - -it will also try to get it from an attribute, as in: - -```Python -id = data.id -``` +All the fields in `HeroPublic` are the same as in `HeroBase`, with `id` declared as `int` (not `None`): -And with this, the Pydantic *model* is compatible with ORMs, and you can just declare it in the `response_model` argument in your *path operations*. +* `id` +* `name` +* `age` +* `secret_name` -You will be able to return a database model and it will read the data from it. +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *} -#### Technical Details about ORM mode +#### `HeroCreate` - the *data model* to create a hero -SQLAlchemy and many others are by default "lazy loading". +Now we create a `HeroCreate` model, this is the one that will **validate** the data from the clients. -That means, for example, that they don't fetch the data for relationships from the database unless you try to access the attribute that would contain that data. +It has the same fields as `HeroBase`, and it also has `secret_name`. -For example, accessing the attribute `items`: - -```Python -current_user.items -``` - -would make SQLAlchemy go to the `items` table and get the items for this user, but not before. - -Without `orm_mode`, if you returned a SQLAlchemy model from your *path operation*, it wouldn't include the relationship data. - -Even if you declared those relationships in your Pydantic models. - -But with ORM mode, as Pydantic itself will try to access the data it needs from attributes (instead of assuming a `dict`), you can declare the specific data you want to return and it will be able to go and get it, even from ORMs. - -## CRUD utils - -Now let's see the file `sql_app/crud.py`. - -In this file we will have reusable functions to interact with the data in the database. - -**CRUD** comes from: **C**reate, **R**ead, **U**pdate, and **D**elete. - -...although in this example we are only creating and reading. - -### Read data - -Import `Session` from `sqlalchemy.orm`, this will allow you to declare the type of the `db` parameters and have better type checks and completion in your functions. - -Import `models` (the SQLAlchemy models) and `schemas` (the Pydantic *models* / schemas). - -Create utility functions to: - -* Read a single user by ID and by email. -* Read multiple users. -* Read multiple items. - -```Python hl_lines="1 3 6-7 10-11 14-15 27-28" -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` +Now, when the clients **create a new hero**, they will send the `secret_name`, it will be stored in the database, but those secret names won't be returned in the API to the clients. /// tip -By creating functions that are only dedicated to interacting with the database (get a user or an item) independent of your *path operation function*, you can more easily reuse them in multiple parts and also add unit tests for them. - -/// +This is how you would handle **passwords**. Receive them, but don't return them in the API. -### Create data - -Now create utility functions to create data. - -The steps are: - -* Create a SQLAlchemy model *instance* with your data. -* `add` that instance object to your database session. -* `commit` the changes to the database (so that they are saved). -* `refresh` your instance (so that it contains any new data from the database, like the generated ID). - -```Python hl_lines="18-24 31-36" -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` - -/// info - -In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. - -The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. +You would also **hash** the values of the passwords before storing them, **never store them in plain text**. /// -/// tip +The fields of `HeroCreate` are: -The SQLAlchemy model for `User` contains a `hashed_password` that should contain a secure hashed version of the password. +* `name` +* `age` +* `secret_name` -But as what the API client provides is the original password, you need to extract it and generate the hashed password in your application. +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:22] hl[21:22] *} -And then pass the `hashed_password` argument with the value to save. +#### `HeroUpdate` - the *data model* to update a hero -/// +We didn't have a way to **update a hero** in the previous version of the app, but now with **multiple models**, we can do it. 🎉 -/// warning +The `HeroUpdate` *data model* is somewhat special, it has **all the same fields** that would be needed to create a new hero, but all the fields are **optional** (they all have a default value). This way, when you update a hero, you can send just the fields that you want to update. -This example is not secure, the password is not hashed. +Because all the **fields actually change** (the type now includes `None` and they now have a default value of `None`), we need to **re-declare** them. -In a real life application you would need to hash the password and never save them in plaintext. +We don't really need to inherit from `HeroBase` because we are re-declaring all the fields. I'll leave it inheriting just for consistency, but this is not necessary. It's more a matter of personal taste. 🤷 -For more details, go back to the Security section in the tutorial. +The fields of `HeroUpdate` are: -Here we are focusing only on the tools and mechanics of databases. +* `name` +* `age` +* `secret_name` -/// - -/// tip - -Instead of passing each of the keyword arguments to `Item` and reading each one of them from the Pydantic *model*, we are generating a `dict` with the Pydantic *model*'s data with: - -`item.dict()` +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:28] hl[25:28] *} -and then we are passing the `dict`'s key-value pairs as the keyword arguments to the SQLAlchemy `Item`, with: +### Create with `HeroCreate` and return a `HeroPublic` -`Item(**item.dict())` - -And then we pass the extra keyword argument `owner_id` that is not provided by the Pydantic *model*, with: - -`Item(**item.dict(), owner_id=user_id)` - -/// +Now that we have **multiple models**, we can update the parts of the app that use them. -## Main **FastAPI** app +We receive in the request a `HeroCreate` *data model*, and from it, we create a `Hero` *table model*. -And now in the file `sql_app/main.py` let's integrate and use all the other parts we created before. +This new *table model* `Hero` will have the fields sent by the client, and will also have an `id` generated by the database. -### Create the database tables +Then we return the same *table model* `Hero` as is from the function. But as we declare the `response_model` with the `HeroPublic` *data model*, **FastAPI** will use `HeroPublic` to validate and serialize the data. -In a very simplistic way create the database tables: - -//// tab | Python 3.9+ - -```Python hl_lines="7" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -#### Alembic Note - -Normally you would probably initialize your database (create tables, etc) with Alembic. - -And you would also use Alembic for "migrations" (that's its main job). - -A "migration" is the set of steps needed whenever you change the structure of your SQLAlchemy models, add a new attribute, etc. to replicate those changes in the database, add a new column, a new table, etc. - -You can find an example of Alembic in a FastAPI project in the [Full Stack FastAPI Template](../project-generation.md){.internal-link target=_blank}. Specifically in the `alembic` directory in the source code. - -### Create a dependency - -Now use the `SessionLocal` class we created in the `sql_app/database.py` file to create a dependency. - -We need to have an independent database session/connection (`SessionLocal`) per request, use the same session through all the request and then close it after the request is finished. - -And then a new session will be created for the next request. - -For that, we will create a new dependency with `yield`, as explained before in the section about [Dependencies with `yield`](dependencies/dependencies-with-yield.md){.internal-link target=_blank}. - -Our dependency will create a new SQLAlchemy `SessionLocal` that will be used in a single request, and then close it once the request is finished. - -//// tab | Python 3.9+ - -```Python hl_lines="13-18" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15-20" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -/// info - -We put the creation of the `SessionLocal()` and handling of the requests in a `try` block. - -And then we close it in the `finally` block. - -This way we make sure the database session is always closed after the request. Even if there was an exception while processing the request. - -But you can't raise another exception from the exit code (after `yield`). See more in [Dependencies with `yield` and `HTTPException`](dependencies/dependencies-with-yield.md#dependencies-with-yield-and-httpexception){.internal-link target=_blank} - -/// - -And then, when using the dependency in a *path operation function*, we declare it with the type `Session` we imported directly from SQLAlchemy. - -This will then give us better editor support inside the *path operation function*, because the editor will know that the `db` parameter is of type `Session`: - -//// tab | Python 3.9+ - -```Python hl_lines="22 30 36 45 51" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24 32 38 47 53" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -/// info | "Technical Details" - -The parameter `db` is actually of type `SessionLocal`, but this class (created with `sessionmaker()`) is a "proxy" of a SQLAlchemy `Session`, so, the editor doesn't really know what methods are provided. - -But by declaring the type as `Session`, the editor now can know the available methods (`.add()`, `.query()`, `.commit()`, etc) and can provide better support (like completion). The type declaration doesn't affect the actual object. - -/// - -### Create your **FastAPI** *path operations* - -Now, finally, here's the standard **FastAPI** *path operations* code. - -//// tab | Python 3.9+ - -```Python hl_lines="21-26 29-32 35-40 43-47 50-53" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23-28 31-34 37-42 45-49 52-55" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -We are creating the database session before each request in the dependency with `yield`, and then closing it afterwards. - -And then we can create the required dependency in the *path operation function*, to get that session directly. - -With that, we can just call `crud.get_user` directly from inside of the *path operation function* and use that session. - -/// tip - -Notice that the values you return are SQLAlchemy models, or lists of SQLAlchemy models. - -But as all the *path operations* have a `response_model` with Pydantic *models* / schemas using `orm_mode`, the data declared in your Pydantic models will be extracted from them and returned to the client, with all the normal filtering and validation. - -/// +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[56:62] hl[56:58] *} /// tip -Also notice that there are `response_models` that have standard Python types like `List[schemas.Item]`. - -But as the content/parameter of that `List` is a Pydantic *model* with `orm_mode`, the data will be retrieved and returned to the client as normally, without problems. - -/// - -### About `def` vs `async def` - -Here we are using SQLAlchemy code inside of the *path operation function* and in the dependency, and, in turn, it will go and communicate with an external database. - -That could potentially require some "waiting". - -But as SQLAlchemy doesn't have compatibility for using `await` directly, as would be with something like: - -```Python -user = await db.query(User).first() -``` - -...and instead we are using: - -```Python -user = db.query(User).first() -``` - -Then we should declare the *path operation functions* and the dependency without `async def`, just with a normal `def`, as: - -```Python hl_lines="2" -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - ... -``` - -/// info +Now we use `response_model=HeroPublic` instead of the **return type annotation** `-> HeroPublic` because the value that we are returning is actually *not* a `HeroPublic`. -If you need to connect to your relational database asynchronously, see [Async SQL (Relational) Databases](../how-to/async-sql-encode-databases.md){.internal-link target=_blank}. +If we had declared `-> HeroPublic`, your editor and linter would complain (rightfully so) that you are returning a `Hero` instead of a `HeroPublic`. -/// - -/// note | "Very Technical Details" - -If you are curious and have a deep technical knowledge, you can check the very technical details of how this `async def` vs `def` is handled in the [Async](../async.md#very-technical-details){.internal-link target=_blank} docs. +By declaring it in `response_model` we are telling **FastAPI** to do its thing, without interfering with the type annotations and the help from your editor and other tools. /// -## Migrations - -Because we are using SQLAlchemy directly and we don't require any kind of plug-in for it to work with **FastAPI**, we could integrate database migrations with Alembic directly. - -And as the code related to SQLAlchemy and the SQLAlchemy models lives in separate independent files, you would even be able to perform the migrations with Alembic without having to install FastAPI, Pydantic, or anything else. - -The same way, you would be able to use the same SQLAlchemy models and utilities in other parts of your code that are not related to **FastAPI**. - -For example, in a background task worker with Celery, RQ, or ARQ. - -## Review all the files - - Remember you should have a directory named `my_super_project` that contains a sub-directory called `sql_app`. - -`sql_app` should have the following files: - -* `sql_app/__init__.py`: is an empty file. - -* `sql_app/database.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -* `sql_app/models.py`: +### Read Heroes with `HeroPublic` -```Python -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -* `sql_app/schemas.py`: - -//// tab | Python 3.10+ - -```Python -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// +We can do the same as before to **read** `Hero`s, again, we use `response_model=list[HeroPublic]` to ensure that the data is validated and serialized correctly. -//// tab | Python 3.8+ +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[65:72] hl[65] *} -```Python -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -* `sql_app/crud.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` +### Read One Hero with `HeroPublic` -* `sql_app/main.py`: +We can **read** a single hero: -//// tab | Python 3.9+ +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[75:80] hl[77] *} -```Python -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` +### Update a Hero with `HeroUpdate` -//// +We can **update a hero**. For this we use an HTTP `PATCH` operation. -//// tab | Python 3.8+ +And in the code, we get a `dict` with all the data sent by the client, **only the data sent by the client**, excluding any values that would be there just for being the default values. To do it we use `exclude_unset=True`. This is the main trick. 🪄 -```Python -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` +Then we use `hero_db.sqlmodel_update(hero_data)` to update the `hero_db` with the data from `hero_data`. -//// +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[83:93] hl[83:84,88:89] *} -## Check it +### Delete a Hero Again -You can copy this code and use it as is. +**Deleting** a hero stays pretty much the same. -/// info +We won't satisfy the desire to refactor everything in this one. 😅 -In fact, the code shown here is part of the tests. As most of the code in these docs. +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *} -/// - -Then you can run it with Uvicorn: +### Run the App Again +You can run the app again:
```console -$ uvicorn sql_app.main:app --reload +$ fastapi dev main.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ```
-And then, you can open your browser at http://127.0.0.1:8000/docs. - -And you will be able to interact with your **FastAPI** application, reading data from a real database: - - - -## Interact with the database directly - -If you want to explore the SQLite database (file) directly, independently of FastAPI, to debug its contents, add tables, columns, records, modify data, etc. you can use DB Browser for SQLite. - -It will look like this: +If you go to the `/docs` API UI, you will see that it is now updated, and it won't expect to receive the `id` from the client when creating a hero, etc. +
+
-You can also use an online SQLite browser like SQLite Viewer or ExtendsClass. - -## Alternative DB session with middleware - -If you can't use dependencies with `yield` -- for example, if you are not using **Python 3.7** and can't install the "backports" mentioned above for **Python 3.6** -- you can set up the session in a "middleware" in a similar way. - -A "middleware" is basically a function that is always executed for each request, with some code executed before, and some code executed after the endpoint function. - -### Create a middleware - -The middleware we'll add (just a function) will create a new SQLAlchemy `SessionLocal` for each request, add it to the request and then close it once the request is finished. - -//// tab | Python 3.9+ - -```Python hl_lines="12-20" -{!> ../../docs_src/sql_databases/sql_app_py39/alt_main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14-22" -{!> ../../docs_src/sql_databases/sql_app/alt_main.py!} -``` - -//// - -/// info - -We put the creation of the `SessionLocal()` and handling of the requests in a `try` block. - -And then we close it in the `finally` block. - -This way we make sure the database session is always closed after the request. Even if there was an exception while processing the request. - -/// - -### About `request.state` - -`request.state` is a property of each `Request` object. It is there to store arbitrary objects attached to the request itself, like the database session in this case. You can read more about it in Starlette's docs about `Request` state. - -For us in this case, it helps us ensure a single database session is used through all the request, and then closed afterwards (in the middleware). - -### Dependencies with `yield` or middleware - -Adding a **middleware** here is similar to what a dependency with `yield` does, with some differences: - -* It requires more code and is a bit more complex. -* The middleware has to be an `async` function. - * If there is code in it that has to "wait" for the network, it could "block" your application there and degrade performance a bit. - * Although it's probably not very problematic here with the way `SQLAlchemy` works. - * But if you added more code to the middleware that had a lot of I/O waiting, it could then be problematic. -* A middleware is run for *every* request. - * So, a connection will be created for every request. - * Even when the *path operation* that handles that request didn't need the DB. - -/// tip - -It's probably better to use dependencies with `yield` when they are enough for the use case. - -/// - -/// info - -Dependencies with `yield` were added recently to **FastAPI**. +## Recap -A previous version of this tutorial only had the examples with a middleware and there are probably several applications using the middleware for database session management. +You can use **SQLModel** to interact with a SQL database and simplify the code with *data models* and *table models*. -/// +You can learn a lot more at the **SQLModel** docs, there's a longer mini tutorial on using SQLModel with **FastAPI**. 🚀 diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index e55c6f176..8e0f6765d 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -71,13 +71,11 @@ plugins: redirects: redirect_maps: deployment/deta.md: deployment/cloud.md - advanced/sql-databases-peewee.md: how-to/sql-databases-peewee.md - advanced/async-sql-databases.md: how-to/async-sql-encode-databases.md - advanced/nosql-databases.md: how-to/nosql-databases-couchbase.md advanced/graphql.md: how-to/graphql.md advanced/custom-request-and-route.md: how-to/custom-request-and-route.md advanced/conditional-openapi.md: how-to/conditional-openapi.md advanced/extending-openapi.md: how-to/extending-openapi.md + advanced/testing-database.md: how-to/testing-database.md mkdocstrings: handlers: python: @@ -187,7 +185,6 @@ nav: - advanced/testing-websockets.md - advanced/testing-events.md - advanced/testing-dependencies.md - - advanced/testing-database.md - advanced/async-tests.md - advanced/settings.md - advanced/openapi-callbacks.md @@ -214,9 +211,7 @@ nav: - how-to/separate-openapi-schemas.md - how-to/custom-docs-ui-assets.md - how-to/configure-swagger-ui.md - - how-to/sql-databases-peewee.md - - how-to/async-sql-encode-databases.md - - how-to/nosql-databases-couchbase.md + - how-to/testing-database.md - Reference (Code API): - reference/index.md - reference/fastapi.md diff --git a/docs/zh/docs/advanced/testing-database.md b/docs/zh/docs/advanced/testing-database.md deleted file mode 100644 index ecab4f65b..000000000 --- a/docs/zh/docs/advanced/testing-database.md +++ /dev/null @@ -1,101 +0,0 @@ -# 测试数据库 - -您还可以使用[测试依赖项](testing-dependencies.md){.internal-link target=_blank}中的覆盖依赖项方法变更测试的数据库。 - -实现设置其它测试数据库、在测试后回滚数据、或预填测试数据等操作。 - -本章的主要思路与上一章完全相同。 - -## 为 SQL 应用添加测试 - -为了使用测试数据库,我们要升级 [SQL 关系型数据库](../tutorial/sql-databases.md){.internal-link target=_blank} 一章中的示例。 - -应用的所有代码都一样,直接查看那一章的示例代码即可。 - -本章只是新添加了测试文件。 - -正常的依赖项 `get_db()` 返回数据库会话。 - -测试时使用覆盖依赖项返回自定义数据库会话代替正常的依赖项。 - -本例中,要创建仅用于测试的临时数据库。 - -## 文件架构 - -创建新文件 `sql_app/tests/test_sql_app.py`。 - -因此,新的文件架构如下: - -``` hl_lines="9-11" -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - ├── schemas.py - └── tests - ├── __init__.py - └── test_sql_app.py -``` - -## 创建新的数据库会话 - -首先,为新建数据库创建新的数据库会话。 - -测试时,使用 `test.db` 替代 `sql_app.db`。 - -但其余的会话代码基本上都是一样的,只要复制就可以了。 - -```Python hl_lines="8-13" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -/// tip | "提示" - -为减少代码重复,最好把这段代码写成函数,在 `database.py` 与 `tests/test_sql_app.py`中使用。 - -为了把注意力集中在测试代码上,本例只是复制了这段代码。 - -/// - -## 创建数据库 - -因为现在是想在新文件中使用新数据库,所以要使用以下代码创建数据库: - -```Python -Base.metadata.create_all(bind=engine) -``` - -一般是在 `main.py` 中调用这行代码,但在 `main.py` 里,这行代码用于创建 `sql_app.db`,但是现在要为测试创建 `test.db`。 - -因此,要在测试代码中添加这行代码创建新的数据库文件。 - -```Python hl_lines="16" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -## 覆盖依赖项 - -接下来,创建覆盖依赖项,并为应用添加覆盖内容。 - -```Python hl_lines="19-24 27" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -/// tip | "提示" - -`overrider_get_db()` 与 `get_db` 的代码几乎完全一样,只是 `overrider_get_db` 中使用测试数据库的 `TestingSessionLocal`。 - -/// - -## 测试应用 - -然后,就可以正常测试了。 - -```Python hl_lines="32-47" -{!../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -测试期间,所有在数据库中所做的修改都在 `test.db` 里,不会影响主应用的 `sql_app.db`。 diff --git a/docs_src/async_sql_databases/tutorial001.py b/docs_src/async_sql_databases/tutorial001.py deleted file mode 100644 index cbf43d790..000000000 --- a/docs_src/async_sql_databases/tutorial001.py +++ /dev/null @@ -1,65 +0,0 @@ -from typing import List - -import databases -import sqlalchemy -from fastapi import FastAPI -from pydantic import BaseModel - -# SQLAlchemy specific code, as with any other app -DATABASE_URL = "sqlite:///./test.db" -# DATABASE_URL = "postgresql://user:password@postgresserver/db" - -database = databases.Database(DATABASE_URL) - -metadata = sqlalchemy.MetaData() - -notes = sqlalchemy.Table( - "notes", - metadata, - sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True), - sqlalchemy.Column("text", sqlalchemy.String), - sqlalchemy.Column("completed", sqlalchemy.Boolean), -) - - -engine = sqlalchemy.create_engine( - DATABASE_URL, connect_args={"check_same_thread": False} -) -metadata.create_all(engine) - - -class NoteIn(BaseModel): - text: str - completed: bool - - -class Note(BaseModel): - id: int - text: str - completed: bool - - -app = FastAPI() - - -@app.on_event("startup") -async def startup(): - await database.connect() - - -@app.on_event("shutdown") -async def shutdown(): - await database.disconnect() - - -@app.get("/notes/", response_model=List[Note]) -async def read_notes(): - query = notes.select() - return await database.fetch_all(query) - - -@app.post("/notes/", response_model=Note) -async def create_note(note: NoteIn): - query = notes.insert().values(text=note.text, completed=note.completed) - last_record_id = await database.execute(query) - return {**note.dict(), "id": last_record_id} diff --git a/docs_src/nosql_databases/tutorial001.py b/docs_src/nosql_databases/tutorial001.py deleted file mode 100644 index 91893e528..000000000 --- a/docs_src/nosql_databases/tutorial001.py +++ /dev/null @@ -1,53 +0,0 @@ -from typing import Union - -from couchbase import LOCKMODE_WAIT -from couchbase.bucket import Bucket -from couchbase.cluster import Cluster, PasswordAuthenticator -from fastapi import FastAPI -from pydantic import BaseModel - -USERPROFILE_DOC_TYPE = "userprofile" - - -def get_bucket(): - cluster = Cluster( - "couchbase://couchbasehost:8091?fetch_mutation_tokens=1&operation_timeout=30&n1ql_timeout=300" - ) - authenticator = PasswordAuthenticator("username", "password") - cluster.authenticate(authenticator) - bucket: Bucket = cluster.open_bucket("bucket_name", lockmode=LOCKMODE_WAIT) - bucket.timeout = 30 - bucket.n1ql_timeout = 300 - return bucket - - -class User(BaseModel): - username: str - email: Union[str, None] = None - full_name: Union[str, None] = None - disabled: Union[bool, None] = None - - -class UserInDB(User): - type: str = USERPROFILE_DOC_TYPE - hashed_password: str - - -def get_user(bucket: Bucket, username: str): - doc_id = f"userprofile::{username}" - result = bucket.get(doc_id, quiet=True) - if not result.value: - return None - user = UserInDB(**result.value) - return user - - -# FastAPI specific code -app = FastAPI() - - -@app.get("/users/{username}", response_model=User) -def read_user(username: str): - bucket = get_bucket() - user = get_user(bucket=bucket, username=username) - return user diff --git a/docs_src/sql_databases/sql_app/__init__.py b/docs_src/sql_databases/sql_app/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs_src/sql_databases/sql_app/alt_main.py b/docs_src/sql_databases/sql_app/alt_main.py deleted file mode 100644 index f7206bcb4..000000000 --- a/docs_src/sql_databases/sql_app/alt_main.py +++ /dev/null @@ -1,62 +0,0 @@ -from typing import List - -from fastapi import Depends, FastAPI, HTTPException, Request, Response -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -@app.middleware("http") -async def db_session_middleware(request: Request, call_next): - response = Response("Internal server error", status_code=500) - try: - request.state.db = SessionLocal() - response = await call_next(request) - finally: - request.state.db.close() - return response - - -# Dependency -def get_db(request: Request): - return request.state.db - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=List[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=List[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app/crud.py b/docs_src/sql_databases/sql_app/crud.py deleted file mode 100644 index 679acdb5c..000000000 --- a/docs_src/sql_databases/sql_app/crud.py +++ /dev/null @@ -1,36 +0,0 @@ -from sqlalchemy.orm import Session - -from . import models, schemas - - -def get_user(db: Session, user_id: int): - return db.query(models.User).filter(models.User.id == user_id).first() - - -def get_user_by_email(db: Session, email: str): - return db.query(models.User).filter(models.User.email == email).first() - - -def get_users(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.User).offset(skip).limit(limit).all() - - -def create_user(db: Session, user: schemas.UserCreate): - fake_hashed_password = user.password + "notreallyhashed" - db_user = models.User(email=user.email, hashed_password=fake_hashed_password) - db.add(db_user) - db.commit() - db.refresh(db_user) - return db_user - - -def get_items(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.Item).offset(skip).limit(limit).all() - - -def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int): - db_item = models.Item(**item.dict(), owner_id=user_id) - db.add(db_item) - db.commit() - db.refresh(db_item) - return db_item diff --git a/docs_src/sql_databases/sql_app/database.py b/docs_src/sql_databases/sql_app/database.py deleted file mode 100644 index 45a8b9f69..000000000 --- a/docs_src/sql_databases/sql_app/database.py +++ /dev/null @@ -1,13 +0,0 @@ -from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker - -SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" -# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - -Base = declarative_base() diff --git a/docs_src/sql_databases/sql_app/main.py b/docs_src/sql_databases/sql_app/main.py deleted file mode 100644 index e7508c59d..000000000 --- a/docs_src/sql_databases/sql_app/main.py +++ /dev/null @@ -1,55 +0,0 @@ -from typing import List - -from fastapi import Depends, FastAPI, HTTPException -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -# Dependency -def get_db(): - db = SessionLocal() - try: - yield db - finally: - db.close() - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=List[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=List[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app/models.py b/docs_src/sql_databases/sql_app/models.py deleted file mode 100644 index 09ae2a807..000000000 --- a/docs_src/sql_databases/sql_app/models.py +++ /dev/null @@ -1,26 +0,0 @@ -from sqlalchemy import Boolean, Column, ForeignKey, Integer, String -from sqlalchemy.orm import relationship - -from .database import Base - - -class User(Base): - __tablename__ = "users" - - id = Column(Integer, primary_key=True) - email = Column(String, unique=True, index=True) - hashed_password = Column(String) - is_active = Column(Boolean, default=True) - - items = relationship("Item", back_populates="owner") - - -class Item(Base): - __tablename__ = "items" - - id = Column(Integer, primary_key=True) - title = Column(String, index=True) - description = Column(String, index=True) - owner_id = Column(Integer, ForeignKey("users.id")) - - owner = relationship("User", back_populates="items") diff --git a/docs_src/sql_databases/sql_app/schemas.py b/docs_src/sql_databases/sql_app/schemas.py deleted file mode 100644 index c49beba88..000000000 --- a/docs_src/sql_databases/sql_app/schemas.py +++ /dev/null @@ -1,37 +0,0 @@ -from typing import List, Union - -from pydantic import BaseModel - - -class ItemBase(BaseModel): - title: str - description: Union[str, None] = None - - -class ItemCreate(ItemBase): - pass - - -class Item(ItemBase): - id: int - owner_id: int - - class Config: - orm_mode = True - - -class UserBase(BaseModel): - email: str - - -class UserCreate(UserBase): - password: str - - -class User(UserBase): - id: int - is_active: bool - items: List[Item] = [] - - class Config: - orm_mode = True diff --git a/docs_src/sql_databases/sql_app/tests/__init__.py b/docs_src/sql_databases/sql_app/tests/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs_src/sql_databases/sql_app/tests/test_sql_app.py b/docs_src/sql_databases/sql_app/tests/test_sql_app.py deleted file mode 100644 index 5f55add0a..000000000 --- a/docs_src/sql_databases/sql_app/tests/test_sql_app.py +++ /dev/null @@ -1,50 +0,0 @@ -from fastapi.testclient import TestClient -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import StaticPool - -from ..database import Base -from ..main import app, get_db - -SQLALCHEMY_DATABASE_URL = "sqlite://" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, - connect_args={"check_same_thread": False}, - poolclass=StaticPool, -) -TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - - -Base.metadata.create_all(bind=engine) - - -def override_get_db(): - try: - db = TestingSessionLocal() - yield db - finally: - db.close() - - -app.dependency_overrides[get_db] = override_get_db - -client = TestClient(app) - - -def test_create_user(): - response = client.post( - "/users/", - json={"email": "deadpool@example.com", "password": "chimichangas4life"}, - ) - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert "id" in data - user_id = data["id"] - - response = client.get(f"/users/{user_id}") - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert data["id"] == user_id diff --git a/docs_src/sql_databases/sql_app_py310/__init__.py b/docs_src/sql_databases/sql_app_py310/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs_src/sql_databases/sql_app_py310/alt_main.py b/docs_src/sql_databases/sql_app_py310/alt_main.py deleted file mode 100644 index 5de88ec3a..000000000 --- a/docs_src/sql_databases/sql_app_py310/alt_main.py +++ /dev/null @@ -1,60 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException, Request, Response -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -@app.middleware("http") -async def db_session_middleware(request: Request, call_next): - response = Response("Internal server error", status_code=500) - try: - request.state.db = SessionLocal() - response = await call_next(request) - finally: - request.state.db.close() - return response - - -# Dependency -def get_db(request: Request): - return request.state.db - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py310/crud.py b/docs_src/sql_databases/sql_app_py310/crud.py deleted file mode 100644 index 679acdb5c..000000000 --- a/docs_src/sql_databases/sql_app_py310/crud.py +++ /dev/null @@ -1,36 +0,0 @@ -from sqlalchemy.orm import Session - -from . import models, schemas - - -def get_user(db: Session, user_id: int): - return db.query(models.User).filter(models.User.id == user_id).first() - - -def get_user_by_email(db: Session, email: str): - return db.query(models.User).filter(models.User.email == email).first() - - -def get_users(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.User).offset(skip).limit(limit).all() - - -def create_user(db: Session, user: schemas.UserCreate): - fake_hashed_password = user.password + "notreallyhashed" - db_user = models.User(email=user.email, hashed_password=fake_hashed_password) - db.add(db_user) - db.commit() - db.refresh(db_user) - return db_user - - -def get_items(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.Item).offset(skip).limit(limit).all() - - -def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int): - db_item = models.Item(**item.dict(), owner_id=user_id) - db.add(db_item) - db.commit() - db.refresh(db_item) - return db_item diff --git a/docs_src/sql_databases/sql_app_py310/database.py b/docs_src/sql_databases/sql_app_py310/database.py deleted file mode 100644 index 45a8b9f69..000000000 --- a/docs_src/sql_databases/sql_app_py310/database.py +++ /dev/null @@ -1,13 +0,0 @@ -from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker - -SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" -# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - -Base = declarative_base() diff --git a/docs_src/sql_databases/sql_app_py310/main.py b/docs_src/sql_databases/sql_app_py310/main.py deleted file mode 100644 index a9856d0b6..000000000 --- a/docs_src/sql_databases/sql_app_py310/main.py +++ /dev/null @@ -1,53 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -# Dependency -def get_db(): - db = SessionLocal() - try: - yield db - finally: - db.close() - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py310/models.py b/docs_src/sql_databases/sql_app_py310/models.py deleted file mode 100644 index 09ae2a807..000000000 --- a/docs_src/sql_databases/sql_app_py310/models.py +++ /dev/null @@ -1,26 +0,0 @@ -from sqlalchemy import Boolean, Column, ForeignKey, Integer, String -from sqlalchemy.orm import relationship - -from .database import Base - - -class User(Base): - __tablename__ = "users" - - id = Column(Integer, primary_key=True) - email = Column(String, unique=True, index=True) - hashed_password = Column(String) - is_active = Column(Boolean, default=True) - - items = relationship("Item", back_populates="owner") - - -class Item(Base): - __tablename__ = "items" - - id = Column(Integer, primary_key=True) - title = Column(String, index=True) - description = Column(String, index=True) - owner_id = Column(Integer, ForeignKey("users.id")) - - owner = relationship("User", back_populates="items") diff --git a/docs_src/sql_databases/sql_app_py310/schemas.py b/docs_src/sql_databases/sql_app_py310/schemas.py deleted file mode 100644 index aea2e3f10..000000000 --- a/docs_src/sql_databases/sql_app_py310/schemas.py +++ /dev/null @@ -1,35 +0,0 @@ -from pydantic import BaseModel - - -class ItemBase(BaseModel): - title: str - description: str | None = None - - -class ItemCreate(ItemBase): - pass - - -class Item(ItemBase): - id: int - owner_id: int - - class Config: - orm_mode = True - - -class UserBase(BaseModel): - email: str - - -class UserCreate(UserBase): - password: str - - -class User(UserBase): - id: int - is_active: bool - items: list[Item] = [] - - class Config: - orm_mode = True diff --git a/docs_src/sql_databases/sql_app_py310/tests/__init__.py b/docs_src/sql_databases/sql_app_py310/tests/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py b/docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py deleted file mode 100644 index c60c3356f..000000000 --- a/docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py +++ /dev/null @@ -1,47 +0,0 @@ -from fastapi.testclient import TestClient -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker - -from ..database import Base -from ..main import app, get_db - -SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - - -Base.metadata.create_all(bind=engine) - - -def override_get_db(): - try: - db = TestingSessionLocal() - yield db - finally: - db.close() - - -app.dependency_overrides[get_db] = override_get_db - -client = TestClient(app) - - -def test_create_user(): - response = client.post( - "/users/", - json={"email": "deadpool@example.com", "password": "chimichangas4life"}, - ) - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert "id" in data - user_id = data["id"] - - response = client.get(f"/users/{user_id}") - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert data["id"] == user_id diff --git a/docs_src/sql_databases/sql_app_py39/__init__.py b/docs_src/sql_databases/sql_app_py39/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs_src/sql_databases/sql_app_py39/alt_main.py b/docs_src/sql_databases/sql_app_py39/alt_main.py deleted file mode 100644 index 5de88ec3a..000000000 --- a/docs_src/sql_databases/sql_app_py39/alt_main.py +++ /dev/null @@ -1,60 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException, Request, Response -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -@app.middleware("http") -async def db_session_middleware(request: Request, call_next): - response = Response("Internal server error", status_code=500) - try: - request.state.db = SessionLocal() - response = await call_next(request) - finally: - request.state.db.close() - return response - - -# Dependency -def get_db(request: Request): - return request.state.db - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py39/crud.py b/docs_src/sql_databases/sql_app_py39/crud.py deleted file mode 100644 index 679acdb5c..000000000 --- a/docs_src/sql_databases/sql_app_py39/crud.py +++ /dev/null @@ -1,36 +0,0 @@ -from sqlalchemy.orm import Session - -from . import models, schemas - - -def get_user(db: Session, user_id: int): - return db.query(models.User).filter(models.User.id == user_id).first() - - -def get_user_by_email(db: Session, email: str): - return db.query(models.User).filter(models.User.email == email).first() - - -def get_users(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.User).offset(skip).limit(limit).all() - - -def create_user(db: Session, user: schemas.UserCreate): - fake_hashed_password = user.password + "notreallyhashed" - db_user = models.User(email=user.email, hashed_password=fake_hashed_password) - db.add(db_user) - db.commit() - db.refresh(db_user) - return db_user - - -def get_items(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.Item).offset(skip).limit(limit).all() - - -def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int): - db_item = models.Item(**item.dict(), owner_id=user_id) - db.add(db_item) - db.commit() - db.refresh(db_item) - return db_item diff --git a/docs_src/sql_databases/sql_app_py39/database.py b/docs_src/sql_databases/sql_app_py39/database.py deleted file mode 100644 index 45a8b9f69..000000000 --- a/docs_src/sql_databases/sql_app_py39/database.py +++ /dev/null @@ -1,13 +0,0 @@ -from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker - -SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" -# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - -Base = declarative_base() diff --git a/docs_src/sql_databases/sql_app_py39/main.py b/docs_src/sql_databases/sql_app_py39/main.py deleted file mode 100644 index a9856d0b6..000000000 --- a/docs_src/sql_databases/sql_app_py39/main.py +++ /dev/null @@ -1,53 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -# Dependency -def get_db(): - db = SessionLocal() - try: - yield db - finally: - db.close() - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py39/models.py b/docs_src/sql_databases/sql_app_py39/models.py deleted file mode 100644 index 09ae2a807..000000000 --- a/docs_src/sql_databases/sql_app_py39/models.py +++ /dev/null @@ -1,26 +0,0 @@ -from sqlalchemy import Boolean, Column, ForeignKey, Integer, String -from sqlalchemy.orm import relationship - -from .database import Base - - -class User(Base): - __tablename__ = "users" - - id = Column(Integer, primary_key=True) - email = Column(String, unique=True, index=True) - hashed_password = Column(String) - is_active = Column(Boolean, default=True) - - items = relationship("Item", back_populates="owner") - - -class Item(Base): - __tablename__ = "items" - - id = Column(Integer, primary_key=True) - title = Column(String, index=True) - description = Column(String, index=True) - owner_id = Column(Integer, ForeignKey("users.id")) - - owner = relationship("User", back_populates="items") diff --git a/docs_src/sql_databases/sql_app_py39/schemas.py b/docs_src/sql_databases/sql_app_py39/schemas.py deleted file mode 100644 index dadc403d9..000000000 --- a/docs_src/sql_databases/sql_app_py39/schemas.py +++ /dev/null @@ -1,37 +0,0 @@ -from typing import Union - -from pydantic import BaseModel - - -class ItemBase(BaseModel): - title: str - description: Union[str, None] = None - - -class ItemCreate(ItemBase): - pass - - -class Item(ItemBase): - id: int - owner_id: int - - class Config: - orm_mode = True - - -class UserBase(BaseModel): - email: str - - -class UserCreate(UserBase): - password: str - - -class User(UserBase): - id: int - is_active: bool - items: list[Item] = [] - - class Config: - orm_mode = True diff --git a/docs_src/sql_databases/sql_app_py39/tests/__init__.py b/docs_src/sql_databases/sql_app_py39/tests/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py b/docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py deleted file mode 100644 index c60c3356f..000000000 --- a/docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py +++ /dev/null @@ -1,47 +0,0 @@ -from fastapi.testclient import TestClient -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker - -from ..database import Base -from ..main import app, get_db - -SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - - -Base.metadata.create_all(bind=engine) - - -def override_get_db(): - try: - db = TestingSessionLocal() - yield db - finally: - db.close() - - -app.dependency_overrides[get_db] = override_get_db - -client = TestClient(app) - - -def test_create_user(): - response = client.post( - "/users/", - json={"email": "deadpool@example.com", "password": "chimichangas4life"}, - ) - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert "id" in data - user_id = data["id"] - - response = client.get(f"/users/{user_id}") - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert data["id"] == user_id diff --git a/docs_src/sql_databases/tutorial001.py b/docs_src/sql_databases/tutorial001.py new file mode 100644 index 000000000..be86ec0ee --- /dev/null +++ b/docs_src/sql_databases/tutorial001.py @@ -0,0 +1,71 @@ +from typing import List, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: Session = Depends(get_session)) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +) -> List[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: Session = Depends(get_session)) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_an.py b/docs_src/sql_databases/tutorial001_an.py new file mode 100644 index 000000000..8c000d31c --- /dev/null +++ b/docs_src/sql_databases/tutorial001_an.py @@ -0,0 +1,74 @@ +from typing import List, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select +from typing_extensions import Annotated + + +class Hero(SQLModel, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: SessionDep) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +) -> List[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: SessionDep) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_an_py310.py b/docs_src/sql_databases/tutorial001_an_py310.py new file mode 100644 index 000000000..de1fb81fa --- /dev/null +++ b/docs_src/sql_databases/tutorial001_an_py310.py @@ -0,0 +1,73 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: int | None = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: SessionDep) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +) -> list[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: SessionDep) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_an_py39.py b/docs_src/sql_databases/tutorial001_an_py39.py new file mode 100644 index 000000000..595892746 --- /dev/null +++ b/docs_src/sql_databases/tutorial001_an_py39.py @@ -0,0 +1,73 @@ +from typing import Annotated, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: SessionDep) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +) -> list[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: SessionDep) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_py310.py b/docs_src/sql_databases/tutorial001_py310.py new file mode 100644 index 000000000..b58462e6a --- /dev/null +++ b/docs_src/sql_databases/tutorial001_py310.py @@ -0,0 +1,69 @@ +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: int | None = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: Session = Depends(get_session)) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +) -> list[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: Session = Depends(get_session)) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_py39.py b/docs_src/sql_databases/tutorial001_py39.py new file mode 100644 index 000000000..410a52d0c --- /dev/null +++ b/docs_src/sql_databases/tutorial001_py39.py @@ -0,0 +1,71 @@ +from typing import Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: Session = Depends(get_session)) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +) -> list[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: Session = Depends(get_session)) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002.py b/docs_src/sql_databases/tutorial002.py new file mode 100644 index 000000000..4350d19c6 --- /dev/null +++ b/docs_src/sql_databases/tutorial002.py @@ -0,0 +1,104 @@ +from typing import List, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: Union[str, None] = None + age: Union[int, None] = None + secret_name: Union[str, None] = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: Session = Depends(get_session)): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=List[HeroPublic]) +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero( + hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session) +): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_an.py b/docs_src/sql_databases/tutorial002_an.py new file mode 100644 index 000000000..15e3d7c3a --- /dev/null +++ b/docs_src/sql_databases/tutorial002_an.py @@ -0,0 +1,104 @@ +from typing import List, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select +from typing_extensions import Annotated + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: Union[str, None] = None + age: Union[int, None] = None + secret_name: Union[str, None] = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: SessionDep): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=List[HeroPublic]) +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_an_py310.py b/docs_src/sql_databases/tutorial002_an_py310.py new file mode 100644 index 000000000..64c554b8a --- /dev/null +++ b/docs_src/sql_databases/tutorial002_an_py310.py @@ -0,0 +1,103 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: int | None = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: str | None = None + age: int | None = None + secret_name: str | None = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: SessionDep): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=list[HeroPublic]) +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_an_py39.py b/docs_src/sql_databases/tutorial002_an_py39.py new file mode 100644 index 000000000..a8a0721ff --- /dev/null +++ b/docs_src/sql_databases/tutorial002_an_py39.py @@ -0,0 +1,103 @@ +from typing import Annotated, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: Union[str, None] = None + age: Union[int, None] = None + secret_name: Union[str, None] = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: SessionDep): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=list[HeroPublic]) +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_py310.py b/docs_src/sql_databases/tutorial002_py310.py new file mode 100644 index 000000000..ec3d68db5 --- /dev/null +++ b/docs_src/sql_databases/tutorial002_py310.py @@ -0,0 +1,102 @@ +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: int | None = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: str | None = None + age: int | None = None + secret_name: str | None = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: Session = Depends(get_session)): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=list[HeroPublic]) +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero( + hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session) +): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_py39.py b/docs_src/sql_databases/tutorial002_py39.py new file mode 100644 index 000000000..d8f5dd090 --- /dev/null +++ b/docs_src/sql_databases/tutorial002_py39.py @@ -0,0 +1,104 @@ +from typing import Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: Union[str, None] = None + age: Union[int, None] = None + secret_name: Union[str, None] = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: Session = Depends(get_session)): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=list[HeroPublic]) +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero( + hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session) +): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/requirements-docs.txt b/requirements-docs.txt index c05bd51e3..1639159af 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -16,4 +16,4 @@ griffe-typingdoc==0.2.7 # For griffe, it formats with black black==24.3.0 mkdocs-macros-plugin==1.0.5 -markdown-include-variants==0.0.1 +markdown-include-variants==0.0.3 diff --git a/requirements-tests.txt b/requirements-tests.txt index 7b1f7ea1a..189fcaf7e 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -4,10 +4,7 @@ pytest >=7.1.3,<8.0.0 coverage[toml] >= 6.5.0,< 8.0 mypy ==1.8.0 dirty-equals ==0.6.0 -# TODO: once removing databases from tutorial, upgrade SQLAlchemy -# probably when including SQLModel -sqlalchemy >=1.3.18,<2.0.33 -databases[sqlite] >=0.3.2,<0.7.0 +sqlmodel==0.0.22 flask >=1.1.2,<3.0.0 anyio[trio] >=3.2.1,<4.0.0 PyJWT==2.8.0 diff --git a/scripts/playwright/sql_databases/image01.py b/scripts/playwright/sql_databases/image01.py new file mode 100644 index 000000000..0dd6f2514 --- /dev/null +++ b/scripts/playwright/sql_databases/image01.py @@ -0,0 +1,37 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_label("post /heroes/").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/sql-databases/image01.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/sql_databases/tutorial001.py"], +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/playwright/sql_databases/image02.py b/scripts/playwright/sql_databases/image02.py new file mode 100644 index 000000000..6c4f685e8 --- /dev/null +++ b/scripts/playwright/sql_databases/image02.py @@ -0,0 +1,37 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_label("post /heroes/").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/sql-databases/image02.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/sql_databases/tutorial002.py"], +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/tests/test_tutorial/test_async_sql_databases/__init__.py b/tests/test_tutorial/test_async_sql_databases/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py b/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py deleted file mode 100644 index 13568a532..000000000 --- a/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py +++ /dev/null @@ -1,146 +0,0 @@ -import pytest -from fastapi import FastAPI -from fastapi.testclient import TestClient - -from ...utils import needs_pydanticv1 - - -@pytest.fixture(name="app", scope="module") -def get_app(): - with pytest.warns(DeprecationWarning): - from docs_src.async_sql_databases.tutorial001 import app - yield app - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_read(app: FastAPI): - with TestClient(app) as client: - note = {"text": "Foo bar", "completed": False} - response = client.post("/notes/", json=note) - assert response.status_code == 200, response.text - data = response.json() - assert data["text"] == note["text"] - assert data["completed"] == note["completed"] - assert "id" in data - response = client.get("/notes/") - assert response.status_code == 200, response.text - assert data in response.json() - - -def test_openapi_schema(app: FastAPI): - with TestClient(app) as client: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/notes/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Notes Notes Get", - "type": "array", - "items": { - "$ref": "#/components/schemas/Note" - }, - } - } - }, - } - }, - "summary": "Read Notes", - "operationId": "read_notes_notes__get", - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Note"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Note", - "operationId": "create_note_notes__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/NoteIn"} - } - }, - "required": True, - }, - }, - } - }, - "components": { - "schemas": { - "NoteIn": { - "title": "NoteIn", - "required": ["text", "completed"], - "type": "object", - "properties": { - "text": {"title": "Text", "type": "string"}, - "completed": {"title": "Completed", "type": "boolean"}, - }, - }, - "Note": { - "title": "Note", - "required": ["id", "text", "completed"], - "type": "object", - "properties": { - "id": {"title": "Id", "type": "integer"}, - "text": {"title": "Text", "type": "string"}, - "completed": {"title": "Completed", "type": "boolean"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": { - "$ref": "#/components/schemas/ValidationError" - }, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases.py b/tests/test_tutorial/test_sql_databases/test_sql_databases.py deleted file mode 100644 index e3e2b36a8..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases.py +++ /dev/null @@ -1,419 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_pydanticv1 - - -@pytest.fixture(scope="module") -def client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app import main - - # Ensure import side effects are re-executed - importlib.reload(main) - with TestClient(main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_nonexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py deleted file mode 100644 index 73b97e09d..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py +++ /dev/null @@ -1,421 +0,0 @@ -import importlib -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_pydanticv1 - - -@pytest.fixture(scope="module") -def client(): - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app import alt_main - - # Ensure import side effects are re-executed - importlib.reload(alt_main) - - with TestClient(alt_main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_nonexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py deleted file mode 100644 index a078f012a..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py +++ /dev/null @@ -1,433 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv1 - - -@pytest.fixture(scope="module") -def client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py310 import alt_main - - # Ensure import side effects are re-executed - importlib.reload(alt_main) - - with TestClient(alt_main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_nonexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -@needs_py310 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -@needs_py310 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py deleted file mode 100644 index a5da07ac6..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py +++ /dev/null @@ -1,433 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39, needs_pydanticv1 - - -@pytest.fixture(scope="module") -def client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py39 import alt_main - - # Ensure import side effects are re-executed - importlib.reload(alt_main) - - with TestClient(alt_main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_nonexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py deleted file mode 100644 index 5a9106598..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py +++ /dev/null @@ -1,432 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv1 - - -@pytest.fixture(scope="module", name="client") -def get_client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py310 import main - - # Ensure import side effects are re-executed - importlib.reload(main) - with TestClient(main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_nonexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -@needs_py310 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -@needs_py310 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py deleted file mode 100644 index a354ba905..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py +++ /dev/null @@ -1,432 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39, needs_pydanticv1 - - -@pytest.fixture(scope="module", name="client") -def get_client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py39 import main - - # Ensure import side effects are re-executed - importlib.reload(main) - with TestClient(main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_nonexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -@needs_py39 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -@needs_py39 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_testing_databases.py b/tests/test_tutorial/test_sql_databases/test_testing_databases.py deleted file mode 100644 index ce6ce230c..000000000 --- a/tests/test_tutorial/test_sql_databases/test_testing_databases.py +++ /dev/null @@ -1,27 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest - -from ...utils import needs_pydanticv1 - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_testing_dbs(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./test.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app.tests import test_sql_app - - # Ensure import side effects are re-executed - importlib.reload(test_sql_app) - test_sql_app.test_create_user() - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) diff --git a/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py b/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py deleted file mode 100644 index 545d63c2a..000000000 --- a/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py +++ /dev/null @@ -1,28 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest - -from ...utils import needs_py310, needs_pydanticv1 - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_testing_dbs_py39(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./test.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py310.tests import test_sql_app - - # Ensure import side effects are re-executed - importlib.reload(test_sql_app) - test_sql_app.test_create_user() - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) diff --git a/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py b/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py deleted file mode 100644 index 99bfd3fa8..000000000 --- a/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py +++ /dev/null @@ -1,28 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest - -from ...utils import needs_py39, needs_pydanticv1 - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_testing_dbs_py39(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./test.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py39.tests import test_sql_app - - # Ensure import side effects are re-executed - importlib.reload(test_sql_app) - test_sql_app.test_create_user() - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) diff --git a/tests/test_tutorial/test_sql_databases/test_tutorial001.py b/tests/test_tutorial/test_sql_databases/test_tutorial001.py new file mode 100644 index 000000000..cc7e590df --- /dev/null +++ b/tests/test_tutorial/test_sql_databases/test_tutorial001.py @@ -0,0 +1,373 @@ +import importlib +import warnings + +import pytest +from dirty_equals import IsDict, IsInt +from fastapi.testclient import TestClient +from inline_snapshot import snapshot +from sqlalchemy import StaticPool +from sqlmodel import SQLModel, create_engine +from sqlmodel.main import default_registry + +from tests.utils import needs_py39, needs_py310 + + +def clear_sqlmodel(): + # Clear the tables in the metadata for the default base model + SQLModel.metadata.clear() + # Clear the Models associated with the registry, to avoid warnings + default_registry.dispose() + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py39", marks=needs_py39), + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + clear_sqlmodel() + # TODO: remove when updating SQL tutorial to use new lifespan API + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + mod = importlib.import_module(f"docs_src.sql_databases.{request.param}") + clear_sqlmodel() + importlib.reload(mod) + mod.sqlite_url = "sqlite://" + mod.engine = create_engine( + mod.sqlite_url, connect_args={"check_same_thread": False}, poolclass=StaticPool + ) + + with TestClient(mod.app) as c: + yield c + + +def test_crud_app(client: TestClient): + # TODO: this warns that SQLModel.from_orm is deprecated in Pydantic v1, refactor + # this if using obj.model_validate becomes independent of Pydantic v2 + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + # No heroes before creating + response = client.get("heroes/") + assert response.status_code == 200, response.text + assert response.json() == [] + + # Create a hero + response = client.post( + "/heroes/", + json={ + "id": 999, + "name": "Dead Pond", + "age": 30, + "secret_name": "Dive Wilson", + }, + ) + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"age": 30, "secret_name": "Dive Wilson", "id": 999, "name": "Dead Pond"} + ) + + # Read a hero + hero_id = response.json()["id"] + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"name": "Dead Pond", "age": 30, "id": 999, "secret_name": "Dive Wilson"} + ) + + # Read all heroes + # Create more heroes first + response = client.post( + "/heroes/", + json={"name": "Spider-Boy", "age": 18, "secret_name": "Pedro Parqueador"}, + ) + assert response.status_code == 200, response.text + response = client.post( + "/heroes/", json={"name": "Rusty-Man", "secret_name": "Tommy Sharp"} + ) + assert response.status_code == 200, response.text + + response = client.get("/heroes/") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + [ + { + "name": "Dead Pond", + "age": 30, + "id": IsInt(), + "secret_name": "Dive Wilson", + }, + { + "name": "Spider-Boy", + "age": 18, + "id": IsInt(), + "secret_name": "Pedro Parqueador", + }, + { + "name": "Rusty-Man", + "age": None, + "id": IsInt(), + "secret_name": "Tommy Sharp", + }, + ] + ) + + response = client.get("/heroes/?offset=1&limit=1") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + [ + { + "name": "Spider-Boy", + "age": 18, + "id": IsInt(), + "secret_name": "Pedro Parqueador", + } + ] + ) + + # Delete a hero + response = client.delete(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot({"ok": True}) + + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 404, response.text + + response = client.delete(f"/heroes/{hero_id}") + assert response.status_code == 404, response.text + assert response.json() == snapshot({"detail": "Hero not found"}) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/heroes/": { + "post": { + "summary": "Create Hero", + "operationId": "create_hero_heroes__post", + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Hero"} + } + }, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Hero"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "get": { + "summary": "Read Heroes", + "operationId": "read_heroes_heroes__get", + "parameters": [ + { + "name": "offset", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "default": 0, + "title": "Offset", + }, + }, + { + "name": "limit", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "maximum": 100, + "default": 100, + "title": "Limit", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hero" + }, + "title": "Response Read Heroes Heroes Get", + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + }, + "/heroes/{hero_id}": { + "get": { + "summary": "Read Hero", + "operationId": "read_hero_heroes__hero_id__get", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Hero"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "delete": { + "summary": "Delete Hero", + "operationId": "delete_hero_heroes__hero_id__delete", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + }, + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Hero": { + "properties": { + "id": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Id", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Id", + } + ), + "name": {"type": "string", "title": "Name"}, + "age": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Age", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Age", + } + ), + "secret_name": {"type": "string", "title": "Secret Name"}, + }, + "type": "object", + "required": ["name", "secret_name"], + "title": "Hero", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_sql_databases/test_tutorial002.py b/tests/test_tutorial/test_sql_databases/test_tutorial002.py new file mode 100644 index 000000000..68c1966f5 --- /dev/null +++ b/tests/test_tutorial/test_sql_databases/test_tutorial002.py @@ -0,0 +1,481 @@ +import importlib +import warnings + +import pytest +from dirty_equals import IsDict, IsInt +from fastapi.testclient import TestClient +from inline_snapshot import snapshot +from sqlalchemy import StaticPool +from sqlmodel import SQLModel, create_engine +from sqlmodel.main import default_registry + +from tests.utils import needs_py39, needs_py310 + + +def clear_sqlmodel(): + # Clear the tables in the metadata for the default base model + SQLModel.metadata.clear() + # Clear the Models associated with the registry, to avoid warnings + default_registry.dispose() + + +@pytest.fixture( + name="client", + params=[ + "tutorial002", + pytest.param("tutorial002_py39", marks=needs_py39), + pytest.param("tutorial002_py310", marks=needs_py310), + "tutorial002_an", + pytest.param("tutorial002_an_py39", marks=needs_py39), + pytest.param("tutorial002_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + clear_sqlmodel() + # TODO: remove when updating SQL tutorial to use new lifespan API + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + mod = importlib.import_module(f"docs_src.sql_databases.{request.param}") + clear_sqlmodel() + importlib.reload(mod) + mod.sqlite_url = "sqlite://" + mod.engine = create_engine( + mod.sqlite_url, connect_args={"check_same_thread": False}, poolclass=StaticPool + ) + + with TestClient(mod.app) as c: + yield c + + +def test_crud_app(client: TestClient): + # TODO: this warns that SQLModel.from_orm is deprecated in Pydantic v1, refactor + # this if using obj.model_validate becomes independent of Pydantic v2 + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + # No heroes before creating + response = client.get("heroes/") + assert response.status_code == 200, response.text + assert response.json() == [] + + # Create a hero + response = client.post( + "/heroes/", + json={ + "id": 9000, + "name": "Dead Pond", + "age": 30, + "secret_name": "Dive Wilson", + }, + ) + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"age": 30, "id": IsInt(), "name": "Dead Pond"} + ) + assert ( + response.json()["id"] != 9000 + ), "The ID should be generated by the database" + + # Read a hero + hero_id = response.json()["id"] + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"name": "Dead Pond", "age": 30, "id": IsInt()} + ) + + # Read all heroes + # Create more heroes first + response = client.post( + "/heroes/", + json={"name": "Spider-Boy", "age": 18, "secret_name": "Pedro Parqueador"}, + ) + assert response.status_code == 200, response.text + response = client.post( + "/heroes/", json={"name": "Rusty-Man", "secret_name": "Tommy Sharp"} + ) + assert response.status_code == 200, response.text + + response = client.get("/heroes/") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + [ + {"name": "Dead Pond", "age": 30, "id": IsInt()}, + {"name": "Spider-Boy", "age": 18, "id": IsInt()}, + {"name": "Rusty-Man", "age": None, "id": IsInt()}, + ] + ) + + response = client.get("/heroes/?offset=1&limit=1") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + [{"name": "Spider-Boy", "age": 18, "id": IsInt()}] + ) + + # Update a hero + response = client.patch( + f"/heroes/{hero_id}", json={"name": "Dog Pond", "age": None} + ) + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"name": "Dog Pond", "age": None, "id": hero_id} + ) + + # Get updated hero + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"name": "Dog Pond", "age": None, "id": hero_id} + ) + + # Delete a hero + response = client.delete(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot({"ok": True}) + + # The hero is no longer found + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 404, response.text + + # Delete a hero that does not exist + response = client.delete(f"/heroes/{hero_id}") + assert response.status_code == 404, response.text + assert response.json() == snapshot({"detail": "Hero not found"}) + + # Update a hero that does not exist + response = client.patch(f"/heroes/{hero_id}", json={"name": "Dog Pond"}) + assert response.status_code == 404, response.text + assert response.json() == snapshot({"detail": "Hero not found"}) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/heroes/": { + "post": { + "summary": "Create Hero", + "operationId": "create_hero_heroes__post", + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroCreate" + } + } + }, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroPublic" + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "get": { + "summary": "Read Heroes", + "operationId": "read_heroes_heroes__get", + "parameters": [ + { + "name": "offset", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "default": 0, + "title": "Offset", + }, + }, + { + "name": "limit", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "maximum": 100, + "default": 100, + "title": "Limit", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/HeroPublic" + }, + "title": "Response Read Heroes Heroes Get", + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + }, + "/heroes/{hero_id}": { + "get": { + "summary": "Read Hero", + "operationId": "read_hero_heroes__hero_id__get", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroPublic" + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "patch": { + "summary": "Update Hero", + "operationId": "update_hero_heroes__hero_id__patch", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroUpdate" + } + } + }, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroPublic" + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "delete": { + "summary": "Delete Hero", + "operationId": "delete_hero_heroes__hero_id__delete", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + }, + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "HeroCreate": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "age": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Age", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Age", + } + ), + "secret_name": {"type": "string", "title": "Secret Name"}, + }, + "type": "object", + "required": ["name", "secret_name"], + "title": "HeroCreate", + }, + "HeroPublic": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "age": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Age", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Age", + } + ), + "id": {"type": "integer", "title": "Id"}, + }, + "type": "object", + "required": ["name", "id"], + "title": "HeroPublic", + }, + "HeroUpdate": { + "properties": { + "name": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Name", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Name", + } + ), + "age": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Age", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Age", + } + ), + "secret_name": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Secret Name", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Secret Name", + } + ), + }, + "type": "object", + "title": "HeroUpdate", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) From dbb4a91e121317da6e53e1c06aa02170c40cf78c Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 9 Oct 2024 19:45:08 +0000 Subject: [PATCH 054/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e34fd0df9..819d4b327 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Docs +* ✨ Add new tutorial for SQL databases with SQLModel. PR [#12285](https://github.com/fastapi/fastapi/pull/12285) by [@tiangolo](https://github.com/tiangolo). * 📝 Add External Link: How to profile a FastAPI asynchronous request. PR [#12389](https://github.com/fastapi/fastapi/pull/12389) by [@brouberol](https://github.com/brouberol). * 🔧 Remove `base_path` for `mdx_include` Markdown extension in MkDocs. PR [#12391](https://github.com/fastapi/fastapi/pull/12391) by [@tiangolo](https://github.com/tiangolo). * 📝 Update link to Swagger UI configuration docs. PR [#12264](https://github.com/fastapi/fastapi/pull/12264) by [@makisukurisu](https://github.com/makisukurisu). From 104dc0b8d86cb57165da919bc8cec2e225f6b61c Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 9 Oct 2024 22:11:46 +0200 Subject: [PATCH 055/932] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#12396)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/pre-commit/pre-commit-hooks: v4.6.0 → v5.0.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.6.0...v5.0.0) - [github.com/astral-sh/ruff-pre-commit: v0.6.8 → v0.6.9](https://github.com/astral-sh/ruff-pre-commit/compare/v0.6.8...v0.6.9) Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .pre-commit-config.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 48a7d495c..a62acccfe 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,7 +4,7 @@ default_language_version: python: python3.10 repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.6.0 + rev: v5.0.0 hooks: - id: check-added-large-files - id: check-toml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.6.8 + rev: v0.6.9 hooks: - id: ruff args: From 529155e72e196f82e0289f173a185e8ddb2888ce Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 9 Oct 2024 20:12:15 +0000 Subject: [PATCH 056/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 819d4b327..4fe600ed4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -40,6 +40,7 @@ hide: ### Internal +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12396](https://github.com/fastapi/fastapi/pull/12396) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 🔨 Add script to generate variants of files. PR [#12405](https://github.com/fastapi/fastapi/pull/12405) by [@tiangolo](https://github.com/tiangolo). * 🔧 Add speakeasy-api to `sponsors_badge.yml`. PR [#12404](https://github.com/fastapi/fastapi/pull/12404) by [@tiangolo](https://github.com/tiangolo). * ➕ Add docs dependency: markdown-include-variants. PR [#12399](https://github.com/fastapi/fastapi/pull/12399) by [@tiangolo](https://github.com/tiangolo). From 8ae4603d680f86ae1e5f96e58546dee4f543171f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Pacheco?= Date: Sat, 12 Oct 2024 05:36:32 -0400 Subject: [PATCH 057/932] =?UTF-8?q?=F0=9F=90=9B=20Remove=20`Required`=20sh?= =?UTF-8?q?adowing=20from=20fastapi=20using=20Pydantic=20v2=20(#12197)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sofie Van Landeghem --- .../query_params_str_validations/tutorial006d.py | 3 +-- .../tutorial006d_an.py | 3 +-- .../tutorial006d_an_py39.py | 3 +-- fastapi/_compat.py | 9 +++++---- fastapi/dependencies/utils.py | 14 ++++++++------ 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/docs_src/query_params_str_validations/tutorial006d.py b/docs_src/query_params_str_validations/tutorial006d.py index 42c5bf4eb..a8d69c889 100644 --- a/docs_src/query_params_str_validations/tutorial006d.py +++ b/docs_src/query_params_str_validations/tutorial006d.py @@ -1,11 +1,10 @@ from fastapi import FastAPI, Query -from pydantic import Required app = FastAPI() @app.get("/items/") -async def read_items(q: str = Query(default=Required, min_length=3)): +async def read_items(q: str = Query(default=..., min_length=3)): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006d_an.py b/docs_src/query_params_str_validations/tutorial006d_an.py index bc8283e15..ea3b02583 100644 --- a/docs_src/query_params_str_validations/tutorial006d_an.py +++ b/docs_src/query_params_str_validations/tutorial006d_an.py @@ -1,12 +1,11 @@ from fastapi import FastAPI, Query -from pydantic import Required from typing_extensions import Annotated app = FastAPI() @app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = Required): +async def read_items(q: Annotated[str, Query(min_length=3)] = ...): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006d_an_py39.py b/docs_src/query_params_str_validations/tutorial006d_an_py39.py index 035d9e3bd..687a9f544 100644 --- a/docs_src/query_params_str_validations/tutorial006d_an_py39.py +++ b/docs_src/query_params_str_validations/tutorial006d_an_py39.py @@ -1,13 +1,12 @@ from typing import Annotated from fastapi import FastAPI, Query -from pydantic import Required app = FastAPI() @app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = Required): +async def read_items(q: Annotated[str, Query(min_length=3)] = ...): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/fastapi/_compat.py b/fastapi/_compat.py index 4b07b44fa..56c5d744e 100644 --- a/fastapi/_compat.py +++ b/fastapi/_compat.py @@ -71,7 +71,7 @@ if PYDANTIC_V2: general_plain_validator_function as with_info_plain_validator_function, # noqa: F401 ) - Required = PydanticUndefined + RequiredParam = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient @@ -313,9 +313,10 @@ else: from pydantic.fields import ( # type: ignore[no-redef,attr-defined] ModelField as ModelField, # noqa: F401 ) - from pydantic.fields import ( # type: ignore[no-redef,attr-defined] - Required as Required, # noqa: F401 - ) + + # Keeping old "Required" functionality from Pydantic V1, without + # shadowing typing.Required. + RequiredParam: Any = Ellipsis # type: ignore[no-redef] from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Undefined as Undefined, ) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 813c74620..87653c80d 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -24,7 +24,7 @@ from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, - Required, + RequiredParam, Undefined, _regenerate_error_with_loc, copy_field_info, @@ -377,7 +377,9 @@ def analyze_param( field_info = copy_field_info( field_info=fastapi_annotation, annotation=use_annotation ) - assert field_info.default is Undefined or field_info.default is Required, ( + assert ( + field_info.default is Undefined or field_info.default is RequiredParam + ), ( f"`{field_info.__class__.__name__}` default value cannot be set in" f" `Annotated` for {param_name!r}. Set the default value with `=` instead." ) @@ -385,7 +387,7 @@ def analyze_param( assert not is_path_param, "Path parameters cannot have default values" field_info.default = value else: - field_info.default = Required + field_info.default = RequiredParam # Get Annotated Depends elif isinstance(fastapi_annotation, params.Depends): depends = fastapi_annotation @@ -434,9 +436,9 @@ def analyze_param( ), f"Cannot specify FastAPI annotation for type {type_annotation!r}" # Handle default assignations, neither field_info nor depends was not found in Annotated nor default value elif field_info is None and depends is None: - default_value = value if value is not inspect.Signature.empty else Required + default_value = value if value is not inspect.Signature.empty else RequiredParam if is_path_param: - # We might check here that `default_value is Required`, but the fact is that the same + # We might check here that `default_value is RequiredParam`, but the fact is that the same # parameter might sometimes be a path parameter and sometimes not. See # `tests/test_infer_param_optionality.py` for an example. field_info = params.Path(annotation=use_annotation) @@ -480,7 +482,7 @@ def analyze_param( type_=use_annotation_from_field_info, default=field_info.default, alias=alias, - required=field_info.default in (Required, Undefined), + required=field_info.default in (RequiredParam, Undefined), field_info=field_info, ) if is_path_param: From b29cf1621a9b9046ff68cf21c67f96953bc8feeb Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 12 Oct 2024 09:36:55 +0000 Subject: [PATCH 058/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4fe600ed4..d070a84a3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Fixes + +* 🐛 Remove `Required` shadowing from fastapi using Pydantic v2. PR [#12197](https://github.com/fastapi/fastapi/pull/12197) by [@pachewise](https://github.com/pachewise). + ### Refactors * ♻️ Update type annotations for improved `python-multipart`. PR [#12407](https://github.com/fastapi/fastapi/pull/12407) by [@tiangolo](https://github.com/tiangolo). From e049fc4ea15a7b844326efa545a7e370713f6612 Mon Sep 17 00:00:00 2001 From: Felix Fanghaenel <35657654+flxdot@users.noreply.github.com> Date: Sat, 12 Oct 2024 11:44:57 +0200 Subject: [PATCH 059/932] =?UTF-8?q?=F0=9F=90=9B=20Fix=20openapi=20generati?= =?UTF-8?q?on=20with=20responses=20kwarg=20(#10895)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: flxdot Co-authored-by: Sofie Van Landeghem Co-authored-by: Sławek Ehlert --- fastapi/routing.py | 4 ++- tests/test_computed_fields.py | 27 ++++++++++++-- ...t_openapi_separate_input_output_schemas.py | 36 ++++++++++++++++--- 3 files changed, 59 insertions(+), 8 deletions(-) diff --git a/fastapi/routing.py b/fastapi/routing.py index 86e303602..8ea4bb219 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -541,7 +541,9 @@ class APIRoute(routing.Route): additional_status_code ), f"Status code {additional_status_code} must not have a response body" response_name = f"Response_{additional_status_code}_{self.unique_id}" - response_field = create_model_field(name=response_name, type_=model) + response_field = create_model_field( + name=response_name, type_=model, mode="serialization" + ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], ModelField] = response_fields diff --git a/tests/test_computed_fields.py b/tests/test_computed_fields.py index 5286507b2..a1b412168 100644 --- a/tests/test_computed_fields.py +++ b/tests/test_computed_fields.py @@ -24,13 +24,18 @@ def get_client(): def read_root() -> Rectangle: return Rectangle(width=3, length=4) + @app.get("/responses", responses={200: {"model": Rectangle}}) + def read_responses() -> Rectangle: + return Rectangle(width=3, length=4) + client = TestClient(app) return client +@pytest.mark.parametrize("path", ["/", "/responses"]) @needs_pydanticv2 -def test_get(client: TestClient): - response = client.get("/") +def test_get(client: TestClient, path: str): + response = client.get(path) assert response.status_code == 200, response.text assert response.json() == {"width": 3, "length": 4, "area": 12} @@ -58,7 +63,23 @@ def test_openapi_schema(client: TestClient): } }, } - } + }, + "/responses": { + "get": { + "summary": "Read Responses", + "operationId": "read_responses_responses_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Rectangle"} + } + }, + } + }, + } + }, }, "components": { "schemas": { diff --git a/tests/test_openapi_separate_input_output_schemas.py b/tests/test_openapi_separate_input_output_schemas.py index aeb85f735..f7e045259 100644 --- a/tests/test_openapi_separate_input_output_schemas.py +++ b/tests/test_openapi_separate_input_output_schemas.py @@ -26,8 +26,8 @@ class Item(BaseModel): def get_app_client(separate_input_output_schemas: bool = True) -> TestClient: app = FastAPI(separate_input_output_schemas=separate_input_output_schemas) - @app.post("/items/") - def create_item(item: Item): + @app.post("/items/", responses={402: {"model": Item}}) + def create_item(item: Item) -> Item: return item @app.post("/items-list/") @@ -174,7 +174,23 @@ def test_openapi_schema(): "responses": { "200": { "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item-Output" + } + } + }, + }, + "402": { + "description": "Payment Required", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item-Output" + } + } + }, }, "422": { "description": "Validation Error", @@ -374,7 +390,19 @@ def test_openapi_schema_no_separate(): "responses": { "200": { "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + }, + "402": { + "description": "Payment Required", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, }, "422": { "description": "Validation Error", From f0be7686468229a7c9aa49c0c2cfff754c81dbdc Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 12 Oct 2024 09:45:17 +0000 Subject: [PATCH 060/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d070a84a3..07035bf94 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Fixes +* 🐛 Fix openapi generation with responses kwarg. PR [#10895](https://github.com/fastapi/fastapi/pull/10895) by [@flxdot](https://github.com/flxdot). * 🐛 Remove `Required` shadowing from fastapi using Pydantic v2. PR [#12197](https://github.com/fastapi/fastapi/pull/12197) by [@pachewise](https://github.com/pachewise). ### Refactors From 113da5b0a7f33be300b7fea8dddbe51ee7b96157 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 12 Oct 2024 11:51:09 +0200 Subject: [PATCH 061/932] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?5.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 07035bf94..4843370e7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.115.1 + ### Fixes * 🐛 Fix openapi generation with responses kwarg. PR [#10895](https://github.com/fastapi/fastapi/pull/10895) by [@flxdot](https://github.com/flxdot). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 7dd74c28f..09c8074ed 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.115.0" +__version__ = "0.115.1" from starlette import status as status From b77f2351d1561c0e9599205c3faaaed7b52c24fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 12 Oct 2024 11:59:01 +0200 Subject: [PATCH 062/932] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20Starlett?= =?UTF-8?q?e=20to=20`>=3D0.37.2,<0.41.0`=20(#12431)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 1be2817a1..c934356d8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,7 +41,7 @@ classifiers = [ "Topic :: Internet :: WWW/HTTP", ] dependencies = [ - "starlette>=0.37.2,<0.39.0", + "starlette>=0.37.2,<0.41.0", "pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0", "typing-extensions>=4.8.0", ] From 63c428fbf9363aaad0e967d30f8b199f5dc23e39 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 12 Oct 2024 09:59:23 +0000 Subject: [PATCH 063/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4843370e7..780f41ed3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Upgrades + +* ⬆️ Upgrade Starlette to `>=0.37.2,<0.41.0`. PR [#12431](https://github.com/fastapi/fastapi/pull/12431) by [@tiangolo](https://github.com/tiangolo). + ## 0.115.1 ### Fixes From 07684aea793d042fb5a12dde46dfe6d1e2196725 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 12 Oct 2024 12:00:47 +0200 Subject: [PATCH 064/932] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?5.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 780f41ed3..3ba765b08 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.115.2 + ### Upgrades * ⬆️ Upgrade Starlette to `>=0.37.2,<0.41.0`. PR [#12431](https://github.com/fastapi/fastapi/pull/12431) by [@tiangolo](https://github.com/tiangolo). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 09c8074ed..77b52f35b 100644 --- a/fastapi/__init__.py +++ b/fastapi/__init__.py @@ -1,6 +1,6 @@ """FastAPI framework, high performance, easy to learn, fast to code, ready for production""" -__version__ = "0.115.1" +__version__ = "0.115.2" from starlette import status as status From 91672fb9edf4a504a0106b5396f9be16ffbf40b1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 12 Oct 2024 12:29:31 +0200 Subject: [PATCH 065/932] =?UTF-8?q?=E2=AC=86=20Update=20httpx=20requiremen?= =?UTF-8?q?t=20from=20<0.25.0,>=3D0.23.0=20to=20>=3D0.23.0,<0.28.0=20(#115?= =?UTF-8?q?09)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Updates the requirements on [httpx](https://github.com/encode/httpx) to permit the latest version. - [Release notes](https://github.com/encode/httpx/releases) - [Changelog](https://github.com/encode/httpx/blob/master/CHANGELOG.md) - [Commits](https://github.com/encode/httpx/compare/0.23.0...0.27.0) --- updated-dependencies: - dependency-name: httpx dependency-type: direct:production ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-docs-tests.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs-tests.txt b/requirements-docs-tests.txt index 40b956e51..331d2a5b3 100644 --- a/requirements-docs-tests.txt +++ b/requirements-docs-tests.txt @@ -1,4 +1,4 @@ # For mkdocstrings and tests -httpx >=0.23.0,<0.25.0 +httpx >=0.23.0,<0.28.0 # For linting and generating docs versions ruff ==0.6.4 From 3347f0dde58899e9d934b9f25fcd4f0120a002da Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 12 Oct 2024 10:29:52 +0000 Subject: [PATCH 066/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3ba765b08..90e45367b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Internal + +* ⬆ Update httpx requirement from <0.25.0,>=0.23.0 to >=0.23.0,<0.28.0. PR [#11509](https://github.com/fastapi/fastapi/pull/11509) by [@dependabot[bot]](https://github.com/apps/dependabot). + ## 0.115.2 ### Upgrades From a30eb6f5179974f8e6a809a94094f04a787d5aa7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 12 Oct 2024 14:27:19 +0200 Subject: [PATCH 067/932] =?UTF-8?q?=F0=9F=91=B7=20Use=20uv=20in=20CI=20(#1?= =?UTF-8?q?2281)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build-docs.yml | 40 +++++++++------- .github/workflows/deploy-docs.yml | 18 ++++--- .github/workflows/label-approved.yml | 21 ++++++++- .github/workflows/notify-translations.yml | 16 +++++++ .github/workflows/smokeshow.yml | 16 +++++-- .github/workflows/test.yml | 57 +++++++++++++---------- requirements-github-actions.txt | 1 + 7 files changed, 115 insertions(+), 54 deletions(-) diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index 52c34a49e..dd11727c7 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -7,6 +7,10 @@ on: types: - opened - synchronize + +env: + UV_SYSTEM_PYTHON: 1 + jobs: changes: runs-on: ubuntu-latest @@ -48,18 +52,20 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - - uses: actions/cache@v4 - id: cache + - name: Setup uv + uses: astral-sh/setup-uv@v3 with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-insiders.txt', 'requirements-docs-tests.txt') }}-v08 + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml - name: Install docs extras - if: steps.cache.outputs.cache-hit != 'true' - run: pip install -r requirements-docs.txt + run: uv pip install -r requirements-docs.txt # Install MkDocs Material Insiders here just to put it in the cache for the rest of the steps - name: Install Material for MkDocs Insiders - if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) && steps.cache.outputs.cache-hit != 'true' - run: pip install -r requirements-docs-insiders.txt + if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) + run: uv pip install -r requirements-docs-insiders.txt env: TOKEN: ${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }} - name: Verify Docs @@ -88,17 +94,19 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - - uses: actions/cache@v4 - id: cache + - name: Setup uv + uses: astral-sh/setup-uv@v3 with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-insiders.txt', 'requirements-docs-tests.txt') }}-v08 + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml - name: Install docs extras - if: steps.cache.outputs.cache-hit != 'true' - run: pip install -r requirements-docs.txt + run: uv pip install -r requirements-docs.txt - name: Install Material for MkDocs Insiders - if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) && steps.cache.outputs.cache-hit != 'true' - run: pip install -r requirements-docs-insiders.txt + if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) + run: uv pip install -r requirements-docs-insiders.txt env: TOKEN: ${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }} - name: Update Languages diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 22dc89dff..2fd46df6b 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -12,6 +12,9 @@ permissions: pull-requests: write statuses: write +env: + UV_SYSTEM_PYTHON: 1 + jobs: deploy-docs: runs-on: ubuntu-latest @@ -25,21 +28,22 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - - uses: actions/cache@v4 - id: cache + - name: Setup uv + uses: astral-sh/setup-uv@v3 with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-github-actions-${{ env.pythonLocation }}-${{ hashFiles('requirements-github-actions.txt') }}-v01 + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml - name: Install GitHub Actions dependencies - if: steps.cache.outputs.cache-hit != 'true' - run: pip install -r requirements-github-actions.txt + run: uv pip install -r requirements-github-actions.txt - name: Deploy Docs Status Pending run: python ./scripts/deploy_docs_status.py env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} COMMIT_SHA: ${{ github.event.workflow_run.head_sha }} RUN_ID: ${{ github.run_id }} - - name: Clean site run: | rm -rf ./site diff --git a/.github/workflows/label-approved.yml b/.github/workflows/label-approved.yml index 0470fb606..e44584cf1 100644 --- a/.github/workflows/label-approved.yml +++ b/.github/workflows/label-approved.yml @@ -8,6 +8,9 @@ on: permissions: pull-requests: write +env: + UV_SYSTEM_PYTHON: 1 + jobs: label-approved: if: github.repository_owner == 'fastapi' @@ -19,8 +22,22 @@ jobs: run: echo "$GITHUB_CONTEXT" - uses: docker://tiangolo/label-approved:0.0.4 with: - token: ${{ secrets.GITHUB_TOKEN }} - config: > + python-version: "3.11" + - name: Setup uv + uses: astral-sh/setup-uv@v3 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - name: Install GitHub Actions dependencies + run: uv pip install -r requirements-github-actions.txt + - name: Label Approved + run: python ./scripts/label_approved.py + env: + TOKEN: ${{ secrets.GITHUB_TOKEN }} + CONFIG: > { "approved-1": { diff --git a/.github/workflows/notify-translations.yml b/.github/workflows/notify-translations.yml index 4787f3ddd..98aa41e5a 100644 --- a/.github/workflows/notify-translations.yml +++ b/.github/workflows/notify-translations.yml @@ -18,6 +18,9 @@ on: permissions: discussions: write +env: + UV_SYSTEM_PYTHON: 1 + jobs: notify-translations: runs-on: ubuntu-latest @@ -27,6 +30,19 @@ jobs: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Setup uv + uses: astral-sh/setup-uv@v3 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml # Allow debugging with tmate - name: Setup tmate session uses: mxschmitt/action-tmate@v3 diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index d3a975df5..e9aa1093f 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -8,6 +8,9 @@ on: permissions: statuses: write +env: + UV_SYSTEM_PYTHON: 1 + jobs: smokeshow: if: ${{ github.event.workflow_run.conclusion == 'success' }} @@ -21,16 +24,21 @@ jobs: - uses: actions/setup-python@v5 with: python-version: '3.9' - - - run: pip install smokeshow - + - name: Setup uv + uses: astral-sh/setup-uv@v3 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - run: uv pip install -r requirements-github-actions.txt - uses: actions/download-artifact@v4 with: name: coverage-html path: htmlcov github-token: ${{ secrets.GITHUB_TOKEN }} run-id: ${{ github.event.workflow_run.id }} - - run: smokeshow upload htmlcov env: SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fb4b083c4..643037a12 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -12,6 +12,9 @@ on: # cron every week on monday - cron: "0 0 * * 1" +env: + UV_SYSTEM_PYTHON: 1 + jobs: lint: runs-on: ubuntu-latest @@ -25,19 +28,18 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - # Issue ref: https://github.com/actions/setup-python/issues/436 - # cache: "pip" - # cache-dependency-path: pyproject.toml - - uses: actions/cache@v4 - id: cache + - name: Setup uv + uses: astral-sh/setup-uv@v3 with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-${{ env.pythonLocation }}-pydantic-v2-${{ hashFiles('pyproject.toml', 'requirements-tests.txt', 'requirements-docs-tests.txt') }}-test-v08 + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml - name: Install Dependencies - if: steps.cache.outputs.cache-hit != 'true' - run: pip install -r requirements-tests.txt + run: uv pip install -r requirements-tests.txt - name: Install Pydantic v2 - run: pip install --upgrade "pydantic>=2.0.2,<3.0.0" + run: uv pip install --upgrade "pydantic>=2.0.2,<3.0.0" - name: Lint run: bash scripts/lint.sh @@ -63,23 +65,22 @@ jobs: uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - # Issue ref: https://github.com/actions/setup-python/issues/436 - # cache: "pip" - # cache-dependency-path: pyproject.toml - - uses: actions/cache@v4 - id: cache + - name: Setup uv + uses: astral-sh/setup-uv@v3 with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ matrix.pydantic-version }}-${{ hashFiles('pyproject.toml', 'requirements-tests.txt', 'requirements-docs-tests.txt') }}-test-v08 + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml - name: Install Dependencies - if: steps.cache.outputs.cache-hit != 'true' - run: pip install -r requirements-tests.txt + run: uv pip install -r requirements-tests.txt - name: Install Pydantic v1 if: matrix.pydantic-version == 'pydantic-v1' - run: pip install "pydantic>=1.10.0,<2.0.0" + run: uv pip install "pydantic>=1.10.0,<2.0.0" - name: Install Pydantic v2 if: matrix.pydantic-version == 'pydantic-v2' - run: pip install --upgrade "pydantic>=2.0.2,<3.0.0" + run: uv pip install --upgrade "pydantic>=2.0.2,<3.0.0" - run: mkdir coverage - name: Test run: bash scripts/test.sh @@ -105,16 +106,22 @@ jobs: - uses: actions/setup-python@v5 with: python-version: '3.8' - # Issue ref: https://github.com/actions/setup-python/issues/436 - # cache: "pip" - # cache-dependency-path: pyproject.toml + - name: Setup uv + uses: astral-sh/setup-uv@v3 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - name: Install Dependencies + run: uv pip install -r requirements-tests.txt - name: Get coverage files uses: actions/download-artifact@v4 with: pattern: coverage-* path: coverage merge-multiple: true - - run: pip install coverage[toml] - run: ls -la coverage - run: coverage combine coverage - run: coverage report diff --git a/requirements-github-actions.txt b/requirements-github-actions.txt index 559dc06fb..a6dace544 100644 --- a/requirements-github-actions.txt +++ b/requirements-github-actions.txt @@ -2,3 +2,4 @@ PyGithub>=2.3.0,<3.0.0 pydantic>=2.5.3,<3.0.0 pydantic-settings>=2.1.0,<3.0.0 httpx>=0.27.0,<0.28.0 +smokeshow From ac6c08c71f816cfa60502bd410deca75f0b580ae Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 12 Oct 2024 12:28:10 +0000 Subject: [PATCH 068/932] =?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 90e45367b..30f98970a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Internal +* 👷 Use uv in CI. PR [#12281](https://github.com/fastapi/fastapi/pull/12281) by [@tiangolo](https://github.com/tiangolo). * ⬆ Update httpx requirement from <0.25.0,>=0.23.0 to >=0.23.0,<0.28.0. PR [#11509](https://github.com/fastapi/fastapi/pull/11509) by [@dependabot[bot]](https://github.com/apps/dependabot). ## 0.115.2 From 495d90161bae81d7e037b6c7998a9ab6e89d58a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 12 Oct 2024 15:47:46 +0200 Subject: [PATCH 069/932] =?UTF-8?q?=F0=9F=91=B7=20Fix=20smokeshow,=20check?= =?UTF-8?q?out=20files=20on=20CI=20(#12434)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/smokeshow.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index e9aa1093f..daff8e244 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -21,6 +21,7 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: '3.9' From 84ef149f838ab932f4ade3f1adbe566cece1b4fb Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 12 Oct 2024 13:49:27 +0000 Subject: [PATCH 070/932] =?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 30f98970a..e0988f461 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Internal +* 👷 Fix smokeshow, checkout files on CI. PR [#12434](https://github.com/fastapi/fastapi/pull/12434) by [@tiangolo](https://github.com/tiangolo). * 👷 Use uv in CI. PR [#12281](https://github.com/fastapi/fastapi/pull/12281) by [@tiangolo](https://github.com/tiangolo). * ⬆ Update httpx requirement from <0.25.0,>=0.23.0 to >=0.23.0,<0.28.0. PR [#11509](https://github.com/fastapi/fastapi/pull/11509) by [@dependabot[bot]](https://github.com/apps/dependabot). From 6384f730f7e672d4cea8c951dfa9c9e8bb3481f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 12 Oct 2024 15:58:30 +0200 Subject: [PATCH 071/932] =?UTF-8?q?=F0=9F=91=B7=20Refactor=20label-approve?= =?UTF-8?q?d,=20make=20it=20an=20internal=20script=20instead=20of=20an=20e?= =?UTF-8?q?xternal=20GitHub=20Action=20(#12280)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/label-approved.yml | 4 +- scripts/label_approved.py | 60 ++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 scripts/label_approved.py diff --git a/.github/workflows/label-approved.yml b/.github/workflows/label-approved.yml index e44584cf1..11176bed8 100644 --- a/.github/workflows/label-approved.yml +++ b/.github/workflows/label-approved.yml @@ -20,7 +20,9 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: docker://tiangolo/label-approved:0.0.4 + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 with: python-version: "3.11" - name: Setup uv diff --git a/scripts/label_approved.py b/scripts/label_approved.py new file mode 100644 index 000000000..271444504 --- /dev/null +++ b/scripts/label_approved.py @@ -0,0 +1,60 @@ +import logging +from typing import Literal + +from github import Github +from github.PullRequestReview import PullRequestReview +from pydantic import BaseModel, SecretStr +from pydantic_settings import BaseSettings + + +class LabelSettings(BaseModel): + await_label: str | None = None + number: int + + +default_config = {"approved-2": LabelSettings(await_label="awaiting-review", number=2)} + + +class Settings(BaseSettings): + github_repository: str + token: SecretStr + debug: bool | None = False + config: dict[str, LabelSettings] | Literal[""] = default_config + + +settings = Settings() +if settings.debug: + logging.basicConfig(level=logging.DEBUG) +else: + logging.basicConfig(level=logging.INFO) +logging.debug(f"Using config: {settings.json()}") +g = Github(settings.token.get_secret_value()) +repo = g.get_repo(settings.github_repository) +for pr in repo.get_pulls(state="open"): + logging.info(f"Checking PR: #{pr.number}") + pr_labels = list(pr.get_labels()) + pr_label_by_name = {label.name: label for label in pr_labels} + reviews = list(pr.get_reviews()) + review_by_user: dict[str, PullRequestReview] = {} + for review in reviews: + if review.user.login in review_by_user: + stored_review = review_by_user[review.user.login] + if review.submitted_at >= stored_review.submitted_at: + review_by_user[review.user.login] = review + else: + review_by_user[review.user.login] = review + approved_reviews = [ + review for review in review_by_user.values() if review.state == "APPROVED" + ] + config = settings.config or default_config + for approved_label, conf in config.items(): + logging.debug(f"Processing config: {conf.json()}") + if conf.await_label is None or (conf.await_label in pr_label_by_name): + logging.debug(f"Processable PR: {pr.number}") + if len(approved_reviews) >= conf.number: + logging.info(f"Adding label to PR: {pr.number}") + pr.add_to_labels(approved_label) + if conf.await_label: + logging.info(f"Removing label from PR: {pr.number}") + pr.remove_from_labels(conf.await_label) +logging.info("Finished") From 766a14ddff6d710d483ba8cd06c3e7d05bd459f0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 12 Oct 2024 13:59:03 +0000 Subject: [PATCH 072/932] =?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 e0988f461..f94faf4b7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Internal +* 👷 Refactor label-approved, make it an internal script instead of an external GitHub Action. PR [#12280](https://github.com/fastapi/fastapi/pull/12280) by [@tiangolo](https://github.com/tiangolo). * 👷 Fix smokeshow, checkout files on CI. PR [#12434](https://github.com/fastapi/fastapi/pull/12434) by [@tiangolo](https://github.com/tiangolo). * 👷 Use uv in CI. PR [#12281](https://github.com/fastapi/fastapi/pull/12281) by [@tiangolo](https://github.com/tiangolo). * ⬆ Update httpx requirement from <0.25.0,>=0.23.0 to >=0.23.0,<0.28.0. PR [#11509](https://github.com/fastapi/fastapi/pull/11509) by [@dependabot[bot]](https://github.com/apps/dependabot). From b887d434dbe760db1f1989dd410c9624cb904d43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Paulo=20Falc=C3=A3o?= <72179636+Paulofalcao2002@users.noreply.github.com> Date: Mon, 14 Oct 2024 06:15:24 -0300 Subject: [PATCH 073/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/response-cookies.md`=20(#?= =?UTF-8?q?12417)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/response-cookies.md | 55 +++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 docs/pt/docs/advanced/response-cookies.md diff --git a/docs/pt/docs/advanced/response-cookies.md b/docs/pt/docs/advanced/response-cookies.md new file mode 100644 index 000000000..d0821b5b2 --- /dev/null +++ b/docs/pt/docs/advanced/response-cookies.md @@ -0,0 +1,55 @@ +# Cookies de Resposta + +## Usando um parâmetro `Response` + +Você pode declarar um parâmetro do tipo `Response` na sua *função de operação de rota*. + +E então você pode definir cookies nesse objeto de resposta *temporário*. + +```Python hl_lines="1 8-9" +{!../../docs_src/response_cookies/tutorial002.py!} +``` + +Em seguida, você pode retornar qualquer objeto que precise, como normalmente faria (um `dict`, um modelo de banco de dados, etc). + +E se você declarou um `response_model`, ele ainda será usado para filtrar e converter o objeto que você retornou. + +**FastAPI** usará essa resposta *temporária* para extrair os cookies (também os cabeçalhos e código de status) e os colocará na resposta final que contém o valor que você retornou, filtrado por qualquer `response_model`. + +Você também pode declarar o parâmetro `Response` em dependências e definir cookies (e cabeçalhos) nelas. + +## Retornando uma `Response` diretamente + +Você também pode criar cookies ao retornar uma `Response` diretamente no seu código. + +Para fazer isso, você pode criar uma resposta como descrito em [Retornando uma Resposta Diretamente](response-directly.md){.internal-link target=_blank}. + +Então, defina os cookies nela e a retorne: + +```Python hl_lines="10-12" +{!../../docs_src/response_cookies/tutorial001.py!} +``` + +/// tip | Dica + +Lembre-se de que se você retornar uma resposta diretamente em vez de usar o parâmetro `Response`, FastAPI a retornará diretamente. + +Portanto, você terá que garantir que seus dados sejam do tipo correto. E.g. será compatível com JSON se você estiver retornando um `JSONResponse`. + +E também que você não esteja enviando nenhum dado que deveria ter sido filtrado por um `response_model`. + +/// + +### Mais informações + +/// note | "Detalhes Técnicos" + +Você também poderia usar `from starlette.responses import Response` ou `from starlette.responses import JSONResponse`. + +**FastAPI** fornece as mesmas `starlette.responses` em `fastapi.responses` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vem diretamente do Starlette. + +E como o `Response` pode ser usado frequentemente para definir cabeçalhos e cookies, o **FastAPI** também o fornece em `fastapi.Response`. + +/// + +Para ver todos os parâmetros e opções disponíveis, verifique a documentação no Starlette. From 0e4dc88bd7487c05d8269b6ae3bb0330614c5549 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 14 Oct 2024 09:15:46 +0000 Subject: [PATCH 074/932] =?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 f94faf4b7..5e33cb95d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Translations + +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-cookies.md`. PR [#12417](https://github.com/fastapi/fastapi/pull/12417) by [@Paulofalcao2002](https://github.com/Paulofalcao2002). + ### Internal * 👷 Refactor label-approved, make it an internal script instead of an external GitHub Action. PR [#12280](https://github.com/fastapi/fastapi/pull/12280) by [@tiangolo](https://github.com/tiangolo). From d4e183da3f6a1476131cbd91948172fdfad8a993 Mon Sep 17 00:00:00 2001 From: Anderson Rocha Date: Mon, 14 Oct 2024 10:16:06 +0100 Subject: [PATCH 075/932] =?UTF-8?q?=20=F0=9F=8C=90=20Add=20Portuguese=20tr?= =?UTF-8?q?anslation=20for=20`docs/pt/docs/tutorial/body-updates.md`=20(#1?= =?UTF-8?q?2381)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/body-updates.md | 204 ++++++++++++++++++++++++++ 1 file changed, 204 insertions(+) create mode 100644 docs/pt/docs/tutorial/body-updates.md diff --git a/docs/pt/docs/tutorial/body-updates.md b/docs/pt/docs/tutorial/body-updates.md new file mode 100644 index 000000000..1a0455c1c --- /dev/null +++ b/docs/pt/docs/tutorial/body-updates.md @@ -0,0 +1,204 @@ +# Corpo - Atualizações + +## Atualização de dados existentes com `PUT` + +Para atualizar um item, você pode usar a operação HTTP `PUT`. + +Você pode usar `jsonable_encoder` para converter os dados de entrada em dados que podem ser armazenados como JSON (por exemplo, com um banco de dados NoSQL). Por exemplo, convertendo `datetime` em `str`. + +//// tab | Python 3.10+ + +```Python hl_lines="28-33" +{!> ../../../docs_src/body_updates/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="30-35" +{!> ../../../docs_src/body_updates/tutorial001.py!} +``` + +//// + +`PUT` é usado para receber dados que devem substituir os dados existentes. + +### Aviso sobre a substituição + +Isso significa que, se você quiser atualizar o item `bar` usando `PUT` com um corpo contendo: + +```Python +{ + "name": "Barz", + "price": 3, + "description": None, +} +``` + +Como ele não inclui o atributo já armazenado `"tax": 20.2`, o modelo de entrada assumiria o valor padrão de `"tax": 10.5`. + +E os dados seriam salvos com esse "novo" `tax` de `10.5`. + +## Atualizações parciais com `PATCH` + +Você também pode usar a operação HTTP `PATCH` para *atualizar* parcialmente os dados. + +Isso significa que você pode enviar apenas os dados que deseja atualizar, deixando o restante intacto. + +/// note | Nota + +`PATCH` é menos comumente usado e conhecido do que `PUT`. + +E muitas equipes usam apenas `PUT`, mesmo para atualizações parciais. + +Você é **livre** para usá-los como preferir, **FastAPI** não impõe restrições. + +Mas este guia te dá uma ideia de como eles são destinados a serem usados. + +/// + +### Usando o parâmetro `exclude_unset` do Pydantic + +Se você quiser receber atualizações parciais, é muito útil usar o parâmetro `exclude_unset` no método `.model_dump()` do modelo do Pydantic. + +Como `item.model_dump(exclude_unset=True)`. + +/// info | Informação + +No Pydantic v1, o método que era chamado `.dict()` e foi depreciado (mas ainda suportado) no Pydantic v2. Agora, deve-se usar o método `.model_dump()`. + +Os exemplos aqui usam `.dict()` para compatibilidade com o Pydantic v1, mas você deve usar `.model_dump()` a partir do Pydantic v2. + +/// + +Isso gera um `dict` com apenas os dados definidos ao criar o modelo `item`, excluindo os valores padrão. + +Então, você pode usar isso para gerar um `dict` com apenas os dados definidos (enviados na solicitação), omitindo valores padrão: + +//// tab | Python 3.10+ + +```Python hl_lines="32" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="34" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` + +//// + +### Usando o parâmetro `update` do Pydantic + +Agora, você pode criar uma cópia do modelo existente usando `.model_copy()`, e passar o parâmetro `update` com um `dict` contendo os dados para atualizar. + +/// info | Informação + +No Pydantic v1, o método era chamado `.copy()`, ele foi depreciado (mas ainda suportado) no Pydantic v2, e renomeado para `.model_copy()`. + +Os exemplos aqui usam `.copy()` para compatibilidade com o Pydantic v1, mas você deve usar `.model_copy()` com o Pydantic v2. + +/// + +Como `stored_item_model.model_copy(update=update_data)`: + +//// tab | Python 3.10+ + +```Python hl_lines="33" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="35" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` + +//// + +### Recapitulando as atualizações parciais + +Resumindo, para aplicar atualizações parciais você pode: + +* (Opcionalmente) usar `PATCH` em vez de `PUT`. +* Recuperar os dados armazenados. +* Colocar esses dados em um modelo do Pydantic. +* Gerar um `dict` sem valores padrão a partir do modelo de entrada (usando `exclude_unset`). + * Dessa forma, você pode atualizar apenas os valores definidos pelo usuário, em vez de substituir os valores já armazenados com valores padrão em seu modelo. +* Criar uma cópia do modelo armazenado, atualizando seus atributos com as atualizações parciais recebidas (usando o parâmetro `update`). +* Converter o modelo copiado em algo que possa ser armazenado no seu banco de dados (por exemplo, usando o `jsonable_encoder`). + * Isso é comparável ao uso do método `.model_dump()`, mas garante (e converte) os valores para tipos de dados que possam ser convertidos em JSON, por exemplo, `datetime` para `str`. +* Salvar os dados no seu banco de dados. +* Retornar o modelo atualizado. + +//// tab | Python 3.10+ + +```Python hl_lines="28-35" +{!> ../../../docs_src/body_updates/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="30-37" +{!> ../../../docs_src/body_updates/tutorial002.py!} +``` + +//// + +/// tip | Dica + +Você pode realmente usar essa mesma técnica com uma operação HTTP `PUT`. + +Mas o exemplo aqui usa `PATCH` porque foi criado para esses casos de uso. + +/// + +/// note | Nota + +Observe que o modelo de entrada ainda é validado. + +Portanto, se você quiser receber atualizações parciais que possam omitir todos os atributos, precisará ter um modelo com todos os atributos marcados como opcionais (com valores padrão ou `None`). + +Para distinguir os modelos com todos os valores opcionais para **atualizações** e modelos com valores obrigatórios para **criação**, você pode usar as ideias descritas em [Modelos Adicionais](extra-models.md){.internal-link target=_blank}. + +/// From 7358ed246e1dd722f5b6b376c6ba64883a4bd039 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 14 Oct 2024 09:17:01 +0000 Subject: [PATCH 076/932] =?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 5e33cb95d..75166bcd5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/body-updates.md`. PR [#12381](https://github.com/fastapi/fastapi/pull/12381) by [@andersonrocha0](https://github.com/andersonrocha0). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-cookies.md`. PR [#12417](https://github.com/fastapi/fastapi/pull/12417) by [@Paulofalcao2002](https://github.com/Paulofalcao2002). ### Internal From 5f998ee55acbd344509a2775968d6bc703f141f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 14 Oct 2024 12:51:58 +0200 Subject: [PATCH 077/932] =?UTF-8?q?=F0=9F=94=A7=20Update=20team,=20include?= =?UTF-8?q?=20YuriiMotov=20=F0=9F=9A=80=20(#12453)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/members.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/en/data/members.yml b/docs/en/data/members.yml index 0069f8c75..a3a6b912d 100644 --- a/docs/en/data/members.yml +++ b/docs/en/data/members.yml @@ -11,6 +11,9 @@ members: - login: svlandeg avatar_url: https://avatars.githubusercontent.com/u/8796347 url: https://github.com/svlandeg +- login: YuriiMotov + avatar_url: https://avatars.githubusercontent.com/u/109919500 + url: https://github.com/YuriiMotov - login: estebanx64 avatar_url: https://avatars.githubusercontent.com/u/10840422 url: https://github.com/estebanx64 From 38f65c033f779b7f355661ea83c395d66c1bed7b Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 14 Oct 2024 10:52:26 +0000 Subject: [PATCH 078/932] =?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 75166bcd5..08f1652f5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Internal +* 🔧 Update team, include YuriiMotov 🚀. PR [#12453](https://github.com/fastapi/fastapi/pull/12453) by [@tiangolo](https://github.com/tiangolo). * 👷 Refactor label-approved, make it an internal script instead of an external GitHub Action. PR [#12280](https://github.com/fastapi/fastapi/pull/12280) by [@tiangolo](https://github.com/tiangolo). * 👷 Fix smokeshow, checkout files on CI. PR [#12434](https://github.com/fastapi/fastapi/pull/12434) by [@tiangolo](https://github.com/tiangolo). * 👷 Use uv in CI. PR [#12281](https://github.com/fastapi/fastapi/pull/12281) by [@tiangolo](https://github.com/tiangolo). From 7148584ac47697d50988a1cd0dad27991a29c036 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Mon, 14 Oct 2024 11:57:32 -0300 Subject: [PATCH 079/932] =?UTF-8?q?=F0=9F=8C=90=20Remove=20Portuguese=20tr?= =?UTF-8?q?anslation=20for=20`docs/pt/docs/deployment.md`=20(#12427)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/deployment.md | 414 ------------------------------------- 1 file changed, 414 deletions(-) delete mode 100644 docs/pt/docs/deployment.md diff --git a/docs/pt/docs/deployment.md b/docs/pt/docs/deployment.md deleted file mode 100644 index 6874a2529..000000000 --- a/docs/pt/docs/deployment.md +++ /dev/null @@ -1,414 +0,0 @@ -# Implantação - -Implantar uma aplicação **FastAPI** é relativamente fácil. - -Existem vários modos de realizar o _deploy_ dependendo de seu caso de uso específico e as ferramentas que você utiliza. - -Você verá mais sobre alguns modos de fazer o _deploy_ nas próximas seções. - -## Versões do FastAPI - -**FastAPI** já está sendo utilizado em produção em muitas aplicações e sistemas. E a cobertura de teste é mantida a 100%. Mas seu desenvolvimento continua andando rapidamente. - -Novos recursos são adicionados frequentemente, _bugs_ são corrigidos regularmente, e o código está continuamente melhorando. - -É por isso que as versões atuais estão ainda no `0.x.x`, isso reflete que cada versão poderia ter potencialmente alterações que podem quebrar. Isso segue as convenções de Versionamento Semântico. - -Você pode criar aplicações para produção com **FastAPI** bem agora (e você provavelmente já faça isso por um tempo), você tem que ter certeza de utilizar uma versão que funcione corretamente com o resto do seu código. - -### Anote sua versão `fastapi` - -A primeira coisa que você deve fazer é "fixar" a versão do **FastAPI** que está utilizando para a última versão específica que você sabe que funciona corretamente para a sua aplicação. - -Por exemplo, vamos dizer que você esteja utilizando a versão `0.45.0` no seu _app_. - -Se você usa um arquivo `requirements.txt`, dá para especificar a versão assim: - -```txt -fastapi==0.45.0 -``` - -isso significa que você pode usar exatamente a versão `0.45.0`. - -Ou você poderia fixar assim: - -```txt -fastapi>=0.45.0,<0.46.0 -``` - -o que significa que você pode usar as versões `0.45.0` ou acima, mas menor que `0.46.0`. Por exemplo, a versão `0.45.2` poderia ser aceita. - -Se você usa qualquer outra ferramenta para gerenciar suas instalações, como Poetry, Pipenv ou outro, todos terão um modo que você possa usar para definir versões específicas para seus pacotes. - -### Versões disponíveis - -Você pode ver as versões disponíveis (por exemplo, para verificar qual é a versão atual) nas [Notas de Lançamento](release-notes.md){.internal-link target=_blank}. - -### Sobre as versões - -Seguindo as convenções do Versionamento Semântico, qualquer versão abaixo de `1.0.0` pode potencialmente adicionar mudanças que quebrem. - -FastAPI também segue a convenção que qualquer versão de _"PATCH"_ seja para ajustes de _bugs_ e mudanças que não quebrem a aplicação. - -/// tip - -O _"PATCH"_ é o último número, por exemplo, em `0.2.3`, a versão do _PATCH_ é `3`. - -/// - -Então, você poderia ser capaz de fixar para uma versão como: - -```txt -fastapi>=0.45.0,<0.46.0 -``` - -Mudanças que quebram e novos recursos são adicionados em versões _"MINOR"_. - -/// tip - -O _"MINOR"_ é o número do meio, por exemplo, em `0.2.3`, a versão _MINOR_ é `2`. - -/// - -### Atualizando as versões FastAPI - -Você pode adicionar testes em sua aplicação. - -Com o **FastAPI** é muito fácil (graças ao Starlette), verifique a documentação: [Testando](tutorial/testing.md){.internal-link target=_blank} - -Após você ter os testes, então você pode fazer o _upgrade_ da versão **FastAPI** para uma mais recente, e ter certeza que todo seu código esteja funcionando corretamente rodando seus testes. - -Se tudo estiver funcionando, ou após você fazer as alterações necessárias, e todos seus testes estiverem passando, então você poderá fixar o `fastapi` para a versão mais recente. - -### Sobre Starlette - -Você não deve fixar a versão do `starlette`. - -Versões diferentes do **FastAPI** irão utilizar uma versão mais nova específica do Starlette. - -Então, você pode deixar que o **FastAPI** use a versão correta do Starlette. - -### Sobre Pydantic - -Pydantic inclui os testes para **FastAPI** em seus próprios testes, então novas versões do Pydantic (acima de `1.0.0`) são sempre compatíveis com FastAPI. - -Você pode fixar o Pydantic para qualquer versão acima de `1.0.0` e abaixo de `2.0.0` que funcionará. - -Por exemplo: - -```txt -pydantic>=1.2.0,<2.0.0 -``` - -## Docker - -Nessa seção você verá instruções e _links_ para guias de saber como: - -* Fazer uma imagem/container da sua aplicação **FastAPI** com máxima performance. Em aproximadamente **5 min**. -* (Opcionalmente) entender o que você, como desenvolvedor, precisa saber sobre HTTPS. -* Inicializar um _cluster_ Docker Swarm Mode com HTTPS automático, mesmo em um simples servidor de $5 dólares/mês. Em aproximadamente **20 min**. -* Gere e implante uma aplicação **FastAPI** completa, usando seu _cluster_ Docker Swarm, com HTTPS etc. Em aproxiamadamente **10 min**. - -Você pode usar **Docker** para implantação. Ele tem várias vantagens como segurança, replicabilidade, desenvolvimento simplificado etc. - -Se você está usando Docker, você pode utilizar a imagem Docker oficial: - -### tiangolo/uvicorn-gunicorn-fastapi - -Essa imagem tem um mecanismo incluído de "auto-ajuste", para que você possa apenas adicionar seu código e ter uma alta performance automaticamente. E sem fazer sacrifícios. - -Mas você pode ainda mudar e atualizar todas as configurações com variáveis de ambiente ou arquivos de configuração. - -/// tip - -Para ver todas as configurações e opções, vá para a página da imagem do Docker: tiangolo/uvicorn-gunicorn-fastapi. - -/// - -### Crie um `Dockerfile` - -* Vá para o diretório de seu projeto. -* Crie um `Dockerfile` com: - -```Dockerfile -FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7 - -COPY ./app /app -``` - -#### Grandes aplicações - -Se você seguiu a seção sobre criação de [Grandes Aplicações com Múltiplos Arquivos](tutorial/bigger-applications.md){.internal-link target=_blank}, seu `Dockerfile` poderia parecer como: - -```Dockerfile -FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7 - -COPY ./app /app/app -``` - -#### Raspberry Pi e outras arquiteturas - -Se você estiver rodando Docker em um Raspberry Pi (que possui um processador ARM) ou qualquer outra arquitetura, você pode criar um `Dockerfile` do zero, baseado em uma imagem base Python (que é multi-arquitetural) e utilizar Uvicorn sozinho. - -Nesse caso, seu `Dockerfile` poderia parecer assim: - -```Dockerfile -FROM python:3.7 - -RUN pip install fastapi uvicorn - -EXPOSE 80 - -COPY ./app /app - -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] -``` - -### Crie o código **FastAPI** - -* Crie um diretório `app` e entre nele. -* Crie um arquivo `main.py` com: - -```Python -from fastapi import FastAPI - -app = FastAPI() - - -@app.get("/") -def read_root(): - return {"Hello": "World"} - - -@app.get("/items/{item_id}") -def read_item(item_id: int, q: str = None): - return {"item_id": item_id, "q": q} -``` - -* Você deve ter uma estrutura de diretórios assim: - -``` -. -├── app -│ └── main.py -└── Dockerfile -``` - -### Construa a imagem Docker - -* Vá para o diretório do projeto (onde seu `Dockerfile` está, contendo seu diretório `app`. -* Construa sua imagem FastAPI: - -
- -```console -$ docker build -t myimage . - ----> 100% -``` - -
- -### Inicie o container Docker - -* Rode um container baseado em sua imagem: - -
- -```console -$ docker run -d --name mycontainer -p 80:80 myimage -``` - -
- -Agora você tem um servidor FastAPI otimizado em um container Docker. Auto-ajustado para seu servidor atual (e número de núcleos de CPU). - -### Verifique - -Você deve ser capaz de verificar na URL de seu container Docker, por exemplo: http://192.168.99.100/items/5?q=somequery ou http://127.0.0.1/items/5?q=somequery (ou equivalente, usando seu _host_ Docker). - -Você verá algo como: - -```JSON -{"item_id": 5, "q": "somequery"} -``` - -### API interativa de documetação - -Agora você pode ir para http://192.168.99.100/docs ou http://127.0.0.1/docs (ou equivalente, usando seu _host_ Docker). - -Você verá a API interativa de documentação (fornecida por Swagger UI): - -![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) - -### APIs alternativas de documentação - -E você pode também ir para http://192.168.99.100/redoc ou http://127.0.0.1/redoc (ou equivalente, usando seu _host_ Docker). - -Você verá a documentação automática alternativa (fornecida por ReDoc): - -![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) - -## HTTPS - -### Sobre HTTPS - -É fácil assumir que HTTPS seja algo que esteja apenas "habilitado" ou não. - -Mas ele é um pouquinho mais complexo do que isso. - -/// tip - -Se você está com pressa ou não se importa, continue na próxima seção com instruções passo a passo para configurar tudo. - -/// - -Para aprender o básico de HTTPS, pela perspectiva de um consumidor, verifique https://howhttps.works/. - -Agora, pela perspectiva de um desenvolvedor, aqui estão algumas coisas para se ter em mente enquanto se pensa sobre HTTPS: - -* Para HTTPS, o servidor precisa ter "certificados" gerados por terceiros. - * Esses certificados são na verdade adquiridos por terceiros, não "gerados". -* Certificados tem um prazo de uso. - * Eles expiram. - * E então eles precisam ser renovados, adquiridos novamente por terceiros. -* A encriptação da conexão acontece no nível TCP. - * TCP é uma camada abaixo do HTTP. - * Então, o controle de certificado e encriptação é feito antes do HTTP. -* TCP não conhece nada sobre "domínios". Somente sobre endereços IP. - * A informação sobre o domínio requisitado vai nos dados HTTP. -* Os certificados HTTPS "certificam" um certo domínio, mas o protocolo e a encriptação acontecem no nível TCP, antes de saber qual domínio está sendo lidado. -* Por padrão, isso significa que você pode ter somente um certificado HTTPS por endereço IP. - * Não importa quão grande é seu servidor ou quão pequena cada aplicação que você tenha possar ser. - * No entanto, existe uma solução para isso. -* Existe uma extensão para o protocolo TLS (o que controla a encriptação no nível TCP, antes do HTTP) chamada SNI. - * Essa extensão SNI permite um único servidor (com um único endereço IP) a ter vários certificados HTTPS e servir múltiplas aplicações/domínios HTTPS. - * Para que isso funcione, um único componente (programa) rodando no servidor, ouvindo no endereço IP público, deve ter todos os certificados HTTPS no servidor. -* Após obter uma conexão segura, o protocolo de comunicação ainda é HTTP. - * O conteúdo está encriptado, mesmo embora ele esteja sendo enviado com o protocolo HTTP. - -É uma prática comum ter um servidor HTTP/programa rodando no servidor (a máquina, _host_ etc.) e gerenciar todas as partes HTTP: enviar as requisições HTTP decriptadas para a aplicação HTTP rodando no mesmo servidor (a aplicação **FastAPI**, nesse caso), pega a resposta HTTP da aplicação, encripta utilizando o certificado apropriado e enviando de volta para o cliente usando HTTPS. Esse servidor é frequentemente chamado TLS _Termination Proxy_. - -### Vamos encriptar - -Antes de encriptar, esses certificados HTTPS foram vendidos por terceiros de confiança. - -O processo para adquirir um desses certificados costumava ser chato, exigia muita papelada e eram bem caros. - -Mas então _Let's Encrypt_ foi criado. - -É um projeto da Fundação Linux.Ele fornece certificados HTTPS de graça. De um jeito automatizado. Esses certificados utilizam todos os padrões de segurança criptográfica, e tem vida curta (cerca de 3 meses), para que a segurança seja melhor devido ao seu curto período de vida. - -Os domínios são seguramente verificados e os certificados são gerados automaticamente. Isso também permite automatizar a renovação desses certificados. - -A idéia é automatizar a aquisição e renovação desses certificados, para que você possa ter um HTTPS seguro, grátis, para sempre. - -### Traefik - -Traefik é um _proxy_ reverso / _load balancer_ de alta performance. Ele pode fazer o trabalho do _"TLS Termination Proxy"_ (à parte de outros recursos). - -Ele tem integração com _Let's Encrypt_. Assim, ele pode controlar todas as partes HTTPS, incluindo a aquisição e renovação de certificados. - -Ele também tem integrações com Docker. Assim, você pode declarar seus domínios em cada configuração de aplicação e leitura dessas configurações, gerando os certificados HTTPS e servindo o HTTPS para sua aplicação automaticamente, sem exigir qualquer mudança em sua configuração. - ---- - -Com essas ferramentas e informações, continue com a próxima seção para combinar tudo. - -## _Cluster_ de Docker Swarm Mode com Traefik e HTTPS - -Você pode ter um _cluster_ de Docker Swarm Mode configurado em minutos (cerca de 20) com o Traefik controlando HTTPS (incluindo aquisição e renovação de certificados). - -Utilizando o Docker Swarm Mode, você pode iniciar com um _"cluster"_ de apenas uma máquina (que pode até ser um servidor por 5 dólares / mês) e então você pode aumentar conforme a necessidade adicionando mais servidores. - -Para configurar um _cluster_ Docker Swarm Mode com Traefik controlando HTTPS, siga essa orientação: - -### Docker Swarm Mode and Traefik for an HTTPS cluster - -### Faça o _deploy_ de uma aplicação FastAPI - -O jeito mais fácil de configurar tudo pode ser utilizando o [Gerador de Projetos **FastAPI**](project-generation.md){.internal-link target=_blank}. - -Ele é designado para ser integrado com esse _cluster_ Docker Swarm com Traefik e HTTPS descrito acima. - -Você pode gerar um projeto em cerca de 2 minutos. - -O projeto gerado tem instruções para fazer o _deploy_, fazendo isso leva outros 2 minutos. - -## Alternativamente, faça o _deploy_ **FastAPI** sem Docker - -Você pode fazer o _deploy_ do **FastAPI** diretamente sem o Docker também. - -Você apenas precisa instalar um servidor ASGI compatível como: - -//// tab | Uvicorn - -* Uvicorn, um servidor ASGI peso leve, construído sobre uvloop e httptools. - -
- -```console -$ pip install "uvicorn[standard]" - ----> 100% -``` - -
- -//// - -//// tab | Hypercorn - -* Hypercorn, um servidor ASGI também compatível com HTTP/2. - -
- -```console -$ pip install hypercorn - ----> 100% -``` - -
- -...ou qualquer outro servidor ASGI. - -//// - -E rode sua applicação do mesmo modo que você tem feito nos tutoriais, mas sem a opção `--reload`, por exemplo: - -//// tab | Uvicorn - -
- -```console -$ uvicorn main:app --host 0.0.0.0 --port 80 - -INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) -``` - -
- -//// - -//// tab | Hypercorn - -
- -```console -$ hypercorn main:app --bind 0.0.0.0:80 - -Running on 0.0.0.0:8080 over http (CTRL + C to quit) -``` - -
- -//// - -Você deve querer configurar mais algumas ferramentas para ter certeza que ele seja reinicializado automaticamante se ele parar. - -Você também deve querer instalar Gunicorn e utilizar ele como um gerenciador para o Uvicorn, ou usar Hypercorn com múltiplos _workers_. - -Tenha certeza de ajustar o número de _workers_ etc. - -Mas se você estiver fazendo tudo isso, você pode apenas usar uma imagem Docker que fará isso automaticamente. From 923d44de356e4dd6ea5cea996deb454ba3139ada Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 14 Oct 2024 14:57:54 +0000 Subject: [PATCH 080/932] =?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 08f1652f5..2c2a9a649 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Remove Portuguese translation for `docs/pt/docs/deployment.md`. PR [#12427](https://github.com/fastapi/fastapi/pull/12427) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/body-updates.md`. PR [#12381](https://github.com/fastapi/fastapi/pull/12381) by [@andersonrocha0](https://github.com/andersonrocha0). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-cookies.md`. PR [#12417](https://github.com/fastapi/fastapi/pull/12417) by [@Paulofalcao2002](https://github.com/Paulofalcao2002). From e58c185526d3a4c39e16d05ec9fc3abd4febc3d5 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Tue, 15 Oct 2024 06:53:14 -0300 Subject: [PATCH 081/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/query-param-models.md`=20?= =?UTF-8?q?(#12414)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/query-param-models.md | 197 ++++++++++++++++++++ 1 file changed, 197 insertions(+) create mode 100644 docs/pt/docs/tutorial/query-param-models.md diff --git a/docs/pt/docs/tutorial/query-param-models.md b/docs/pt/docs/tutorial/query-param-models.md new file mode 100644 index 000000000..854183fb4 --- /dev/null +++ b/docs/pt/docs/tutorial/query-param-models.md @@ -0,0 +1,197 @@ +# Modelos de Parâmetros de Consulta + +Se você possui um grupo de **parâmetros de consultas** que são relacionados, você pode criar um **modelo Pydantic** para declará-los. + +Isso permitiria que você **reutilizasse o modelo** em **diversos lugares**, e também declarasse validações e metadados de todos os parâmetros de uma única vez. 😎 + +/// note | Nota + +Isso é suportado desde o FastAPI versão `0.115.0`. 🤓 + +/// + +## Parâmetros de Consulta com um Modelo Pydantic + +Declare os **parâmetros de consulta** que você precisa em um **modelo Pydantic**, e então declare o parâmetro como `Query`: + +//// tab | Python 3.10+ + +```Python hl_lines="9-13 17" +{!> ../../docs_src/query_param_models/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="8-12 16" +{!> ../../docs_src/query_param_models/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10-14 18" +{!> ../../docs_src/query_param_models/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="9-13 17" +{!> ../../docs_src/query_param_models/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="8-12 16" +{!> ../../docs_src/query_param_models/tutorial001_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="9-13 17" +{!> ../../docs_src/query_param_models/tutorial001_py310.py!} +``` + +//// + +O **FastAPI** **extrairá** os dados para **cada campo** dos **parâmetros de consulta** presentes na requisição, e fornecerá o modelo Pydantic que você definiu. + + +## Verifique os Documentos + +Você pode ver os parâmetros de consulta nos documentos de IU em `/docs`: + +
+ +
+ +## Restrinja Parâmetros de Consulta Extras + +Em alguns casos especiais (provavelmente não muito comuns), você queira **restrinjir** os parâmetros de consulta que deseja receber. + +Você pode usar a configuração do modelo Pydantic para `forbid` (proibir) qualquer campo `extra`: + +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../docs_src/query_param_models/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/query_param_models/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../docs_src/query_param_models/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="10" +{!> ../../docs_src/query_param_models/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="9" +{!> ../../docs_src/query_param_models/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira utilizar a versão `Annotated` se possível. + +/// + +```Python hl_lines="11" +{!> ../../docs_src/query_param_models/tutorial002.py!} +``` + +//// + +Caso um cliente tente enviar alguns dados **extras** nos **parâmetros de consulta**, eles receberão um retorno de **erro**. + +Por exemplo, se o cliente tentar enviar um parâmetro de consulta `tool` com o valor `plumbus`, como: + +```http +https://example.com/items/?limit=10&tool=plumbus +``` + +Eles receberão um retorno de **erro** informando-os que o parâmentro de consulta `tool` não é permitido: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus" + } + ] +} +``` + +## Resumo + +Você pode utilizar **modelos Pydantic** para declarar **parâmetros de consulta** no **FastAPI**. 😎 + +/// tip | Dica + +Alerta de spoiler: você também pode utilizar modelos Pydantic para declarar cookies e cabeçalhos, mas você irá ler sobre isso mais a frente no tutorial. 🤫 + +/// From c9f11c2b732de9876dc942da640a521aeb6c1f2d Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 15 Oct 2024 09:53:37 +0000 Subject: [PATCH 082/932] =?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 2c2a9a649..1f794f2ef 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/query-param-models.md`. PR [#12414](https://github.com/fastapi/fastapi/pull/12414) by [@ceb10n](https://github.com/ceb10n). * 🌐 Remove Portuguese translation for `docs/pt/docs/deployment.md`. PR [#12427](https://github.com/fastapi/fastapi/pull/12427) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/body-updates.md`. PR [#12381](https://github.com/fastapi/fastapi/pull/12381) by [@andersonrocha0](https://github.com/andersonrocha0). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-cookies.md`. PR [#12417](https://github.com/fastapi/fastapi/pull/12417) by [@Paulofalcao2002](https://github.com/Paulofalcao2002). From 73546a68e6cc08dc9dc5de2efabceb638035e4ab Mon Sep 17 00:00:00 2001 From: YungYueh ChanLee Date: Tue, 15 Oct 2024 17:57:21 +0800 Subject: [PATCH 083/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Traditional=20Chin?= =?UTF-8?q?ese=20translation=20for=20`docs/zh-hant/docs/about/index.md`=20?= =?UTF-8?q?(#12438)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/about/index.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 docs/zh-hant/docs/about/index.md diff --git a/docs/zh-hant/docs/about/index.md b/docs/zh-hant/docs/about/index.md new file mode 100644 index 000000000..5dcee68f2 --- /dev/null +++ b/docs/zh-hant/docs/about/index.md @@ -0,0 +1,3 @@ +# 關於 FastAPI + +關於 FastAPI、其設計、靈感來源等更多資訊。 🤓 From 33cd8bbcc59971776deda01207bc0692033f549a Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 15 Oct 2024 09:58:11 +0000 Subject: [PATCH 084/932] =?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 1f794f2ef..6289f3603 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/about/index.md`. PR [#12438](https://github.com/fastapi/fastapi/pull/12438) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/query-param-models.md`. PR [#12414](https://github.com/fastapi/fastapi/pull/12414) by [@ceb10n](https://github.com/ceb10n). * 🌐 Remove Portuguese translation for `docs/pt/docs/deployment.md`. PR [#12427](https://github.com/fastapi/fastapi/pull/12427) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/body-updates.md`. PR [#12381](https://github.com/fastapi/fastapi/pull/12381) by [@andersonrocha0](https://github.com/andersonrocha0). From 4d8d092925a8c8f129039eebdde8e395c56a01f3 Mon Sep 17 00:00:00 2001 From: YungYueh ChanLee Date: Tue, 15 Oct 2024 18:00:33 +0800 Subject: [PATCH 085/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Traditional=20Chin?= =?UTF-8?q?ese=20translation=20for=20`docs/zh-hant/docs/resources/index.md?= =?UTF-8?q?`=20(#12443)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/resources/index.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 docs/zh-hant/docs/resources/index.md diff --git a/docs/zh-hant/docs/resources/index.md b/docs/zh-hant/docs/resources/index.md new file mode 100644 index 000000000..f4c70a3a0 --- /dev/null +++ b/docs/zh-hant/docs/resources/index.md @@ -0,0 +1,3 @@ +# 資源 + +額外的資源、外部連結、文章等。 ✈️ From d63f0d60ba32a3a04cb275b10fb25450f1a7c764 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 15 Oct 2024 10:03:32 +0000 Subject: [PATCH 086/932] =?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 6289f3603..6194277be 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/resources/index.md`. PR [#12443](https://github.com/fastapi/fastapi/pull/12443) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/about/index.md`. PR [#12438](https://github.com/fastapi/fastapi/pull/12438) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/query-param-models.md`. PR [#12414](https://github.com/fastapi/fastapi/pull/12414) by [@ceb10n](https://github.com/ceb10n). * 🌐 Remove Portuguese translation for `docs/pt/docs/deployment.md`. PR [#12427](https://github.com/fastapi/fastapi/pull/12427) by [@ceb10n](https://github.com/ceb10n). From 111ced53af4fa89b7f636e9d6b8179996c69d563 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Tue, 15 Oct 2024 12:38:53 +0200 Subject: [PATCH 087/932] =?UTF-8?q?=F0=9F=91=B7=20Update=20issue=20manager?= =?UTF-8?q?=20workflow=20(#12457)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- .github/workflows/issue-manager.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/issue-manager.yml b/.github/workflows/issue-manager.yml index 439084434..6a7e6143e 100644 --- a/.github/workflows/issue-manager.yml +++ b/.github/workflows/issue-manager.yml @@ -39,5 +39,9 @@ jobs: "waiting": { "delay": 2628000, "message": "As this PR has been waiting for the original user for a while but seems to be inactive, it's now going to be closed. But if there's anyone interested, feel free to create a new PR." + }, + "invalid": { + "delay": 0, + "message": "This was marked as invalid and will be closed now. If this is an error, please provide additional details." } } From be03a7313e9e2e0a5d247129ac68afc42928ffa3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 15 Oct 2024 10:39:19 +0000 Subject: [PATCH 088/932] =?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 6194277be..fa0861e33 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -18,6 +18,7 @@ hide: ### Internal +* 👷 Update issue manager workflow . PR [#12457](https://github.com/fastapi/fastapi/pull/12457) by [@alejsdev](https://github.com/alejsdev). * 🔧 Update team, include YuriiMotov 🚀. PR [#12453](https://github.com/fastapi/fastapi/pull/12453) by [@tiangolo](https://github.com/tiangolo). * 👷 Refactor label-approved, make it an internal script instead of an external GitHub Action. PR [#12280](https://github.com/fastapi/fastapi/pull/12280) by [@tiangolo](https://github.com/tiangolo). * 👷 Fix smokeshow, checkout files on CI. PR [#12434](https://github.com/fastapi/fastapi/pull/12434) by [@tiangolo](https://github.com/tiangolo). From 05074585044756077ab1ff56b3279d5f462ce625 Mon Sep 17 00:00:00 2001 From: WISDERFIN <77553770+wisderfin@users.noreply.github.com> Date: Tue, 15 Oct 2024 15:38:57 +0400 Subject: [PATCH 089/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/environment-variables.md`=20(#12436)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/environment-variables.md | 297 ++++++++++++++++++++++++++ 1 file changed, 297 insertions(+) create mode 100644 docs/ru/docs/environment-variables.md diff --git a/docs/ru/docs/environment-variables.md b/docs/ru/docs/environment-variables.md new file mode 100644 index 000000000..a6c7b0c77 --- /dev/null +++ b/docs/ru/docs/environment-variables.md @@ -0,0 +1,297 @@ +# Переменные окружения + +/// tip + +Если вы уже знаете, что такое «переменные окружения» и как их использовать, можете пропустить это. + +/// + +Переменная окружения (также известная как «**env var**») - это переменная, которая живет **вне** кода Python, в **операционной системе**, и может быть прочитана вашим кодом Python (или другими программами). + +Переменные окружения могут быть полезны для работы с **настройками** приложений, как часть **установки** Python и т.д. + +## Создание и использование переменных окружения + +Можно **создавать** и использовать переменные окружения в **оболочке (терминале)**, не прибегая к помощи Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Вы можете создать переменную окружения MY_NAME с помощью +$ export MY_NAME="Wade Wilson" + +// Затем её можно использовать в других программах, например +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Создайте переменную окружения MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Используйте её с другими программами, например +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## Чтение переменных окружения в python + +Так же существует возможность создания переменных окружения **вне** Python, в терминале (или любым другим способом), а затем **чтения их в Python**. + +Например, у вас есть файл `main.py`: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +Второй аргумент `os.getenv()` - это возвращаемое по умолчанию значение. + +Если значение не указано, то по умолчанию оно равно `None`. В данном случае мы указываем `«World»` в качестве значения по умолчанию. +/// + +Затем можно запустить эту программу на Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Здесь мы еще не устанавливаем переменную окружения +$ python main.py + +// Поскольку мы не задали переменную окружения, мы получим значение по умолчанию + +Hello World from Python + +// Но если мы сначала создадим переменную окружения +$ export MY_NAME="Wade Wilson" + +// А затем снова запустим программу +$ python main.py + +// Теперь она прочитает переменную окружения + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Здесь мы еще не устанавливаем переменную окружения +$ python main.py + +// Поскольку мы не задали переменную окружения, мы получим значение по умолчанию + +Hello World from Python + +// Но если мы сначала создадим переменную окружения +$ $Env:MY_NAME = "Wade Wilson" + +// А затем снова запустим программу +$ python main.py + +// Теперь она может прочитать переменную окружения + +Hello Wade Wilson from Python +``` + +
+ +//// + +Поскольку переменные окружения могут быть установлены вне кода, но могут быть прочитаны кодом, и их не нужно хранить (фиксировать в `git`) вместе с остальными файлами, их принято использовать для конфигураций или **настроек**. + +Вы также можете создать переменную окружения только для **конкретного вызова программы**, которая будет доступна только для этой программы и только на время ее выполнения. + +Для этого создайте её непосредственно перед самой программой, в той же строке: + +
+ +```console +// Создайте переменную окружения MY_NAME в строке для этого вызова программы +$ MY_NAME="Wade Wilson" python main.py + +// Теперь она может прочитать переменную окружения + +Hello Wade Wilson from Python + +// После этого переменная окружения больше не существует +$ python main.py + +Hello World from Python +``` + +
+ +/// tip + +Подробнее об этом можно прочитать на сайте The Twelve-Factor App: Config. + +/// + +## Типизация и Валидация + +Эти переменные окружения могут работать только с **текстовыми строками**, поскольку они являются внешними по отношению к Python и должны быть совместимы с другими программами и остальной системой (и даже с различными операционными системами, такими как Linux, Windows, macOS). + +Это означает, что **любое значение**, считанное в Python из переменной окружения, **будет `str`**, и любое преобразование к другому типу или любая проверка должны быть выполнены в коде. + +Подробнее об использовании переменных окружения для работы с **настройками приложения** вы узнаете в [Расширенное руководство пользователя - Настройки и переменные среды](./advanced/settings.md){.internal-link target=_blank}. + +## Переменная окружения `PATH` + +Существует **специальная** переменная окружения **`PATH`**, которая используется операционными системами (Linux, macOS, Windows) для поиска программ для запуска. + +Значение переменной `PATH` - это длинная строка, состоящая из каталогов, разделенных двоеточием `:` в Linux и macOS, и точкой с запятой `;` в Windows. + +Например, переменная окружения `PATH` может выглядеть следующим образом: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Это означает, что система должна искать программы в каталогах: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +Это означает, что система должна искать программы в каталогах: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +Когда вы вводите **команду** в терминале, операционная система **ищет** программу в **каждой из тех директорий**, которые перечислены в переменной окружения `PATH`. + +Например, когда вы вводите `python` в терминале, операционная система ищет программу под названием `python` в **первой директории** в этом списке. + +Если она ее находит, то **использует ее**. В противном случае она продолжает искать в **других каталогах**. + +### Установка Python и обновление `PATH` + +При установке Python вас могут спросить, нужно ли обновить переменную окружения `PATH`. + +//// tab | Linux, macOS + +Допустим, вы устанавливаете Python, и он оказывается в каталоге `/opt/custompython/bin`. + +Если вы скажете «да», чтобы обновить переменную окружения `PATH`, то программа установки добавит `/opt/custompython/bin` в переменную окружения `PATH`. + +Это может выглядеть следующим образом: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +Таким образом, когда вы набираете `python` в терминале, система найдет программу Python в `/opt/custompython/bin` (последний каталог) и использует ее. + +//// + +//// tab | Windows + +Допустим, вы устанавливаете Python, и он оказывается в каталоге `C:\opt\custompython\bin`. + +Если вы согласитесь обновить переменную окружения `PATH`, то программа установки добавит `C:\opt\custompython\bin` в переменную окружения `PATH`. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +Таким образом, когда вы набираете `python` в терминале, система найдет программу Python в `C:\opt\custompython\bin` (последний каталог) и использует ее. + +//// + +Итак, если вы напечатаете: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +Система **найдет** программу `python` в `/opt/custompython/bin` и запустит ее. + +Это примерно эквивалентно набору текста: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +Система **найдет** программу `python` в каталоге `C:\opt\custompython\bin\python` и запустит ее. + +Это примерно эквивалентно набору текста: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +Эта информация будет полезна при изучении [Виртуальных окружений](virtual-environments.md){.internal-link target=_blank}. + +## Вывод + +Благодаря этому вы должны иметь базовое представление о том, что такое **переменные окружения** и как использовать их в Python. + +Подробнее о них вы также можете прочитать в статье о переменных окружения на википедии. + +Во многих случаях не всегда очевидно, как переменные окружения могут быть полезны и применимы. Но они постоянно появляются в различных сценариях разработки, поэтому знать о них полезно. + +Например, эта информация понадобится вам в следующем разделе, посвященном [Виртуальным окружениям](virtual-environments.md). From 9b09974cfc358692712375f899381a159038bb8f Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 15 Oct 2024 11:39:19 +0000 Subject: [PATCH 090/932] =?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 fa0861e33..b8aa738c5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Russian translation for `docs/ru/docs/environment-variables.md`. PR [#12436](https://github.com/fastapi/fastapi/pull/12436) by [@wisderfin](https://github.com/wisderfin). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/resources/index.md`. PR [#12443](https://github.com/fastapi/fastapi/pull/12443) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/about/index.md`. PR [#12438](https://github.com/fastapi/fastapi/pull/12438) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/query-param-models.md`. PR [#12414](https://github.com/fastapi/fastapi/pull/12414) by [@ceb10n](https://github.com/ceb10n). From 12c188b311f97bb3e133c51057d52f9df9efb034 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Tue, 15 Oct 2024 09:32:27 -0300 Subject: [PATCH 091/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Portuguese=20tr?= =?UTF-8?q?anslation=20for=20`docs/pt/docs/python-types.md`=20(#12428)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/python-types.md | 379 ++++++++++++++++++++++++++++++----- 1 file changed, 326 insertions(+), 53 deletions(-) diff --git a/docs/pt/docs/python-types.md b/docs/pt/docs/python-types.md index 05faa860c..a0938259f 100644 --- a/docs/pt/docs/python-types.md +++ b/docs/pt/docs/python-types.md @@ -1,18 +1,18 @@ # Introdução aos tipos Python -**Python 3.6 +** tem suporte para "type hints" opcionais. +O Python possui suporte para "dicas de tipo" ou "type hints" (também chamado de "anotações de tipo" ou "type annotations") -Esses **"type hints"** são uma nova sintaxe (desde Python 3.6+) que permite declarar o tipo de uma variável. +Esses **"type hints"** são uma sintaxe especial que permite declarar o tipo de uma variável. Ao declarar tipos para suas variáveis, editores e ferramentas podem oferecer um melhor suporte. -Este é apenas um **tutorial rápido / atualização** sobre type hints Python. Ele cobre apenas o mínimo necessário para usá-los com o **FastAPI** ... que é realmente muito pouco. +Este é apenas um **tutorial rápido / atualização** sobre type hints do Python. Ele cobre apenas o mínimo necessário para usá-los com o **FastAPI**... que é realmente muito pouco. O **FastAPI** é baseado nesses type hints, eles oferecem muitas vantagens e benefícios. Mas mesmo que você nunca use o **FastAPI**, você se beneficiaria de aprender um pouco sobre eles. -/// note | "Nota" +/// note | Nota Se você é um especialista em Python e já sabe tudo sobre type hints, pule para o próximo capítulo. @@ -35,8 +35,8 @@ John Doe A função faz o seguinte: * Pega um `first_name` e `last_name`. -* Converte a primeira letra de cada uma em maiúsculas com `title ()`. -* Concatena com um espaço no meio. +* Converte a primeira letra de cada uma em maiúsculas com `title()`. +* Concatena com um espaço no meio. ```Python hl_lines="2" {!../../docs_src/python_types/tutorial001.py!} @@ -48,7 +48,7 @@ A função faz o seguinte: Mas agora imagine que você estava escrevendo do zero. -Em algum momento você teria iniciado a definição da função, já tinha os parâmetros prontos ... +Em algum momento você teria iniciado a definição da função, já tinha os parâmetros prontos... Mas então você deve chamar "esse método que converte a primeira letra em maiúscula". @@ -96,37 +96,37 @@ Isso não é o mesmo que declarar valores padrão como seria com: Estamos usando dois pontos (`:`), não é igual a (`=`). -E adicionar type hints normalmente não muda o que acontece do que aconteceria sem elas. +E adicionar type hints normalmente não muda o que acontece do que aconteceria sem eles. Mas agora, imagine que você está novamente no meio da criação dessa função, mas com type hints. -No mesmo ponto, você tenta acionar o preenchimento automático com o `Ctrl Space` e vê: +No mesmo ponto, você tenta acionar o preenchimento automático com o `Ctrl+Space` e vê: -Com isso, você pode rolar, vendo as opções, até encontrar o que "toca uma campainha": +Com isso, você pode rolar, vendo as opções, até encontrar o que "soa familiar": ## Mais motivação -Marque esta função, ela já possui type hints: +Verifique esta função, ela já possui type hints: ```Python hl_lines="1" {!../../docs_src/python_types/tutorial003.py!} ``` -Como o editor conhece os tipos de variáveis, você não apenas obtém a conclusão, mas também as verificações de erro: +Como o editor conhece os tipos de variáveis, você não obtém apenas o preenchimento automático, mas também as verificações de erro: -Agora você sabe que precisa corrigí-lo, converta `age` em uma string com `str (age)`: +Agora você sabe que precisa corrigí-lo, converta `age` em uma string com `str(age)`: ```Python hl_lines="2" {!../../docs_src/python_types/tutorial004.py!} ``` -## Tipos de declaração +## Declarando Tipos Você acabou de ver o local principal para declarar type hints. Como parâmetros de função. @@ -151,39 +151,77 @@ Você pode usar, por exemplo: Existem algumas estruturas de dados que podem conter outros valores, como `dict`, `list`, `set` e `tuple`. E os valores internos também podem ter seu próprio tipo. -Para declarar esses tipos e os tipos internos, você pode usar o módulo Python padrão `typing`. +Estes tipos que possuem tipos internos são chamados de tipos "**genéricos**". E é possível declará-los mesmo com os seus tipos internos. -Ele existe especificamente para suportar esses type hints. +Para declarar esses tipos e os tipos internos, você pode usar o módulo Python padrão `typing`. Ele existe especificamente para suportar esses type hints. -#### `List` +#### Versões mais recentes do Python -Por exemplo, vamos definir uma variável para ser uma `lista` de `str`. +A sintaxe utilizando `typing` é **compatível** com todas as versões, desde o Python 3.6 até as últimas, incluindo o Python 3.9, 3.10, etc. -Em `typing`, importe `List` (com um `L` maiúsculo): +Conforme o Python evolui, **novas versões** chegam com suporte melhorado para esses type annotations, e em muitos casos, você não precisará nem importar e utilizar o módulo `typing` para declarar os type annotations. + +Se você pode escolher uma versão mais recente do Python para o seu projeto, você poderá aproveitar isso ao seu favor. + +Em todos os documentos existem exemplos compatíveis com cada versão do Python (quando existem diferenças). + +Por exemplo, "**Python 3.6+**" significa que é compatível com o Python 3.6 ou superior (incluindo o 3.7, 3.8, 3.9, 3.10, etc). E "**Python 3.9+**" significa que é compatível com o Python 3.9 ou mais recente (incluindo o 3.10, etc). + +Se você pode utilizar a **versão mais recente do Python**, utilize os exemplos para as últimas versões. Eles terão as **melhores e mais simples sintaxes**, como por exemplo, "**Python 3.10+**". + +#### List + +Por exemplo, vamos definir uma variável para ser uma `list` de `str`. + +//// tab | Python 3.9+ + +Declare uma variável com a mesma sintaxe com dois pontos (`:`) + +Como tipo, coloque `list`. + +Como a lista é o tipo que contém algum tipo interno, você coloca o tipo dentro de colchetes: ```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006_py39.py!} ``` -Declare a variável com a mesma sintaxe de dois pontos (`:`). +//// -Como o tipo, coloque a `List`. +//// tab | Python 3.8+ -Como a lista é um tipo que contém alguns tipos internos, você os coloca entre colchetes: +De `typing`, importe `List` (com o `L` maiúsculo): + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006.py!} +``` + +Declare uma variável com a mesma sintaxe com dois pontos (`:`) + +Como tipo, coloque o `List` que você importou de `typing`. + +Como a lista é o tipo que contém algum tipo interno, você coloca o tipo dentro de colchetes: ```Python hl_lines="4" -{!../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` -/// tip | "Dica" +//// + +/// info | Informação -Esses tipos internos entre colchetes são chamados de "parâmetros de tipo". +Estes tipos internos dentro dos colchetes são chamados "parâmetros de tipo" (type parameters). -Nesse caso, `str` é o parâmetro de tipo passado para `List`. +Neste caso, `str` é o parâmetro de tipo passado para `List` (ou `list` no Python 3.9 ou superior). /// -Isso significa que: "a variável `items` é uma `list`, e cada um dos itens desta lista é uma `str`". +Isso significa: "a variável `items` é uma `list`, e cada um dos itens desta lista é uma `str`". + +/// tip | Dica + +Se você usa o Python 3.9 ou superior, você não precisa importar `List` de `typing`. Você pode utilizar o mesmo tipo `list` no lugar. + +/// Ao fazer isso, seu editor pode fornecer suporte mesmo durante o processamento de itens da lista: @@ -195,20 +233,32 @@ Observe que a variável `item` é um dos elementos da lista `items`. E, ainda assim, o editor sabe que é um `str` e fornece suporte para isso. -#### `Tuple` e `Set` +#### Tuple e Set Você faria o mesmo para declarar `tuple`s e `set`s: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial007.py!} ``` +//// + Isso significa que: * A variável `items_t` é uma `tuple` com 3 itens, um `int`, outro `int` e uma `str`. * A variável `items_s` é um `set`, e cada um de seus itens é do tipo `bytes`. -#### `Dict` +#### Dict Para definir um `dict`, você passa 2 parâmetros de tipo, separados por vírgulas. @@ -216,38 +266,185 @@ O primeiro parâmetro de tipo é para as chaves do `dict`. O segundo parâmetro de tipo é para os valores do `dict`: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008_py39.py!} ``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008.py!} +``` + +//// + Isso significa que: * A variável `prices` é um dict`: * As chaves deste `dict` são do tipo `str` (digamos, o nome de cada item). * Os valores deste `dict` são do tipo `float` (digamos, o preço de cada item). -#### `Opcional` +#### Union -Você também pode usar o `Opcional` para declarar que uma variável tem um tipo, como `str`, mas que é "opcional", o que significa que também pode ser `None`: +Você pode declarar que uma variável pode ser de qualquer um dentre **diversos tipos**. Por exemplo, um `int` ou um `str`. + +No Python 3.6 e superior (incluindo o Python 3.10), você pode utilizar o tipo `Union` de `typing`, e colocar dentro dos colchetes os possíveis tipos aceitáveis. + +No Python 3.10 também existe uma **nova sintaxe** onde você pode colocar os possívels tipos separados por uma barra vertical (`|`). + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008b.py!} +``` + +//// + +Em ambos os casos, isso significa que `item` poderia ser um `int` ou um `str`. + + +#### Possívelmente `None` + +Você pode declarar que um valor pode ter um tipo, como `str`, mas que ele também pode ser `None`. + +No Python 3.6 e superior (incluindo o Python 3.10) você pode declará-lo importando e utilizando `Optional` do módulo `typing`. ```Python hl_lines="1 4" {!../../docs_src/python_types/tutorial009.py!} ``` -O uso de `Opcional [str]` em vez de apenas `str` permitirá que o editor o ajude a detectar erros, onde você pode estar assumindo que um valor é sempre um `str`, quando na verdade também pode ser `None`. +O uso de `Optional[str]` em vez de apenas `str` permitirá que o editor o ajude a detectar erros, onde você pode estar assumindo que um valor é sempre um `str`, quando na verdade também pode ser `None`. + +`Optional[Something]` é na verdade um atalho para `Union[Something, None]`, eles são equivalentes. + +Isso também significa que no Python 3.10, você pode utilizar `Something | None`: + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009.py!} +``` + +//// + +//// tab | Python 3.8+ alternative + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009b.py!} +``` + +//// + +#### Utilizando `Union` ou `Optional` + +Se você está utilizando uma versão do Python abaixo da 3.10, aqui vai uma dica do meu ponto de vista bem **subjetivo**: + +* 🚨 Evite utilizar `Optional[SomeType]` +* No lugar, ✨ **use `Union[SomeType, None]`** ✨. + +Ambos são equivalentes, e no final das contas, eles são o mesmo. Mas eu recomendaria o `Union` ao invés de `Optional` porque a palavra **Optional** parece implicar que o valor é opcional, quando na verdade significa "isso pode ser `None`", mesmo que ele não seja opcional e ainda seja obrigatório. + +Eu penso que `Union[SomeType, None]` é mais explícito sobre o que ele significa. + +Isso é apenas sobre palavras e nomes. Mas estas palavras podem afetar como os seus colegas de trabalho pensam sobre o código. + +Por exemplo, vamos pegar esta função: + +```Python hl_lines="1 4" +{!../../docs_src/python_types/tutorial009c.py!} +``` + +O paâmetro `name` é definido como `Optional[str]`, mas ele **não é opcional**, você não pode chamar a função sem o parâmetro: + +```Python +say_hi() # Oh, no, this throws an error! 😱 +``` + +O parâmetro `name` **ainda é obrigatório** (não *opicional*) porque ele não possui um valor padrão. Mesmo assim, `name` aceita `None` como valor: + +```Python +say_hi(name=None) # This works, None is valid 🎉 +``` + +A boa notícia é, quando você estiver no Python 3.10 você não precisará se preocupar mais com isso, pois você poderá simplesmente utilizar o `|` para definir uniões de tipos: + +```Python hl_lines="1 4" +{!../../docs_src/python_types/tutorial009c_py310.py!} +``` + +E então você não precisará mais se preocupar com nomes como `Optional` e `Union`. 😎 #### Tipos genéricos -Esses tipos que usam parâmetros de tipo entre colchetes, como: +Esses tipos que usam parâmetros de tipo entre colchetes são chamados **tipos genéricos** ou **genéricos**. Por exemplo: + +//// tab | Python 3.10+ + +Você pode utilizar os mesmos tipos internos como genéricos (com colchetes e tipos dentro): + +* `list` +* `tuple` +* `set` +* `dict` + +E o mesmo como no Python 3.8, do módulo `typing`: + +* `Union` +* `Optional` (o mesmo que com o 3.8) +* ...entro outros. + +No Python 3.10, como uma alternativa para a utilização dos genéricos `Union` e `Optional`, você pode usar a barra vertical (`|`) para declarar uniões de tipos. Isso é muito melhor e mais simples. + +//// + +//// tab | Python 3.9+ + +Você pode utilizar os mesmos tipos internos como genéricos (com colchetes e tipos dentro): + +* `list` +* `tuple` +* `set` +* `dict` + +E o mesmo como no Python 3.8, do módulo `typing`: + +* `Union` +* `Optional` +* ...entro outros. + +//// + +//// tab | Python 3.8+ * `List` * `Tuple` * `Set` * `Dict` -* `Opcional` -* ...e outros. +* `Union` +* `Optional` +* ...entro outros. -são chamados **tipos genéricos** ou **genéricos**. +//// ### Classes como tipos @@ -255,7 +452,7 @@ Você também pode declarar uma classe como o tipo de uma variável. Digamos que você tenha uma classe `Person`, com um nome: -```Python hl_lines="1 2 3" +```Python hl_lines="1-3" {!../../docs_src/python_types/tutorial010.py!} ``` @@ -269,9 +466,13 @@ E então, novamente, você recebe todo o suporte do editor: +Perceba que isso significa que "`one_person` é uma **instância** da classe `Person`". + +Isso não significa que "`one_person` é a **classe** chamada `Person`". + ## Modelos Pydantic - Pydantic é uma biblioteca Python para executar a validação de dados. +O Pydantic é uma biblioteca Python para executar a validação de dados. Você declara a "forma" dos dados como classes com atributos. @@ -283,21 +484,93 @@ E você recebe todo o suporte do editor com esse objeto resultante. Retirado dos documentos oficiais dos Pydantic: +//// tab | Python 3.10+ + ```Python -{!../../docs_src/python_types/tutorial011.py!} +{!> ../../docs_src/python_types/tutorial011_py310.py!} ``` -/// info | "Informação" +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/python_types/tutorial011_py39.py!} +``` -Para saber mais sobre o Pydantic, verifique seus documentos . +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/python_types/tutorial011.py!} +``` + +//// + +/// info | Informação + +Para saber mais sobre o Pydantic, verifique a sua documentação. /// -**FastAPI** é todo baseado em Pydantic. +O **FastAPI** é todo baseado em Pydantic. Você verá muito mais disso na prática no [Tutorial - Guia do usuário](tutorial/index.md){.internal-link target=_blank}. -## Type hints em **FastAPI** +/// tip | Dica + +O Pydantic tem um comportamento especial quando você usa `Optional` ou `Union[Something, None]` sem um valor padrão. Você pode ler mais sobre isso na documentação do Pydantic sobre campos Opcionais Obrigatórios. + +/// + + +## Type Hints com Metadados de Anotações + +O Python possui uma funcionalidade que nos permite incluir **metadados adicionais** nos type hints utilizando `Annotated`. + +//// tab | Python 3.9+ + +No Python 3.9, `Annotated` é parte da biblioteca padrão, então você pode importá-lo de `typing`. + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +Em versões abaixo do Python 3.9, você importa `Annotated` de `typing_extensions`. + +Ele já estará instalado com o **FastAPI**. + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013.py!} +``` + +//// + +O Python em si não faz nada com este `Annotated`. E para editores e outras ferramentas, o tipo ainda é `str`. + +Mas você pode utilizar este espaço dentro do `Annotated` para fornecer ao **FastAPI** metadata adicional sobre como você deseja que a sua aplicação se comporte. + +O importante aqui de se lembrar é que **o primeiro *type parameter*** que você informar ao `Annotated` é o **tipo de fato**. O resto é apenas metadado para outras ferramentas. + +Por hora, você precisa apenas saber que o `Annotated` existe, e que ele é Python padrão. 😎 + +Mais tarde você verá o quão **poderoso** ele pode ser. + +/// tip | Dica + +O fato de que isso é **Python padrão** significa que você ainda obtém a **melhor experiência de desenvolvedor possível** no seu editor, com as ferramentas que você utiliza para analisar e refatorar o seu código, etc. ✨ + +E também que o seu código será muito compatível com diversas outras ferramentas e bibliotecas Python. 🚀 + +/// + + +## Type hints no **FastAPI** O **FastAPI** aproveita esses type hints para fazer várias coisas. @@ -306,20 +579,20 @@ Com o **FastAPI**, você declara parâmetros com type hints e obtém: * **Suporte ao editor**. * **Verificações de tipo**. -... e **FastAPI** usa as mesmas declarações para: +... e o **FastAPI** usa as mesmas declarações para: -* **Definir requisitos**: dos parâmetros do caminho da solicitação, parâmetros da consulta, cabeçalhos, corpos, dependências, etc. +* **Definir requisitos**: dos parâmetros de rota, parâmetros da consulta, cabeçalhos, corpos, dependências, etc. * **Converter dados**: da solicitação para o tipo necessário. * **Validar dados**: provenientes de cada solicitação: - * A geração de **erros automáticos** retornou ao cliente quando os dados são inválidos. -* **Documente** a API usando OpenAPI: + * Gerando **erros automáticos** retornados ao cliente quando os dados são inválidos. +* **Documentar** a API usando OpenAPI: * que é usado pelas interfaces de usuário da documentação interativa automática. Tudo isso pode parecer abstrato. Não se preocupe. Você verá tudo isso em ação no [Tutorial - Guia do usuário](tutorial/index.md){.internal-link target=_blank}. O importante é que, usando tipos padrão de Python, em um único local (em vez de adicionar mais classes, decoradores, etc.), o **FastAPI** fará muito trabalho para você. -/// info | "Informação" +/// info | Informação Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é a "cheat sheet" do `mypy` . From d7942aea2dd81f03aa85f41b7f04ae76226f287b Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 15 Oct 2024 12:32:58 +0000 Subject: [PATCH 092/932] =?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 b8aa738c5..02773b769 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Update Portuguese translation for `docs/pt/docs/python-types.md`. PR [#12428](https://github.com/fastapi/fastapi/pull/12428) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Russian translation for `docs/ru/docs/environment-variables.md`. PR [#12436](https://github.com/fastapi/fastapi/pull/12436) by [@wisderfin](https://github.com/wisderfin). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/resources/index.md`. PR [#12443](https://github.com/fastapi/fastapi/pull/12443) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/about/index.md`. PR [#12438](https://github.com/fastapi/fastapi/pull/12438) by [@codingjenny](https://github.com/codingjenny). From 80ba3fc5db3234770d09166d1dffc70fbf1e5e20 Mon Sep 17 00:00:00 2001 From: YungYueh ChanLee Date: Tue, 15 Oct 2024 20:33:07 +0800 Subject: [PATCH 093/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Traditional=20Chin?= =?UTF-8?q?ese=20translation=20for=20`docs/zh-hant/docs/deployment/cloud.m?= =?UTF-8?q?d`=20(#12440)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/deployment/cloud.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 docs/zh-hant/docs/deployment/cloud.md diff --git a/docs/zh-hant/docs/deployment/cloud.md b/docs/zh-hant/docs/deployment/cloud.md new file mode 100644 index 000000000..5d645b6c2 --- /dev/null +++ b/docs/zh-hant/docs/deployment/cloud.md @@ -0,0 +1,17 @@ +# 在雲端部署 FastAPI + +你幾乎可以使用 **任何雲端供應商** 來部署你的 FastAPI 應用程式。 + +在大多數情況下,主要的雲端供應商都有部署 FastAPI 的指南。 + +## 雲端供應商 - 贊助商 + +一些雲端供應商 ✨ [**贊助 FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨,這確保了 FastAPI 及其 **生態系統** 持續健康地 **發展**。 + +這也展現了他們對 FastAPI 和其 **社群**(包括你)的真正承諾,他們不僅希望為你提供 **優質的服務**,還希望確保你擁有一個 **良好且健康的框架**:FastAPI。🙇 + +你可能會想嘗試他們的服務,以下有他們的指南: + +* Platform.sh +* Porter +* Coherence From 50639525bf0518a285544cae05eb4ad0b1fadb2e Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 15 Oct 2024 12:34:11 +0000 Subject: [PATCH 094/932] =?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 02773b769..ebdf8820c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/deployment/cloud.md`. PR [#12440](https://github.com/fastapi/fastapi/pull/12440) by [@codingjenny](https://github.com/codingjenny). * 🌐 Update Portuguese translation for `docs/pt/docs/python-types.md`. PR [#12428](https://github.com/fastapi/fastapi/pull/12428) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Russian translation for `docs/ru/docs/environment-variables.md`. PR [#12436](https://github.com/fastapi/fastapi/pull/12436) by [@wisderfin](https://github.com/wisderfin). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/resources/index.md`. PR [#12443](https://github.com/fastapi/fastapi/pull/12443) by [@codingjenny](https://github.com/codingjenny). From 71f2be23871ac1e368ae03f4ba40859b0e87071d Mon Sep 17 00:00:00 2001 From: leonardopaloschi <103431559+leonardopaloschi@users.noreply.github.com> Date: Wed, 16 Oct 2024 04:44:45 -0300 Subject: [PATCH 095/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/response-headers.md`=20(#?= =?UTF-8?q?12458)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/response-headers.md | 45 +++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 docs/pt/docs/advanced/response-headers.md diff --git a/docs/pt/docs/advanced/response-headers.md b/docs/pt/docs/advanced/response-headers.md new file mode 100644 index 000000000..d1958e46b --- /dev/null +++ b/docs/pt/docs/advanced/response-headers.md @@ -0,0 +1,45 @@ +# Cabeçalhos de resposta + +## Usando um parâmetro `Response` + +Você pode declarar um parâmetro do tipo `Response` na sua *função de operação de rota* (assim como você pode fazer para cookies). + +Então você pode definir os cabeçalhos nesse objeto de resposta *temporário*. + +```Python hl_lines="1 7-8" +{!../../docs_src/response_headers/tutorial002.py!} +``` + +Em seguida você pode retornar qualquer objeto que precisar, da maneira que faria normalmente (um `dict`, um modelo de banco de dados, etc.). + +Se você declarou um `response_model`, ele ainda será utilizado para filtrar e converter o objeto que você retornou. + +**FastAPI** usará essa resposta *temporária* para extrair os cabeçalhos (cookies e código de status também) e os colocará na resposta final que contém o valor que você retornou, filtrado por qualquer `response_model`. + +Você também pode declarar o parâmetro `Response` em dependências e definir cabeçalhos (e cookies) nelas. + +## Retornar uma `Response` diretamente + +Você também pode adicionar cabeçalhos quando retornar uma `Response` diretamente. + +Crie uma resposta conforme descrito em [Retornar uma resposta diretamente](response-directly.md){.internal-link target=_blank} e passe os cabeçalhos como um parâmetro adicional: + +```Python hl_lines="10-12" +{!../../docs_src/response_headers/tutorial001.py!} +``` + +/// note | "Detalhes técnicos" + +Você também pode usar `from starlette.responses import Response` ou `from starlette.responses import JSONResponse`. + +**FastAPI** fornece as mesmas `starlette.responses` como `fastapi.responses` apenas como uma conveniência para você, desenvolvedor. Mas a maioria das respostas disponíveis vem diretamente do Starlette. + +E como a `Response` pode ser usada frequentemente para definir cabeçalhos e cookies, **FastAPI** também a fornece em `fastapi.Response`. + +/// + +## Cabeçalhos personalizados + +Tenha em mente que cabeçalhos personalizados proprietários podem ser adicionados usando o prefixo 'X-'. + +Porém, se voce tiver cabeçalhos personalizados que deseja que um cliente no navegador possa ver, você precisa adicioná-los às suas configurações de CORS (saiba mais em [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}), usando o parâmetro `expose_headers` descrito na documentação de CORS do Starlette. From febf6b6a52e36e0d64920fb54670ad7fc29b2eaa Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 16 Oct 2024 07:45:07 +0000 Subject: [PATCH 096/932] =?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 ebdf8820c..165e1dea6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-headers.md`. PR [#12458](https://github.com/fastapi/fastapi/pull/12458) by [@leonardopaloschi](https://github.com/leonardopaloschi). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/deployment/cloud.md`. PR [#12440](https://github.com/fastapi/fastapi/pull/12440) by [@codingjenny](https://github.com/codingjenny). * 🌐 Update Portuguese translation for `docs/pt/docs/python-types.md`. PR [#12428](https://github.com/fastapi/fastapi/pull/12428) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Russian translation for `docs/ru/docs/environment-variables.md`. PR [#12436](https://github.com/fastapi/fastapi/pull/12436) by [@wisderfin](https://github.com/wisderfin). From ac3c2dd96522ca2ec653d95829f7166c96794a5e Mon Sep 17 00:00:00 2001 From: Luis Rodrigues <103431660+devluisrodrigues@users.noreply.github.com> Date: Fri, 18 Oct 2024 09:02:35 -0300 Subject: [PATCH 097/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/how-to/custom-docs-ui-assets.md`?= =?UTF-8?q?=20(#12473)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/how-to/custom-docs-ui-assets.md | 205 +++++++++++++++++++ 1 file changed, 205 insertions(+) create mode 100644 docs/pt/docs/how-to/custom-docs-ui-assets.md diff --git a/docs/pt/docs/how-to/custom-docs-ui-assets.md b/docs/pt/docs/how-to/custom-docs-ui-assets.md new file mode 100644 index 000000000..00dd144c9 --- /dev/null +++ b/docs/pt/docs/how-to/custom-docs-ui-assets.md @@ -0,0 +1,205 @@ +# Recursos Estáticos Personalizados para a UI de Documentação (Hospedagem Própria) + +A documentação da API usa **Swagger UI** e **ReDoc**, e cada um deles precisa de alguns arquivos JavaScript e CSS. + +Por padrão, esses arquivos são fornecidos por um CDN. + +Mas é possível personalizá-los, você pode definir um CDN específico ou providenciar os arquivos você mesmo. + +## CDN Personalizado para JavaScript e CSS + +Vamos supor que você deseja usar um CDN diferente, por exemplo, você deseja usar `https://unpkg.com/`. + +Isso pode ser útil se, por exemplo, você mora em um país que restringe algumas URLs. + +### Desativar a documentação automática + +O primeiro passo é desativar a documentação automática, pois por padrão, ela usa o CDN padrão. + +Para desativá-los, defina suas URLs como `None` ao criar seu aplicativo `FastAPI`: + +```Python hl_lines="8" +{!../../docs_src/custom_docs_ui/tutorial001.py!} +``` + +### Incluir a documentação personalizada + +Agora você pode criar as *operações de rota* para a documentação personalizada. + +Você pode reutilizar as funções internas do FastAPI para criar as páginas HTML para a documentação e passar os argumentos necessários: + +* `openapi_url`: a URL onde a página HTML para a documentação pode obter o esquema OpenAPI para a sua API. Você pode usar aqui o atributo `app.openapi_url`. +* `title`: o título da sua API. +* `oauth2_redirect_url`: você pode usar `app.swagger_ui_oauth2_redirect_url` aqui para usar o padrão. +* `swagger_js_url`: a URL onde a página HTML para a sua documentação do Swagger UI pode obter o arquivo **JavaScript**. Este é o URL do CDN personalizado. +* `swagger_css_url`: a URL onde a página HTML para a sua documentação do Swagger UI pode obter o arquivo **CSS**. Este é o URL do CDN personalizado. + +E de forma semelhante para o ReDoc... + +```Python hl_lines="2-6 11-19 22-24 27-33" +{!../../docs_src/custom_docs_ui/tutorial001.py!} +``` + +/// tip | Dica + +A *operação de rota* para `swagger_ui_redirect` é um auxiliar para quando você usa OAuth2. + +Se você integrar sua API com um provedor OAuth2, você poderá autenticar e voltar para a documentação da API com as credenciais adquiridas. E interagir com ela usando a autenticação OAuth2 real. + +Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse auxiliar de "redirecionamento". + +/// + +### Criar uma *operação de rota* para testar + +Agora, para poder testar se tudo funciona, crie uma *operação de rota*: + +```Python hl_lines="36-38" +{!../../docs_src/custom_docs_ui/tutorial001.py!} +``` + +### Teste + +Agora, você deve ser capaz de ir para a documentação em http://127.0.0.1:8000/docs, e recarregar a página, ela carregará esses recursos do novo CDN. + +## Hospedagem Própria de JavaScript e CSS para a documentação + +Hospedar o JavaScript e o CSS pode ser útil se, por exemplo, você precisa que seu aplicativo continue funcionando mesmo offline, sem acesso aberto à Internet, ou em uma rede local. + +Aqui você verá como providenciar esses arquivos você mesmo, no mesmo aplicativo FastAPI, e configurar a documentação para usá-los. + +### Estrutura de Arquivos do Projeto + +Vamos supor que a estrutura de arquivos do seu projeto se pareça com isso: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +``` + +Agora crie um diretório para armazenar esses arquivos estáticos. + +Sua nova estrutura de arquivos poderia se parecer com isso: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +└── static/ +``` + +### Baixe os arquivos + +Baixe os arquivos estáticos necessários para a documentação e coloque-os no diretório `static/`. + +Você provavelmente pode clicar com o botão direito em cada link e selecionar uma opção semelhante a `Salvar link como...`. + +**Swagger UI** usa os arquivos: + +* `swagger-ui-bundle.js` +* `swagger-ui.css` + +E o **ReDoc** usa os arquivos: + +* `redoc.standalone.js` + +Depois disso, sua estrutura de arquivos deve se parecer com: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +└── static + ├── redoc.standalone.js + ├── swagger-ui-bundle.js + └── swagger-ui.css +``` + +### Prover os arquivos estáticos + +* Importe `StaticFiles`. +* "Monte" a instância `StaticFiles()` em um caminho específico. + +```Python hl_lines="7 11" +{!../../docs_src/custom_docs_ui/tutorial002.py!} +``` + +### Teste os arquivos estáticos + +Inicialize seu aplicativo e vá para http://127.0.0.1:8000/static/redoc.standalone.js. + +Você deverá ver um arquivo JavaScript muito longo para o **ReDoc**. + +Esse arquivo pode começar com algo como: + +```JavaScript +/*! + * ReDoc - OpenAPI/Swagger-generated API Reference Documentation + * ------------------------------------------------------------- + * Version: "2.0.0-rc.18" + * Repo: https://github.com/Redocly/redoc + */ +!function(e,t){"object"==typeof exports&&"object"==typeof m + +... +``` + +Isso confirma que você está conseguindo fornecer arquivos estáticos do seu aplicativo e que você colocou os arquivos estáticos para a documentação no local correto. + +Agora, podemos configurar o aplicativo para usar esses arquivos estáticos para a documentação. + +### Desativar a documentação automática para arquivos estáticos + +Da mesma forma que ao usar um CDN personalizado, o primeiro passo é desativar a documentação automática, pois ela usa o CDN padrão. + +Para desativá-los, defina suas URLs como `None` ao criar seu aplicativo `FastAPI`: + +```Python hl_lines="9" +{!../../docs_src/custom_docs_ui/tutorial002.py!} +``` + +### Incluir a documentação personalizada para arquivos estáticos + +E da mesma forma que com um CDN personalizado, agora você pode criar as *operações de rota* para a documentação personalizada. + +Novamente, você pode reutilizar as funções internas do FastAPI para criar as páginas HTML para a documentação e passar os argumentos necessários: + +* `openapi_url`: a URL onde a página HTML para a documentação pode obter o esquema OpenAPI para a sua API. Você pode usar aqui o atributo `app.openapi_url`. +* `title`: o título da sua API. +* `oauth2_redirect_url`: Você pode usar `app.swagger_ui_oauth2_redirect_url` aqui para usar o padrão. +* `swagger_js_url`: a URL onde a página HTML para a sua documentação do Swagger UI pode obter o arquivo **JavaScript**. Este é o URL do CDN personalizado. **Este é o URL que seu aplicativo está fornecendo**. +* `swagger_css_url`: a URL onde a página HTML para a sua documentação do Swagger UI pode obter o arquivo **CSS**. **Esse é o que seu aplicativo está fornecendo**. + +E de forma semelhante para o ReDoc... + +```Python hl_lines="2-6 14-22 25-27 30-36" +{!../../docs_src/custom_docs_ui/tutorial002.py!} +``` + +/// tip | Dica + +A *operação de rota* para `swagger_ui_redirect` é um auxiliar para quando você usa OAuth2. + +Se você integrar sua API com um provedor OAuth2, você poderá autenticar e voltar para a documentação da API com as credenciais adquiridas. E, então, interagir com ela usando a autenticação OAuth2 real. + +Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse auxiliar de "redirect". + +/// + +### Criar uma *operação de rota* para testar arquivos estáticos + +Agora, para poder testar se tudo funciona, crie uma *operação de rota*: + +```Python hl_lines="39-41" +{!../../docs_src/custom_docs_ui/tutorial002.py!} +``` + +### Teste a UI de Arquivos Estáticos + +Agora, você deve ser capaz de desconectar o WiFi, ir para a documentação em http://127.0.0.1:8000/docs, e recarregar a página. + +E mesmo sem Internet, você será capaz de ver a documentação da sua API e interagir com ela. From b7fb8eb65626e53b151a40c9ef423333dd2e0db7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 18 Oct 2024 12:03:01 +0000 Subject: [PATCH 098/932] =?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 165e1dea6..df35e653f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/custom-docs-ui-assets.md`. PR [#12473](https://github.com/fastapi/fastapi/pull/12473) by [@devluisrodrigues](https://github.com/devluisrodrigues). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-headers.md`. PR [#12458](https://github.com/fastapi/fastapi/pull/12458) by [@leonardopaloschi](https://github.com/leonardopaloschi). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/deployment/cloud.md`. PR [#12440](https://github.com/fastapi/fastapi/pull/12440) by [@codingjenny](https://github.com/codingjenny). * 🌐 Update Portuguese translation for `docs/pt/docs/python-types.md`. PR [#12428](https://github.com/fastapi/fastapi/pull/12428) by [@ceb10n](https://github.com/ceb10n). From 48849f8a11ad82e9dfbc5c399cc2687465f111ae Mon Sep 17 00:00:00 2001 From: Guilherme Rameh <62567654+GuilhermeRameh@users.noreply.github.com> Date: Fri, 18 Oct 2024 09:04:04 -0300 Subject: [PATCH 099/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/how-to/testing-database.md`=20(#12?= =?UTF-8?q?472)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/how-to/testing-database.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 docs/pt/docs/how-to/testing-database.md diff --git a/docs/pt/docs/how-to/testing-database.md b/docs/pt/docs/how-to/testing-database.md new file mode 100644 index 000000000..02f909f24 --- /dev/null +++ b/docs/pt/docs/how-to/testing-database.md @@ -0,0 +1,7 @@ +# Testando a Base de Dados + +Você pode estudar sobre bases de dados, SQL e SQLModel na documentação de SQLModel. 🤓 + +Aqui tem um mini tutorial de como usar SQLModel com FastAPI. ✨ + +Esse tutorial inclui uma sessão sobre testar bases de dados SQL. 😎 From 7038bedc5dad0adfa578d0d2983defabf7d7da57 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 18 Oct 2024 12:05:45 +0000 Subject: [PATCH 100/932] =?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 df35e653f..d795d59ad 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/testing-database.md`. PR [#12472](https://github.com/fastapi/fastapi/pull/12472) by [@GuilhermeRameh](https://github.com/GuilhermeRameh). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/custom-docs-ui-assets.md`. PR [#12473](https://github.com/fastapi/fastapi/pull/12473) by [@devluisrodrigues](https://github.com/devluisrodrigues). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-headers.md`. PR [#12458](https://github.com/fastapi/fastapi/pull/12458) by [@leonardopaloschi](https://github.com/leonardopaloschi). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/deployment/cloud.md`. PR [#12440](https://github.com/fastapi/fastapi/pull/12440) by [@codingjenny](https://github.com/codingjenny). From 53d90074e5996ed0a3c42d352d6d7edab299a43b Mon Sep 17 00:00:00 2001 From: YungYueh ChanLee Date: Fri, 18 Oct 2024 20:10:00 +0800 Subject: [PATCH 101/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Traditional=20Chin?= =?UTF-8?q?ese=20translation=20for=20`docs/zh-hant/docs/deployment/index.m?= =?UTF-8?q?d`=20(#12439)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/deployment/index.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 docs/zh-hant/docs/deployment/index.md diff --git a/docs/zh-hant/docs/deployment/index.md b/docs/zh-hant/docs/deployment/index.md new file mode 100644 index 000000000..e760b3d16 --- /dev/null +++ b/docs/zh-hant/docs/deployment/index.md @@ -0,0 +1,21 @@ +# 部署 + +部署 **FastAPI** 應用程式相對容易。 + +## 部署是什麼意思 + +**部署** 應用程式指的是執行一系列必要的步驟,使其能夠 **讓使用者存取和使用**。 + +對於一個 **Web API**,部署通常涉及將其放置在 **遠端伺服器** 上,並使用性能優良且穩定的 **伺服器程式**,確保使用者能夠高效、無中斷地存取應用程式,且不會遇到問題。 + +這與 **開發** 階段形成鮮明對比,在 **開發** 階段,你會不斷更改程式碼、破壞程式碼、修復程式碼,然後停止和重新啟動伺服器等。 + +## 部署策略 + +根據你的使用場景和使用工具,有多種方法可以實現此目的。 + +你可以使用一些工具自行 **部署伺服器**,你也可以使用能為你完成部分工作的 **雲端服務**,或其他可能的選項。 + +我將向你展示在部署 **FastAPI** 應用程式時你可能應該記住的一些主要概念(儘管其中大部分適用於任何其他類型的 Web 應用程式)。 + +在接下來的部分中,你將看到更多需要記住的細節以及一些技巧。 ✨ From b0761c2552c630a503cf21016ace3f6cc919c049 Mon Sep 17 00:00:00 2001 From: YungYueh ChanLee Date: Fri, 18 Oct 2024 20:12:01 +0800 Subject: [PATCH 102/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Traditional=20Chin?= =?UTF-8?q?ese=20translation=20for=20`docs/zh-hant/docs/fastapi-cli.md`=20?= =?UTF-8?q?(#12444)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/fastapi-cli.md | 83 ++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 docs/zh-hant/docs/fastapi-cli.md diff --git a/docs/zh-hant/docs/fastapi-cli.md b/docs/zh-hant/docs/fastapi-cli.md new file mode 100644 index 000000000..3c644ce46 --- /dev/null +++ b/docs/zh-hant/docs/fastapi-cli.md @@ -0,0 +1,83 @@ +# FastAPI CLI + +**FastAPI CLI** 是一個命令列程式,能用來運行你的 FastAPI 應用程式、管理你的 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** 內部使用了 Uvicorn,這是一個高效能、適合生產環境的 ASGI 伺服器。 😎 + +## `fastapi dev` + +執行 `fastapi dev` 會啟動開發模式。 + +預設情況下,**auto-reload** 功能是啟用的,當你對程式碼進行修改時,伺服器會自動重新載入。這會消耗較多資源,並且可能比禁用時更不穩定。因此,你應該只在開發環境中使用此功能。它也會在 IP 位址 `127.0.0.1` 上監聽,這是用於你的機器與自身通訊的 IP 位址(`localhost`)。 + +## `fastapi run` + +執行 `fastapi run` 會以生產模式啟動 FastAPI。 + +預設情況下,**auto-reload** 功能是禁用的。它也會在 IP 位址 `0.0.0.0` 上監聽,表示會監聽所有可用的 IP 地址,這樣任何能與該機器通訊的人都可以公開存取它。這通常是你在生產環境中運行應用程式的方式,例如在容器中運行時。 + +在大多數情況下,你會(也應該)有一個「終止代理」來處理 HTTPS,這取決於你如何部署你的應用程式,你的服務供應商可能會為你做這件事,或者你需要自己設置它。 + +/// tip + +你可以在[部署文件](deployment/index.md){.internal-link target=_blank}中了解更多相關資訊。 + +/// From f0b5f8adf785e7c36dbcad407d8c47655494f31b Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 18 Oct 2024 12:12:24 +0000 Subject: [PATCH 103/932] =?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 d795d59ad..fe056d237 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/deployment/index.md`. PR [#12439](https://github.com/fastapi/fastapi/pull/12439) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/testing-database.md`. PR [#12472](https://github.com/fastapi/fastapi/pull/12472) by [@GuilhermeRameh](https://github.com/GuilhermeRameh). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/custom-docs-ui-assets.md`. PR [#12473](https://github.com/fastapi/fastapi/pull/12473) by [@devluisrodrigues](https://github.com/devluisrodrigues). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/response-headers.md`. PR [#12458](https://github.com/fastapi/fastapi/pull/12458) by [@leonardopaloschi](https://github.com/leonardopaloschi). From 5afa6d70666e4f6afee6eab91453d725f4b637a3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 18 Oct 2024 12:13:10 +0000 Subject: [PATCH 104/932] =?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 fe056d237..0afecc6d4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/fastapi-cli.md`. PR [#12444](https://github.com/fastapi/fastapi/pull/12444) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/deployment/index.md`. PR [#12439](https://github.com/fastapi/fastapi/pull/12439) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/testing-database.md`. PR [#12472](https://github.com/fastapi/fastapi/pull/12472) by [@GuilhermeRameh](https://github.com/GuilhermeRameh). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/custom-docs-ui-assets.md`. PR [#12473](https://github.com/fastapi/fastapi/pull/12473) by [@devluisrodrigues](https://github.com/devluisrodrigues). From 4c1a1938bc8d4440bd0014aca2576cd3374f401b Mon Sep 17 00:00:00 2001 From: Elton Jefferson Date: Sun, 20 Oct 2024 16:20:23 -0300 Subject: [PATCH 105/932] =?UTF-8?q?=F0=9F=93=9D=20Fix=20broken=20link=20in?= =?UTF-8?q?=20docs=20(#12495)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/az/docs/index.md | 2 +- docs/bn/docs/index.md | 2 +- docs/de/docs/alternatives.md | 2 +- docs/de/docs/index.md | 2 +- docs/em/docs/alternatives.md | 2 +- docs/em/docs/index.md | 2 +- docs/en/docs/alternatives.md | 2 +- docs/en/docs/index.md | 2 +- docs/es/docs/index.md | 2 +- docs/fa/docs/index.md | 2 +- docs/fr/docs/alternatives.md | 2 +- docs/fr/docs/index.md | 2 +- docs/he/docs/index.md | 2 +- docs/hu/docs/index.md | 2 +- docs/it/docs/index.md | 2 +- docs/ja/docs/index.md | 2 +- docs/nl/docs/index.md | 2 +- docs/pl/docs/index.md | 2 +- docs/pt/docs/alternatives.md | 2 +- docs/pt/docs/index.md | 2 +- docs/ru/docs/alternatives.md | 2 +- docs/ru/docs/index.md | 2 +- docs/tr/docs/alternatives.md | 2 +- docs/uk/docs/alternatives.md | 2 +- docs/uk/docs/index.md | 2 +- docs/vi/docs/index.md | 2 +- docs/yo/docs/index.md | 2 +- docs/zh-hant/docs/index.md | 2 +- docs/zh/docs/index.md | 2 +- 30 files changed, 30 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index f274265de..a12e740f7 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,7 @@ The key features are: "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- diff --git a/docs/az/docs/index.md b/docs/az/docs/index.md index b5d7f8f92..ad78d7d06 100644 --- a/docs/az/docs/index.md +++ b/docs/az/docs/index.md @@ -87,7 +87,7 @@ FastAPI Python ilə API yaratmaq üçün standart Python Timothy Crosley - Hug creator (ref)

$5q*9#iM5)%>&v0gd! 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 KzDn-xr~eO~3Q%MK diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 7836efae1..972eb9308 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -1,22 +1,18 @@ # SQL (Relational) Databases -/// info +**FastAPI** doesn't require you to use a SQL (relational) database. But you can use **any database** that you want. -These docs are about to be updated. 🎉 +Here we'll see an example using SQLModel. -The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0. +**SQLModel** is built on top of SQLAlchemy and Pydantic. It was made by the same author of **FastAPI** to be the perfect match for FastAPI applications that need to use **SQL databases**. -The new docs will include Pydantic v2 and will use SQLModel (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well. - -/// - -**FastAPI** doesn't require you to use a SQL (relational) database. +/// tip -But you can use any relational database that you want. +You could use any other SQL or NoSQL database library you want (in some cases called "ORMs"), FastAPI doesn't force you to use anything. 😎 -Here we'll see an example using SQLAlchemy. +/// -You can easily adapt it to any database supported by SQLAlchemy, like: +As SQLModel is based on SQLAlchemy, you can easily use **any database supported** by SQLAlchemy (which makes them also supported by SQLModel), like: * PostgreSQL * MySQL @@ -30,891 +26,335 @@ Later, for your production application, you might want to use a database server /// tip -There is an official project generator with **FastAPI** and **PostgreSQL**, all based on **Docker**, including a frontend and more tools: https://github.com/tiangolo/full-stack-fastapi-postgresql - -/// - -/// note - -Notice that most of the code is the standard `SQLAlchemy` code you would use with any framework. - -The **FastAPI** specific code is as small as always. - -/// - -## ORMs - -**FastAPI** works with any database and any style of library to talk to the database. - -A common pattern is to use an "ORM": an "object-relational mapping" library. - -An ORM has tools to convert ("*map*") between *objects* in code and database tables ("*relations*"). - -With an ORM, you normally create a class that represents a table in a SQL database, each attribute of the class represents a column, with a name and a type. - -For example a class `Pet` could represent a SQL table `pets`. - -And each *instance* object of that class represents a row in the database. - -For example an object `orion_cat` (an instance of `Pet`) could have an attribute `orion_cat.type`, for the column `type`. And the value of that attribute could be, e.g. `"cat"`. - -These ORMs also have tools to make the connections or relations between tables or entities. - -This way, you could also have an attribute `orion_cat.owner` and the owner would contain the data for this pet's owner, taken from the table *owners*. - -So, `orion_cat.owner.name` could be the name (from the `name` column in the `owners` table) of this pet's owner. - -It could have a value like `"Arquilian"`. - -And the ORM will do all the work to get the information from the corresponding table *owners* when you try to access it from your pet object. - -Common ORMs are for example: Django-ORM (part of the Django framework), SQLAlchemy ORM (part of SQLAlchemy, independent of framework) and Peewee (independent of framework), among others. - -Here we will see how to work with **SQLAlchemy ORM**. - -In a similar way you could use any other ORM. - -/// tip - -There's an equivalent article using Peewee here in the docs. +There is an official project generator with **FastAPI** and **PostgreSQL** including a frontend and more tools: https://github.com/fastapi/full-stack-fastapi-template /// -## File structure - -For these examples, let's say you have a directory named `my_super_project` that contains a sub-directory called `sql_app` with a structure like this: - -``` -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - └── schemas.py -``` - -The file `__init__.py` is just an empty file, but it tells Python that `sql_app` with all its modules (Python files) is a package. - -Now let's see what each file/module does. - -## Install `SQLAlchemy` +This is a very simple and short tutorial, if you want to learn about databases in general, about SQL, or more advanced features, go to the SQLModel docs. -First you need to install `SQLAlchemy`. +## Install `SQLModel` -Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: +First, make sure you create your [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install `sqlmodel`:

+
Timothy Crosley - Hug creator (ref)
--- diff --git a/docs/bn/docs/index.md b/docs/bn/docs/index.md index c882506ff..678ac9ca9 100644 --- a/docs/bn/docs/index.md +++ b/docs/bn/docs/index.md @@ -85,7 +85,7 @@ FastAPI একটি আধুনিক, দ্রুত ( বেশি ক্ "\_সত্যিই, আপনি যা তৈরি করেছেন তা খুব মজবুত এবং পরিপূর্ন৷ অনেক উপায়ে, আমি যা **Hug** এ করতে চেয়েছিলাম - তা কাউকে তৈরি করতে দেখে আমি সত্যিই অনুপ্রানিত৷\_" -
টিমোথি ক্রসলে - Hug স্রষ্টা (ref)
+
টিমোথি ক্রসলে - Hug স্রষ্টা (ref)
--- diff --git a/docs/de/docs/alternatives.md b/docs/de/docs/alternatives.md index 286ef1723..49e1cc6f0 100644 --- a/docs/de/docs/alternatives.md +++ b/docs/de/docs/alternatives.md @@ -321,7 +321,7 @@ Das hat tatsächlich dazu geführt, dass Teile von Pydantic aktualisiert wurden, /// -### Hug +### Hug Hug war eines der ersten Frameworks, welches die Deklaration von API-Parametertypen mithilfe von Python-Typhinweisen implementierte. Das war eine großartige Idee, die andere Tools dazu inspirierte, dasselbe zu tun. diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md index af024d18d..411c8e969 100644 --- a/docs/de/docs/index.md +++ b/docs/de/docs/index.md @@ -94,7 +94,7 @@ Seine Schlüssel-Merkmale sind: „_Ehrlich, was Du gebaut hast, sieht super solide und poliert aus. In vielerlei Hinsicht ist es so, wie ich **Hug** haben wollte – es ist wirklich inspirierend, jemanden so etwas bauen zu sehen._“ -
Timothy Crosley - Autor von Hug (Ref)
+
Timothy Crosley - Autor von Hug (Ref)
--- diff --git a/docs/em/docs/alternatives.md b/docs/em/docs/alternatives.md index 334c0de73..5309de51f 100644 --- a/docs/em/docs/alternatives.md +++ b/docs/em/docs/alternatives.md @@ -321,7 +321,7 @@ APISpec ✍ 🎏 🍭 👩‍💻. /// -### 🤗 +### 🤗 🤗 🕐 🥇 🛠️ 🛠️ 📄 🛠️ 🔢 🆎 ⚙️ 🐍 🆎 🔑. 👉 👑 💭 👈 😮 🎏 🧰 🎏. diff --git a/docs/em/docs/index.md b/docs/em/docs/index.md index aa7542366..16b2019d3 100644 --- a/docs/em/docs/index.md +++ b/docs/em/docs/index.md @@ -93,7 +93,7 @@ FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.8️ "_🤙, ⚫️❔ 👆 ✔️ 🏗 👀 💎 💠 & 🇵🇱. 📚 🌌, ⚫️ ⚫️❔ 👤 💚 **🤗** - ⚫️ 🤙 😍 👀 👱 🏗 👈._" -
✡ 🗄 - 🤗 👼 (🇦🇪)
+
✡ 🗄 - 🤗 👼 (🇦🇪)
--- diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md index e98c0475a..f596232d3 100644 --- a/docs/en/docs/alternatives.md +++ b/docs/en/docs/alternatives.md @@ -321,7 +321,7 @@ This actually inspired updating parts of Pydantic, to support the same validatio /// -### Hug +### Hug Hug was one of the first frameworks to implement the declaration of API parameter types using Python type hints. This was a great idea that inspired other tools to do the same. diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index 3ed3d7bf6..4d0514241 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -93,7 +93,7 @@ The key features are: "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md index fe4912253..73d9b679e 100644 --- a/docs/es/docs/index.md +++ b/docs/es/docs/index.md @@ -90,7 +90,7 @@ Sus características principales son: "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md index 1ae566a9f..6addce763 100644 --- a/docs/fa/docs/index.md +++ b/docs/fa/docs/index.md @@ -90,7 +90,7 @@ FastAPI یک وب فریم‌ورک مدرن و سریع (با کارایی با
"Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted Hug to be - it's really inspiring to see someone build that."
-
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- diff --git a/docs/fr/docs/alternatives.md b/docs/fr/docs/alternatives.md index 059a60b69..d2438dc36 100644 --- a/docs/fr/docs/alternatives.md +++ b/docs/fr/docs/alternatives.md @@ -351,7 +351,7 @@ Cela a en fait inspiré la mise à jour de certaines parties de Pydantic, afin d /// -### Hug +### Hug Hug a été l'un des premiers frameworks à implémenter la déclaration des types de paramètres d'API en utilisant les type hints Python. C'était une excellente idée qui a inspiré d'autres outils à faire de même. diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md index dccefdd5a..695429008 100644 --- a/docs/fr/docs/index.md +++ b/docs/fr/docs/index.md @@ -93,7 +93,7 @@ Les principales fonctionnalités sont : "_Honnêtement, ce que vous avez construit a l'air super solide et élégant. A bien des égards, c'est comme ça que je voulais que **Hug** soit - c'est vraiment inspirant de voir quelqu'un construire ça._" -
Timothy Crosley - Créateur de Hug (ref)
+
Timothy Crosley - Créateur de Hug (ref)
--- diff --git a/docs/he/docs/index.md b/docs/he/docs/index.md index 23a2eb824..6498d15e1 100644 --- a/docs/he/docs/index.md +++ b/docs/he/docs/index.md @@ -94,7 +94,7 @@ FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים ג "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md index 8e326a78b..c6f596650 100644 --- a/docs/hu/docs/index.md +++ b/docs/hu/docs/index.md @@ -87,7 +87,7 @@ Kulcs funkciók: "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md index 3bfff82f1..8a1039bc5 100644 --- a/docs/it/docs/index.md +++ b/docs/it/docs/index.md @@ -84,7 +84,7 @@ Le sue caratteristiche principali sono: "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index 72a0e98bc..682c94e83 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -91,7 +91,7 @@ FastAPI は、Pythonの標準である型ヒントに基づいてPython 以降 "_正直、超堅実で洗練されているように見えます。いろんな意味で、それは私がハグしたかったものです。_" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- diff --git a/docs/nl/docs/index.md b/docs/nl/docs/index.md index 8edc3ba0c..d88bb7771 100644 --- a/docs/nl/docs/index.md +++ b/docs/nl/docs/index.md @@ -93,7 +93,7 @@ De belangrijkste kenmerken zijn: "_Wat je hebt gebouwd ziet er echt super solide en gepolijst uit. In veel opzichten is het wat ik wilde dat **Hug** kon zijn - het is echt inspirerend om iemand dit te zien bouwen._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index e591e1c9d..9a96c6553 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -90,7 +90,7 @@ Kluczowe cechy: "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- diff --git a/docs/pt/docs/alternatives.md b/docs/pt/docs/alternatives.md index d3a304fa7..2a2632bbc 100644 --- a/docs/pt/docs/alternatives.md +++ b/docs/pt/docs/alternatives.md @@ -323,7 +323,7 @@ Isso na verdade inspirou a atualização de partes do Pydantic, para dar suporte /// -### Hug +### Hug Hug foi um dos primeiros frameworks a implementar a declaração de tipos de parâmetros usando Python _type hints_. Isso foi uma ótima idéia que inspirou outras ferramentas a fazer o mesmo. diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md index f99144617..bc23114dc 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -78,7 +78,7 @@ Os recursos chave são: "*Honestamente, o que você construiu parece super sólido e rebuscado. De muitas formas, eu queria que o **Hug** fosse assim - é realmente inspirador ver alguém que construiu ele.*" -
Timothy Crosley - criador doHug (ref)
+
Timothy Crosley - criador doHug (ref)
--- diff --git a/docs/ru/docs/alternatives.md b/docs/ru/docs/alternatives.md index 413bf70b2..f83024ad9 100644 --- a/docs/ru/docs/alternatives.md +++ b/docs/ru/docs/alternatives.md @@ -357,7 +357,7 @@ Molten мне попался на начальной стадии написан /// -### Hug +### Hug Hug был одним из первых фреймворков, реализовавших объявление параметров API с использованием подсказок типов Python. Эта отличная идея была использована и другими инструментами. diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 3aa4d82d0..5ebe1494b 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -93,7 +93,7 @@ FastAPI — это современный, быстрый (высокопрои "_Честно говоря, то, что вы создали, выглядит очень солидно и отполировано. Во многих смыслах я хотел, чтобы **Hug** был именно таким — это действительно вдохновляет, когда кто-то создаёт такое._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- diff --git a/docs/tr/docs/alternatives.md b/docs/tr/docs/alternatives.md index bd668ca45..286b7897a 100644 --- a/docs/tr/docs/alternatives.md +++ b/docs/tr/docs/alternatives.md @@ -319,7 +319,7 @@ Bu aslında Pydantic'in de aynı doğrulama stiline geçmesinde ilham kaynağı /// -### Hug +### Hug Hug, Python tip belirteçlerini kullanarak API parametrelerinin tipini belirlemeyi uygulayan ilk framework'lerdendi. Bu, diğer araçlara da ilham kaynağı olan harika bir fikirdi. diff --git a/docs/uk/docs/alternatives.md b/docs/uk/docs/alternatives.md index eb48d6be7..6821ffe70 100644 --- a/docs/uk/docs/alternatives.md +++ b/docs/uk/docs/alternatives.md @@ -321,7 +321,7 @@ Falcon — ще один високопродуктивний фреймворк /// -### Hug +### Hug Hug був одним із перших фреймворків, який реалізував оголошення типів параметрів API за допомогою підказок типу Python. Це була чудова ідея, яка надихнула інші інструменти зробити те саме. diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md index 4c8c54af2..012bac2e2 100644 --- a/docs/uk/docs/index.md +++ b/docs/uk/docs/index.md @@ -88,7 +88,7 @@ FastAPI - це сучасний, швидкий (високопродуктив "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- diff --git a/docs/vi/docs/index.md b/docs/vi/docs/index.md index 09deac6f2..5e346ded8 100644 --- a/docs/vi/docs/index.md +++ b/docs/vi/docs/index.md @@ -93,7 +93,7 @@ Những tính năng như: "_Thành thật, những gì bạn đã xây dựng nhìn siêu chắc chắn và bóng bẩy. Theo nhiều cách, nó là những gì tôi đã muốn Hug trở thành - thật sự truyền cảm hứng để thấy ai đó xây dựng nó._" -
Timothy Crosley - người tạo ra Hug (ref)
+
Timothy Crosley - người tạo ra Hug (ref)
--- diff --git a/docs/yo/docs/index.md b/docs/yo/docs/index.md index ee7f56220..3ad1483de 100644 --- a/docs/yo/docs/index.md +++ b/docs/yo/docs/index.md @@ -93,7 +93,7 @@ FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́b "_Ní tòótọ́, ohun tí o kọ dára ó sì tún dán. Ní ọ̀pọ̀lọpọ̀ ọ̀nà, ohun tí mo fẹ́ kí **Hug** jẹ́ nìyẹn - ó wúni lórí gan-an láti rí ẹnìkan tí ó kọ́ nǹkan bí èyí._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- diff --git a/docs/zh-hant/docs/index.md b/docs/zh-hant/docs/index.md index d260b5b79..137a17284 100644 --- a/docs/zh-hant/docs/index.md +++ b/docs/zh-hant/docs/index.md @@ -87,7 +87,7 @@ FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python "_老實說,你建造的東西看起來非常堅固和精緻。在很多方面,這就是我想要的,看到有人建造它真的很鼓舞人心。_" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index 777240ec2..d3e9e3112 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -94,7 +94,7 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框 「_老实说,你的作品看起来非常可靠和优美。在很多方面,这就是我想让 **Hug** 成为的样子 - 看到有人实现了它真的很鼓舞人心。_」 -
Timothy Crosley - Hug 作者 (ref)
+
Timothy Crosley - Hug 作者 (ref)
--- From 45822d31f265861dff27e9d2a935c87aafb101b3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 20 Oct 2024 19:20:44 +0000 Subject: [PATCH 106/932] =?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 0afecc6d4..1279ac3f1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Fix broken link in docs. PR [#12495](https://github.com/fastapi/fastapi/pull/12495) by [@eltonjncorreia](https://github.com/eltonjncorreia). + ### Translations * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/fastapi-cli.md`. PR [#12444](https://github.com/fastapi/fastapi/pull/12444) by [@codingjenny](https://github.com/codingjenny). From c4f8143dea31699bf015ad3c885f91c68788abfb Mon Sep 17 00:00:00 2001 From: Marcel Hellkamp Date: Tue, 22 Oct 2024 16:19:56 +0200 Subject: [PATCH 107/932] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20Starlett?= =?UTF-8?q?e=20to=20`>=3D0.40.0,<0.42.0`=20(#12469)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index c934356d8..edfa81522 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,7 +41,7 @@ classifiers = [ "Topic :: Internet :: WWW/HTTP", ] dependencies = [ - "starlette>=0.37.2,<0.41.0", + "starlette>=0.40.0,<0.42.0", "pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0", "typing-extensions>=4.8.0", ] From 9c794c9c0d0a10e3bc3516624d30ccaca22f1e18 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 22 Oct 2024 14:20:24 +0000 Subject: [PATCH 108/932] =?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 1279ac3f1..9cd739cf1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Upgrades + +* ⬆️ Upgrade Starlette to `>=0.40.0,<0.42.0`. PR [#12469](https://github.com/fastapi/fastapi/pull/12469) by [@defnull](https://github.com/defnull). + ### Docs * 📝 Fix broken link in docs. PR [#12495](https://github.com/fastapi/fastapi/pull/12495) by [@eltonjncorreia](https://github.com/eltonjncorreia). From c519614b45009e7d51f010e82b0ddf77a327e327 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 22 Oct 2024 15:26:52 +0100 Subject: [PATCH 109/932] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?5.3?= 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 9cd739cf1..be8f67ad6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.115.3 + ### Upgrades * ⬆️ Upgrade Starlette to `>=0.40.0,<0.42.0`. PR [#12469](https://github.com/fastapi/fastapi/pull/12469) by [@defnull](https://github.com/defnull). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 77b52f35b..64d5dd39b 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.2" +__version__ = "0.115.3" from starlette import status as status From 94fafa5030e0c1c036359e5b3d7b3db7b4b2114d Mon Sep 17 00:00:00 2001 From: Fernando Alzueta Date: Tue, 22 Oct 2024 14:33:00 -0300 Subject: [PATCH 110/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/how-to/custom-request-and-route.md?= =?UTF-8?q?`=20(#12483)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/how-to/custom-request-and-route.md | 121 ++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 docs/pt/docs/how-to/custom-request-and-route.md diff --git a/docs/pt/docs/how-to/custom-request-and-route.md b/docs/pt/docs/how-to/custom-request-and-route.md new file mode 100644 index 000000000..64325eed9 --- /dev/null +++ b/docs/pt/docs/how-to/custom-request-and-route.md @@ -0,0 +1,121 @@ +# Requisições Personalizadas e Classes da APIRoute + +Em algum casos, você pode querer sobreescrever a lógica usada pelas classes `Request`e `APIRoute`. + +Em particular, isso pode ser uma boa alternativa para uma lógica em um middleware + +Por exemplo, se você quiser ler ou manipular o corpo da requisição antes que ele seja processado pela sua aplicação. + +/// danger | Perigo + +Isso é um recurso "avançado". + +Se você for um iniciante em **FastAPI** você deve considerar pular essa seção. + +/// + +## Casos de Uso + +Alguns casos de uso incluem: + +* Converter requisições não-JSON para JSON (por exemplo, `msgpack`). +* Descomprimir corpos de requisição comprimidos com gzip. +* Registrar automaticamente todos os corpos de requisição. + +## Manipulando codificações de corpo de requisição personalizadas + +Vamos ver como usar uma subclasse personalizada de `Request` para descomprimir requisições gzip. + +E uma subclasse de `APIRoute` para usar essa classe de requisição personalizada. + +### Criar uma classe `GzipRequest` personalizada + +/// tip | Dica + +Isso é um exemplo de brincadeira para demonstrar como funciona, se você precisar de suporte para Gzip, você pode usar o [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} fornecido. + +/// + +Primeiro, criamos uma classe `GzipRequest`, que irá sobrescrever o método `Request.body()` para descomprimir o corpo na presença de um cabeçalho apropriado. + +Se não houver `gzip` no cabeçalho, ele não tentará descomprimir o corpo. + +Dessa forma, a mesma classe de rota pode lidar com requisições comprimidas ou não comprimidas. + +```Python hl_lines="8-15" +{!../../docs_src/custom_request_and_route/tutorial001.py!} +``` + +### Criar uma classe `GzipRoute` personalizada + +Em seguida, criamos uma subclasse personalizada de `fastapi.routing.APIRoute` que fará uso do `GzipRequest`. + +Dessa vez, ele irá sobrescrever o método `APIRoute.get_route_handler()`. + +Esse método retorna uma função. E essa função é o que irá receber uma requisição e retornar uma resposta. + +Aqui nós usamos para criar um `GzipRequest` a partir da requisição original. + +```Python hl_lines="18-26" +{!../../docs_src/custom_request_and_route/tutorial001.py!} +``` + +/// note | Detalhes Técnicos + +Um `Request` também tem um `request.receive`, que é uma função para "receber" o corpo da requisição. + +Um `Request` também tem um `request.receive`, que é uma função para "receber" o corpo da requisição. + +O dicionário `scope` e a função `receive` são ambos parte da especificação ASGI. + +E essas duas coisas, `scope` e `receive`, são o que é necessário para criar uma nova instância de `Request`. + +Para aprender mais sobre o `Request` confira a documentação do Starlette sobre Requests. + +/// + +A única coisa que a função retornada por `GzipRequest.get_route_handler` faz de diferente é converter o `Request` para um `GzipRequest`. + +Fazendo isso, nosso `GzipRequest` irá cuidar de descomprimir os dados (se necessário) antes de passá-los para nossas *operações de rota*. + +Depois disso, toda a lógica de processamento é a mesma. + +Mas por causa das nossas mudanças em `GzipRequest.body`, o corpo da requisição será automaticamente descomprimido quando for carregado pelo **FastAPI** quando necessário. + +## Acessando o corpo da requisição em um manipulador de exceção + +/// tip | Dica + +Para resolver esse mesmo problema, é provavelmente muito mais fácil usar o `body` em um manipulador personalizado para `RequestValidationError` ([Tratando Erros](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}). + +Mas esse exemplo ainda é valido e mostra como interagir com os componentes internos. + +/// + +Também podemos usar essa mesma abordagem para acessar o corpo da requisição em um manipulador de exceção. + +Tudo que precisamos fazer é manipular a requisição dentro de um bloco `try`/`except`: + +```Python hl_lines="13 15" +{!../../docs_src/custom_request_and_route/tutorial002.py!} +``` + +Se uma exceção ocorrer, a instância `Request` ainda estará em escopo, então podemos ler e fazer uso do corpo da requisição ao lidar com o erro: + +```Python hl_lines="16-18" +{!../../docs_src/custom_request_and_route/tutorial002.py!} +``` + +## Classe `APIRoute` personalizada em um router + +você também pode definir o parametro `route_class` de uma `APIRouter`; + +```Python hl_lines="26" +{!../../docs_src/custom_request_and_route/tutorial003.py!} +``` + +Nesse exemplo, as *operações de rota* sob o `router` irão usar a classe `TimedRoute` personalizada, e terão um cabeçalho extra `X-Response-Time` na resposta com o tempo que levou para gerar a resposta: + +```Python hl_lines="13-20" +{!../../docs_src/custom_request_and_route/tutorial003.py!} +``` From cb74448bd9ce310ac63ef35e0bee320d80b112d8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 22 Oct 2024 17:33:23 +0000 Subject: [PATCH 111/932] =?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 be8f67ad6..10977949d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Translations + +* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/custom-request-and-route.md`. PR [#12483](https://github.com/fastapi/fastapi/pull/12483) by [@devfernandoa](https://github.com/devfernandoa). + ## 0.115.3 ### Upgrades From bbcee4db19cc54bcac3dbbab020c2f247bdac639 Mon Sep 17 00:00:00 2001 From: Leonardo Scarlato <101352133+leoscarlato@users.noreply.github.com> Date: Tue, 22 Oct 2024 14:33:53 -0300 Subject: [PATCH 112/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/dataclasses.md`=20(#12475?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/dataclasses.md | 101 +++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 docs/pt/docs/advanced/dataclasses.md diff --git a/docs/pt/docs/advanced/dataclasses.md b/docs/pt/docs/advanced/dataclasses.md new file mode 100644 index 000000000..af603ada7 --- /dev/null +++ b/docs/pt/docs/advanced/dataclasses.md @@ -0,0 +1,101 @@ +# Usando Dataclasses + +FastAPI é construído em cima do **Pydantic**, e eu tenho mostrado como usar modelos Pydantic para declarar requisições e respostas. + +Mas o FastAPI também suporta o uso de `dataclasses` da mesma forma: + +```Python hl_lines="1 7-12 19-20" +{!../../docs_src/dataclasses/tutorial001.py!} +``` + +Isso ainda é suportado graças ao **Pydantic**, pois ele tem suporte interno para `dataclasses`. + +Então, mesmo com o código acima que não usa Pydantic explicitamente, o FastAPI está usando Pydantic para converter essas dataclasses padrão para a versão do Pydantic. + +E claro, ele suporta o mesmo: + +* validação de dados +* serialização de dados +* documentação de dados, etc. + +Isso funciona da mesma forma que com os modelos Pydantic. E na verdade é alcançado da mesma maneira por baixo dos panos, usando Pydantic. + +/// info | Informação + +Lembre-se de que dataclasses não podem fazer tudo o que os modelos Pydantic podem fazer. + +Então, você ainda pode precisar usar modelos Pydantic. + +Mas se você tem um monte de dataclasses por aí, este é um truque legal para usá-las para alimentar uma API web usando FastAPI. 🤓 + +/// + +## Dataclasses em `response_model` + +Você também pode usar `dataclasses` no parâmetro `response_model`: + +```Python hl_lines="1 7-13 19" +{!../../docs_src/dataclasses/tutorial002.py!} +``` + +A dataclass será automaticamente convertida para uma dataclass Pydantic. + +Dessa forma, seu esquema aparecerá na interface de documentação da API: + + + +## Dataclasses em Estruturas de Dados Aninhadas + +Você também pode combinar `dataclasses` com outras anotações de tipo para criar estruturas de dados aninhadas. + +Em alguns casos, você ainda pode ter que usar a versão do Pydantic das `dataclasses`. Por exemplo, se você tiver erros com a documentação da API gerada automaticamente. + +Nesse caso, você pode simplesmente trocar as `dataclasses` padrão por `pydantic.dataclasses`, que é um substituto direto: + +```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } +{!../../docs_src/dataclasses/tutorial003.py!} +``` + +1. Ainda importamos `field` das `dataclasses` padrão. + +2. `pydantic.dataclasses` é um substituto direto para `dataclasses`. + +3. A dataclass `Author` inclui uma lista de dataclasses `Item`. + +4. A dataclass `Author` é usada como o parâmetro `response_model`. + +5. Você pode usar outras anotações de tipo padrão com dataclasses como o corpo da requisição. + + Neste caso, é uma lista de dataclasses `Item`. + +6. Aqui estamos retornando um dicionário que contém `items`, que é uma lista de dataclasses. + + O FastAPI ainda é capaz de serializar os dados para JSON. + +7. Aqui o `response_model` está usando uma anotação de tipo de uma lista de dataclasses `Author`. + + Novamente, você pode combinar `dataclasses` com anotações de tipo padrão. + +8. Note que esta *função de operação de rota* usa `def` regular em vez de `async def`. + + Como sempre, no FastAPI você pode combinar `def` e `async def` conforme necessário. + + Se você precisar de uma atualização sobre quando usar qual, confira a seção _"Com pressa?"_ na documentação sobre [`async` e `await`](../async.md#in-a-hurry){.internal-link target=_blank}. + +9. Esta *função de operação de rota* não está retornando dataclasses (embora pudesse), mas uma lista de dicionários com dados internos. + + O FastAPI usará o parâmetro `response_model` (que inclui dataclasses) para converter a resposta. + +Você pode combinar `dataclasses` com outras anotações de tipo em muitas combinações diferentes para formar estruturas de dados complexas. + +Confira as dicas de anotação no código acima para ver mais detalhes específicos. + +## Saiba Mais + +Você também pode combinar `dataclasses` com outros modelos Pydantic, herdar deles, incluí-los em seus próprios modelos, etc. + +Para saber mais, confira a documentação do Pydantic sobre dataclasses. + +## Versão + +Isso está disponível desde a versão `0.67.0` do FastAPI. 🔖 From 396c0f6aab738c9ace0c4efc6ff923ff09e82a0e Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 22 Oct 2024 17:36:16 +0000 Subject: [PATCH 113/932] =?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 10977949d..c29c2bebf 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/dataclasses.md`. PR [#12475](https://github.com/fastapi/fastapi/pull/12475) by [@leoscarlato](https://github.com/leoscarlato). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/custom-request-and-route.md`. PR [#12483](https://github.com/fastapi/fastapi/pull/12483) by [@devfernandoa](https://github.com/devfernandoa). ## 0.115.3 From d5a045608477aaf1750ba38823c82da0722e529d Mon Sep 17 00:00:00 2001 From: ilacftemp <159066669+ilacftemp@users.noreply.github.com> Date: Tue, 22 Oct 2024 14:40:08 -0300 Subject: [PATCH 114/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/how-to/extending-openapi.md`=20(#1?= =?UTF-8?q?2470)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/how-to/extending-openapi.md | 91 ++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 docs/pt/docs/how-to/extending-openapi.md diff --git a/docs/pt/docs/how-to/extending-openapi.md b/docs/pt/docs/how-to/extending-openapi.md new file mode 100644 index 000000000..40917325b --- /dev/null +++ b/docs/pt/docs/how-to/extending-openapi.md @@ -0,0 +1,91 @@ + +# Extendendo o OpenAPI + +Existem alguns casos em que pode ser necessário modificar o esquema OpenAPI gerado. + +Nesta seção, você verá como fazer isso. + +## O processo normal + +O processo normal (padrão) é o seguinte: + +Uma aplicação (instância) do `FastAPI` possui um método `.openapi()` que deve retornar o esquema OpenAPI. + +Como parte da criação do objeto de aplicação, uma *operação de rota* para `/openapi.json` (ou para o que você definir como `openapi_url`) é registrada. + +Ela apenas retorna uma resposta JSON com o resultado do método `.openapi()` da aplicação. + +Por padrão, o que o método `.openapi()` faz é verificar se a propriedade `.openapi_schema` tem conteúdo e retorná-lo. + +Se não tiver, ele gera o conteúdo usando a função utilitária em `fastapi.openapi.utils.get_openapi`. + +E essa função `get_openapi()` recebe como parâmetros: + +* `title`: O título do OpenAPI, exibido na documentação. +* `version`: A versão da sua API, por exemplo, `2.5.0`. +* `openapi_version`: A versão da especificação OpenAPI utilizada. Por padrão, a mais recente: `3.1.0`. +* `summary`: Um resumo curto da API. +* `description`: A descrição da sua API, que pode incluir markdown e será exibida na documentação. +* `routes`: Uma lista de rotas, que são cada uma das *operações de rota* registradas. Elas são obtidas de `app.routes`. + +/// info | Informação + +O parâmetro `summary` está disponível no OpenAPI 3.1.0 e superior, suportado pelo FastAPI 0.99.0 e superior. + +/// + +## Sobrescrevendo os padrões + +Com as informações acima, você pode usar a mesma função utilitária para gerar o esquema OpenAPI e sobrescrever cada parte que precisar. + +Por exemplo, vamos adicionar Extensão OpenAPI do ReDoc para incluir um logo personalizado. + +### **FastAPI** Normal + +Primeiro, escreva toda a sua aplicação **FastAPI** normalmente: + +```Python hl_lines="1 4 7-9" +{!../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Gerar o esquema OpenAPI + +Em seguida, use a mesma função utilitária para gerar o esquema OpenAPI, dentro de uma função `custom_openapi()`: + +```Python hl_lines="2 15-21" +{!../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Modificar o esquema OpenAPI + +Agora, você pode adicionar a extensão do ReDoc, incluindo um `x-logo` personalizado ao "objeto" `info` no esquema OpenAPI: + +```Python hl_lines="22-24" +{!../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Armazenar em cache o esquema OpenAPI + +Você pode usar a propriedade `.openapi_schema` como um "cache" para armazenar o esquema gerado. + +Dessa forma, sua aplicação não precisará gerar o esquema toda vez que um usuário abrir a documentação da sua API. + +Ele será gerado apenas uma vez, e o mesmo esquema armazenado em cache será utilizado nas próximas requisições. + +```Python hl_lines="13-14 25-26" +{!../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Sobrescrever o método + +Agora, você pode substituir o método `.openapi()` pela sua nova função. + +```Python hl_lines="29" +{!../../docs_src/extending_openapi/tutorial001.py!} +``` + +### Verificar + +Uma vez que você acessar http://127.0.0.1:8000/redoc, verá que está usando seu logo personalizado (neste exemplo, o logo do **FastAPI**): + + From 180e72b1930e390e4e72b7351f916e46925637b5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 22 Oct 2024 17:41:57 +0000 Subject: [PATCH 115/932] =?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 c29c2bebf..82b78ae5f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/extending-openapi.md`. PR [#12470](https://github.com/fastapi/fastapi/pull/12470) by [@ilacftemp](https://github.com/ilacftemp). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/dataclasses.md`. PR [#12475](https://github.com/fastapi/fastapi/pull/12475) by [@leoscarlato](https://github.com/leoscarlato). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/custom-request-and-route.md`. PR [#12483](https://github.com/fastapi/fastapi/pull/12483) by [@devfernandoa](https://github.com/devfernandoa). From c1f91a0403f33e986480f09ecb46ab97e18446ce Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Tue, 22 Oct 2024 21:28:02 +0100 Subject: [PATCH 116/932] =?UTF-8?q?=F0=9F=8C=90=20Fix=20rendering=20issue?= =?UTF-8?q?=20in=20translations=20(#12509)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/mkdocs.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 8e0f6765d..6443b290a 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -266,7 +266,6 @@ markdown_extensions: # Python Markdown Extensions pymdownx.betterem: - smart_enable: all pymdownx.caret: pymdownx.highlight: line_spans: __span From 92df4e7903c9d980527f33968845ed8b330f9bc2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 22 Oct 2024 20:28:24 +0000 Subject: [PATCH 117/932] =?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 82b78ae5f..3b3454d2f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 🌐 Fix rendering issue in translations. PR [#12509](https://github.com/fastapi/fastapi/pull/12509) by [@alejsdev](https://github.com/alejsdev). + ### Translations * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/extending-openapi.md`. PR [#12470](https://github.com/fastapi/fastapi/pull/12470) by [@ilacftemp](https://github.com/ilacftemp). From 13c57834a550ce8999f28b17bc117419362472b6 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 22 Oct 2024 21:40:52 +0100 Subject: [PATCH 118/932] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#12505)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/astral-sh/ruff-pre-commit: v0.6.9 → v0.7.0](https://github.com/astral-sh/ruff-pre-commit/compare/v0.6.9...v0.7.0) Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a62acccfe..779018ff9 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.6.9 + rev: v0.7.0 hooks: - id: ruff args: From 69cc3161fc1d18e45fd9c7a9c0b2db87c14b4d34 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 22 Oct 2024 20:41:15 +0000 Subject: [PATCH 119/932] =?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 3b3454d2f..c02b6ac75 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,10 @@ hide: * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/dataclasses.md`. PR [#12475](https://github.com/fastapi/fastapi/pull/12475) by [@leoscarlato](https://github.com/leoscarlato). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/custom-request-and-route.md`. PR [#12483](https://github.com/fastapi/fastapi/pull/12483) by [@devfernandoa](https://github.com/devfernandoa). +### Internal + +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12505](https://github.com/fastapi/fastapi/pull/12505) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). + ## 0.115.3 ### Upgrades From c9337b54f0dc07a86b542f22c6fab01968dd7969 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Pedro=20Pereira=20Holanda?= Date: Tue, 22 Oct 2024 17:41:28 -0300 Subject: [PATCH 120/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/header-param-models.md`?= =?UTF-8?q?=20(#12437)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/header-param-models.md | 184 +++++++++++++++++++ 1 file changed, 184 insertions(+) create mode 100644 docs/pt/docs/tutorial/header-param-models.md diff --git a/docs/pt/docs/tutorial/header-param-models.md b/docs/pt/docs/tutorial/header-param-models.md new file mode 100644 index 000000000..a42f77a2d --- /dev/null +++ b/docs/pt/docs/tutorial/header-param-models.md @@ -0,0 +1,184 @@ +# Modelos de Parâmetros do Cabeçalho + +Se você possui um grupo de **parâmetros de cabeçalho** relacionados, você pode criar um **modelo do Pydantic** para declará-los. + +Isso vai lhe permitir **reusar o modelo** em **múltiplos lugares** e também declarar validações e metadadados para todos os parâmetros de uma vez. 😎 + +/// note | Nota + +Isso é possível desde a versão `0.115.0` do FastAPI. 🤓 + +/// + +## Parâmetros do Cabeçalho com um Modelo Pydantic + +Declare os **parâmetros de cabeçalho** que você precisa em um **modelo do Pydantic**, e então declare o parâmetro como `Header`: + +//// tab | Python 3.10+ + +```Python hl_lines="9-14 18" +{!> ../../docs_src/header_param_models/tutorial001_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9-14 18" +{!> ../../docs_src/header_param_models/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10-15 19" +{!> ../../docs_src/header_param_models/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="7-12 16" +{!> ../../docs_src/header_param_models/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="9-14 18" +{!> ../../docs_src/header_param_models/tutorial001_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="7-12 16" +{!> ../../docs_src/header_param_models/tutorial001_py310.py!} +``` + +//// + +O **FastAPI** irá **extrair** os dados de **cada campo** a partir dos **cabeçalhos** da requisição e te retornará o modelo do Pydantic que você definiu. + +### Checando a documentação + +Você pode ver os headers necessários na interface gráfica da documentação em `/docs`: + +
+ +
+ +### Proibindo Cabeçalhos adicionais + +Em alguns casos de uso especiais (provavelmente não muito comuns), você pode querer **restringir** os cabeçalhos que você quer receber. + +Você pode usar a configuração dos modelos do Pydantic para proibir (`forbid`) quaisquer campos `extra`: + +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../docs_src/header_param_models/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="10" +{!> ../../docs_src/header_param_models/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11" +{!> ../../docs_src/header_param_models/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="8" +{!> ../../docs_src/header_param_models/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="10" +{!> ../../docs_src/header_param_models/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="10" +{!> ../../docs_src/header_param_models/tutorial002.py!} +``` + +//// + +Se um cliente tentar enviar alguns **cabeçalhos extra**, eles irão receber uma resposta de **erro**. + +Por exemplo, se o cliente tentar enviar um cabeçalho `tool` com o valor `plumbus`, ele irá receber uma resposta de **erro** informando que o parâmetro do cabeçalho `tool` não é permitido: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["header", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ] +} +``` + +## Resumo + +Você pode utilizar **modelos do Pydantic** para declarar **cabeçalhos** no **FastAPI**. 😎 From fb4b6b7cbeccd9d9abbfabbb80dc63fcdfe0b379 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 22 Oct 2024 20:42:37 +0000 Subject: [PATCH 121/932] =?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 c02b6ac75..c36d08554 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/header-param-models.md`. PR [#12437](https://github.com/fastapi/fastapi/pull/12437) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/extending-openapi.md`. PR [#12470](https://github.com/fastapi/fastapi/pull/12470) by [@ilacftemp](https://github.com/ilacftemp). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/dataclasses.md`. PR [#12475](https://github.com/fastapi/fastapi/pull/12475) by [@leoscarlato](https://github.com/leoscarlato). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/custom-request-and-route.md`. PR [#12483](https://github.com/fastapi/fastapi/pull/12483) by [@devfernandoa](https://github.com/devfernandoa). From 136c48bda6151a468346f87c5534f6d6e0e28a0f Mon Sep 17 00:00:00 2001 From: YungYueh ChanLee Date: Wed, 23 Oct 2024 04:44:51 +0800 Subject: [PATCH 122/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Traditional=20Chin?= =?UTF-8?q?ese=20translation=20for=20`docs/zh-hant/docs/tutorial/index.md`?= =?UTF-8?q?=20(#12466)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/tutorial/index.md | 102 ++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 docs/zh-hant/docs/tutorial/index.md diff --git a/docs/zh-hant/docs/tutorial/index.md b/docs/zh-hant/docs/tutorial/index.md new file mode 100644 index 000000000..34f504851 --- /dev/null +++ b/docs/zh-hant/docs/tutorial/index.md @@ -0,0 +1,102 @@ +# 教學 - 使用者指南 + +本教學將一步一步展示如何使用 **FastAPI** 及其大多數功能。 + +每個部分都是在前一部分的基礎上逐步建置的,但內容結構是按主題分開的,因此你可以直接跳到任何特定的部分,解決你具體的 API 需求。 + +它也被設計成可作為未來的參考,讓你隨時回來查看所需的內容。 + +## 運行程式碼 + +所有程式碼區塊都可以直接複製和使用(它們實際上是經過測試的 Python 檔案)。 + +要運行任何範例,請將程式碼複製到 `main.py` 檔案,並使用以下命令啟動 `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 + +第一步是安裝 FastAPI。 + +確保你建立一個[虛擬環境](../virtual-environments.md){.internal-link target=_blank},啟用它,然後 **安裝 FastAPI**: + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +/// note + +當你使用 `pip install "fastapi[standard]"` 安裝時,會包含一些預設的可選標準相依項。 + +如果你不想包含那些可選的相依項,你可以使用 `pip install fastapi` 來安裝。 + +/// + +## 進階使用者指南 + +還有一個 **進階使用者指南** 你可以稍後閱讀。 + +**進階使用者指南** 建立在這個教學之上,使用相同的概念,並教你一些額外的功能。 + +但首先你應該閱讀 **教學 - 使用者指南**(你正在閱讀的內容)。 + +它被設計成你可以使用 **教學 - 使用者指南** 來建立一個完整的應用程式,然後根據你的需求,使用一些額外的想法來擴展它。 From 59efc69becd330fc92b103be2ac21a94b6450043 Mon Sep 17 00:00:00 2001 From: YungYueh ChanLee Date: Wed, 23 Oct 2024 04:45:13 +0800 Subject: [PATCH 123/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Traditional=20Chin?= =?UTF-8?q?ese=20translation=20for=20`docs/zh-hant/docs/how-to/index.md`?= =?UTF-8?q?=20(#12468)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/how-to/index.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 docs/zh-hant/docs/how-to/index.md diff --git a/docs/zh-hant/docs/how-to/index.md b/docs/zh-hant/docs/how-to/index.md new file mode 100644 index 000000000..d668b5b7a --- /dev/null +++ b/docs/zh-hant/docs/how-to/index.md @@ -0,0 +1,13 @@ +# 使用指南 - 範例集 + +在這裡,你將會看到 **不同主題** 的範例或「如何使用」的指南。 + +大多數這些想法都是 **獨立** 的,在大多數情況下,你只需要研究那些直接適用於 **你的專案** 的東西。 + +如果有些東西看起來很有趣且對你的專案很有用的話再去讀它,否則你可能可以跳過它們。 + +/// tip + +如果你想要以結構化的方式 **學習 FastAPI**(推薦),請前往[教學 - 使用者指南](../tutorial/index.md){.internal-link target=_blank}逐章閱讀。 + +/// From 21fc89976d54d828d4201ec3370eadf2218dc695 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 22 Oct 2024 20:47:24 +0000 Subject: [PATCH 124/932] =?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 c36d08554..f488bf7b4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/tutorial/index.md`. PR [#12466](https://github.com/fastapi/fastapi/pull/12466) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/header-param-models.md`. PR [#12437](https://github.com/fastapi/fastapi/pull/12437) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/extending-openapi.md`. PR [#12470](https://github.com/fastapi/fastapi/pull/12470) by [@ilacftemp](https://github.com/ilacftemp). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/dataclasses.md`. PR [#12475](https://github.com/fastapi/fastapi/pull/12475) by [@leoscarlato](https://github.com/leoscarlato). From 2d43a8a2a3389934890bb60f0e4979074745cbdc Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 22 Oct 2024 20:48:21 +0000 Subject: [PATCH 125/932] =?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 f488bf7b4..daaaa9c99 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/how-to/index.md`. PR [#12468](https://github.com/fastapi/fastapi/pull/12468) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/tutorial/index.md`. PR [#12466](https://github.com/fastapi/fastapi/pull/12466) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/header-param-models.md`. PR [#12437](https://github.com/fastapi/fastapi/pull/12437) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Portuguese translation for `docs/pt/docs/how-to/extending-openapi.md`. PR [#12470](https://github.com/fastapi/fastapi/pull/12470) by [@ilacftemp](https://github.com/ilacftemp). From 8081d2302ec5cffd5d2a35a6e22980d3f03bb395 Mon Sep 17 00:00:00 2001 From: Kevin Kirsche Date: Wed, 23 Oct 2024 14:30:18 -0400 Subject: [PATCH 126/932] =?UTF-8?q?=F0=9F=93=9D=20Fix=20minor=20typos=20(#?= =?UTF-8?q?12516)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/param_functions.py | 2 +- fastapi/security/oauth2.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/fastapi/param_functions.py b/fastapi/param_functions.py index 7ddaace25..b3621626c 100644 --- a/fastapi/param_functions.py +++ b/fastapi/param_functions.py @@ -2298,7 +2298,7 @@ def Security( # noqa: N802 dependency. The term "scope" comes from the OAuth2 specification, it seems to be - intentionaly vague and interpretable. It normally refers to permissions, + intentionally vague and interpretable. It normally refers to permissions, in cases to roles. These scopes are integrated with OpenAPI (and the API docs at `/docs`). diff --git a/fastapi/security/oauth2.py b/fastapi/security/oauth2.py index 9720cace0..6adc55bfe 100644 --- a/fastapi/security/oauth2.py +++ b/fastapi/security/oauth2.py @@ -52,7 +52,7 @@ class OAuth2PasswordRequestForm: ``` Note that for OAuth2 the scope `items:read` is a single scope in an opaque string. - You could have custom internal logic to separate it by colon caracters (`:`) or + You could have custom internal logic to separate it by colon characters (`:`) or similar, and get the two parts `items` and `read`. Many applications do that to group and organize permissions, you could do it as well in your application, just know that that it is application specific, it's not part of the specification. @@ -194,7 +194,7 @@ class OAuth2PasswordRequestFormStrict(OAuth2PasswordRequestForm): ``` Note that for OAuth2 the scope `items:read` is a single scope in an opaque string. - You could have custom internal logic to separate it by colon caracters (`:`) or + You could have custom internal logic to separate it by colon characters (`:`) or similar, and get the two parts `items` and `read`. Many applications do that to group and organize permissions, you could do it as well in your application, just know that that it is application specific, it's not part of the specification. From 593385d1c3bac8173905c28e07ffda9fd5ac4ea6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 23 Oct 2024 18:30:47 +0000 Subject: [PATCH 127/932] =?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 daaaa9c99..93a5a8f56 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Fix minor typos. PR [#12516](https://github.com/fastapi/fastapi/pull/12516) by [@kkirsche](https://github.com/kkirsche). * 🌐 Fix rendering issue in translations. PR [#12509](https://github.com/fastapi/fastapi/pull/12509) by [@alejsdev](https://github.com/alejsdev). ### Translations From e7533b92b3ad2a9f50a19342fde0967aa4601fd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 24 Oct 2024 14:38:34 +0200 Subject: [PATCH 128/932] =?UTF-8?q?=F0=9F=91=B7=20Update=20GitHub=20Action?= =?UTF-8?q?=20to=20deploy=20docs=20previews=20to=20handle=20missing=20depl?= =?UTF-8?q?oy=20comments=20(#12527)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy-docs.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 2fd46df6b..39ea7de52 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -62,7 +62,10 @@ jobs: env: PROJECT_NAME: fastapitiangolo BRANCH: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} - uses: cloudflare/wrangler-action@v3 + # TODO: Use v3 when it's fixed, probably in v3.11 + # https://github.com/cloudflare/wrangler-action/issues/307 + uses: cloudflare/wrangler-action@v3.9 + # uses: cloudflare/wrangler-action@v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} From 6ede04f876acc00e2cf688d39e8d6c79dcac0230 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 24 Oct 2024 12:39:00 +0000 Subject: [PATCH 129/932] =?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 93a5a8f56..243ac4006 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 👷 Update GitHub Action to deploy docs previews to handle missing deploy comments. PR [#12527](https://github.com/fastapi/fastapi/pull/12527) by [@tiangolo](https://github.com/tiangolo). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12505](https://github.com/fastapi/fastapi/pull/12505) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). ## 0.115.3 From 2f2c877d51e827ed1a468ed16bdbe79469b15261 Mon Sep 17 00:00:00 2001 From: YungYueh ChanLee Date: Fri, 25 Oct 2024 02:28:00 +0800 Subject: [PATCH 130/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Traditional=20C?= =?UTF-8?q?hinese=20translation=20for=20`docs/zh-hant/docs/tutorial/index.?= =?UTF-8?q?md`=20(#12524)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/tutorial/index.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/zh-hant/docs/tutorial/index.md b/docs/zh-hant/docs/tutorial/index.md index 34f504851..2aaa78b22 100644 --- a/docs/zh-hant/docs/tutorial/index.md +++ b/docs/zh-hant/docs/tutorial/index.md @@ -61,7 +61,7 @@ $ fastapi dev fastapi dev @@ -93,10 +93,10 @@ $ pip install "fastapi[standard]" ## 進階使用者指南 -還有一個 **進階使用者指南** 你可以稍後閱讀。 +還有一個**進階使用者指南**你可以稍後閱讀。 -**進階使用者指南** 建立在這個教學之上,使用相同的概念,並教你一些額外的功能。 +**進階使用者指南**建立在這個教學之上,使用相同的概念,並教你一些額外的功能。 -但首先你應該閱讀 **教學 - 使用者指南**(你正在閱讀的內容)。 +但首先你應該閱讀**教學 - 使用者指南**(你正在閱讀的內容)。 -它被設計成你可以使用 **教學 - 使用者指南** 來建立一個完整的應用程式,然後根據你的需求,使用一些額外的想法來擴展它。 +它被設計成你可以使用**教學 - 使用者指南**來建立一個完整的應用程式,然後根據你的需求,使用一些額外的想法來擴展它。 From 7b03fa7e0c489204fa268d0f9c2c1f17dbb73645 Mon Sep 17 00:00:00 2001 From: YungYueh ChanLee Date: Fri, 25 Oct 2024 02:28:16 +0800 Subject: [PATCH 131/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Traditional=20C?= =?UTF-8?q?hinese=20translation=20for=20`docs/zh-hant/docs/how-to/index.md?= =?UTF-8?q?`=20(#12523)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/how-to/index.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/zh-hant/docs/how-to/index.md b/docs/zh-hant/docs/how-to/index.md index d668b5b7a..db740140d 100644 --- a/docs/zh-hant/docs/how-to/index.md +++ b/docs/zh-hant/docs/how-to/index.md @@ -1,13 +1,13 @@ # 使用指南 - 範例集 -在這裡,你將會看到 **不同主題** 的範例或「如何使用」的指南。 +在這裡,你將會看到**不同主題**的範例或「如何使用」的指南。 -大多數這些想法都是 **獨立** 的,在大多數情況下,你只需要研究那些直接適用於 **你的專案** 的東西。 +大多數這些想法都是**獨立**的,在大多數情況下,你只需要研究那些直接適用於**你的專案**的東西。 如果有些東西看起來很有趣且對你的專案很有用的話再去讀它,否則你可能可以跳過它們。 /// tip -如果你想要以結構化的方式 **學習 FastAPI**(推薦),請前往[教學 - 使用者指南](../tutorial/index.md){.internal-link target=_blank}逐章閱讀。 +如果你想要以結構化的方式**學習 FastAPI**(推薦),請前往[教學 - 使用者指南](../tutorial/index.md){.internal-link target=_blank}逐章閱讀。 /// From b144221ad538899fedb15c56f052d94febe96d21 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 24 Oct 2024 18:28:22 +0000 Subject: [PATCH 132/932] =?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 243ac4006..616e92308 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Translations +* 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/tutorial/index.md`. PR [#12524](https://github.com/fastapi/fastapi/pull/12524) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/how-to/index.md`. PR [#12468](https://github.com/fastapi/fastapi/pull/12468) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/tutorial/index.md`. PR [#12466](https://github.com/fastapi/fastapi/pull/12466) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/header-param-models.md`. PR [#12437](https://github.com/fastapi/fastapi/pull/12437) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). From ff5f076011d752e91861e4e48c32560cc5386ba1 Mon Sep 17 00:00:00 2001 From: YungYueh ChanLee Date: Fri, 25 Oct 2024 02:28:55 +0800 Subject: [PATCH 133/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Traditional=20C?= =?UTF-8?q?hinese=20translation=20for=20`docs/zh-hant/docs/deployment/clou?= =?UTF-8?q?d.md`=20(#12522)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/deployment/cloud.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/zh-hant/docs/deployment/cloud.md b/docs/zh-hant/docs/deployment/cloud.md index 5d645b6c2..29ebe3ff5 100644 --- a/docs/zh-hant/docs/deployment/cloud.md +++ b/docs/zh-hant/docs/deployment/cloud.md @@ -1,14 +1,14 @@ # 在雲端部署 FastAPI -你幾乎可以使用 **任何雲端供應商** 來部署你的 FastAPI 應用程式。 +你幾乎可以使用**任何雲端供應商**來部署你的 FastAPI 應用程式。 在大多數情況下,主要的雲端供應商都有部署 FastAPI 的指南。 ## 雲端供應商 - 贊助商 -一些雲端供應商 ✨ [**贊助 FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨,這確保了 FastAPI 及其 **生態系統** 持續健康地 **發展**。 +一些雲端供應商 ✨ [**贊助 FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨,這確保了 FastAPI 及其**生態系統**持續健康地**發展**。 -這也展現了他們對 FastAPI 和其 **社群**(包括你)的真正承諾,他們不僅希望為你提供 **優質的服務**,還希望確保你擁有一個 **良好且健康的框架**:FastAPI。🙇 +這也展現了他們對 FastAPI 和其**社群**(包括你)的真正承諾,他們不僅希望為你提供**優質的服務**,還希望確保你擁有一個**良好且健康的框架**:FastAPI。🙇 你可能會想嘗試他們的服務,以下有他們的指南: From b5021a4c84c59f0b0e2354e0116fc6f65055804b Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 24 Oct 2024 18:29:27 +0000 Subject: [PATCH 134/932] =?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 616e92308..20841620b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Translations +* 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/how-to/index.md`. PR [#12523](https://github.com/fastapi/fastapi/pull/12523) by [@codingjenny](https://github.com/codingjenny). * 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/tutorial/index.md`. PR [#12524](https://github.com/fastapi/fastapi/pull/12524) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/how-to/index.md`. PR [#12468](https://github.com/fastapi/fastapi/pull/12468) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/tutorial/index.md`. PR [#12466](https://github.com/fastapi/fastapi/pull/12466) by [@codingjenny](https://github.com/codingjenny). From 86fe2515072fece41cbab7f50ffcd6d445b6d358 Mon Sep 17 00:00:00 2001 From: YungYueh ChanLee Date: Fri, 25 Oct 2024 02:30:54 +0800 Subject: [PATCH 135/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Traditional=20C?= =?UTF-8?q?hinese=20translation=20for=20`docs/zh-hant/docs/deployment/inde?= =?UTF-8?q?x.md`=20(#12521)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/deployment/index.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/zh-hant/docs/deployment/index.md b/docs/zh-hant/docs/deployment/index.md index e760b3d16..1726562b4 100644 --- a/docs/zh-hant/docs/deployment/index.md +++ b/docs/zh-hant/docs/deployment/index.md @@ -4,17 +4,17 @@ ## 部署是什麼意思 -**部署** 應用程式指的是執行一系列必要的步驟,使其能夠 **讓使用者存取和使用**。 +**部署**應用程式指的是執行一系列必要的步驟,使其能夠**讓使用者存取和使用**。 -對於一個 **Web API**,部署通常涉及將其放置在 **遠端伺服器** 上,並使用性能優良且穩定的 **伺服器程式**,確保使用者能夠高效、無中斷地存取應用程式,且不會遇到問題。 +對於一個 **Web API**,部署通常涉及將其放置在**遠端伺服器**上,並使用性能優良且穩定的**伺服器程式**,確保使用者能夠高效、無中斷地存取應用程式,且不會遇到問題。 -這與 **開發** 階段形成鮮明對比,在 **開發** 階段,你會不斷更改程式碼、破壞程式碼、修復程式碼,然後停止和重新啟動伺服器等。 +這與**開發**階段形成鮮明對比,在**開發**階段,你會不斷更改程式碼、破壞程式碼、修復程式碼,然後停止和重新啟動伺服器等。 ## 部署策略 根據你的使用場景和使用工具,有多種方法可以實現此目的。 -你可以使用一些工具自行 **部署伺服器**,你也可以使用能為你完成部分工作的 **雲端服務**,或其他可能的選項。 +你可以使用一些工具自行**部署伺服器**,你也可以使用能為你完成部分工作的**雲端服務**,或其他可能的選項。 我將向你展示在部署 **FastAPI** 應用程式時你可能應該記住的一些主要概念(儘管其中大部分適用於任何其他類型的 Web 應用程式)。 From e2d77a9e425bcba3ef2a8189b62196351bd3677f Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 24 Oct 2024 18:32:39 +0000 Subject: [PATCH 136/932] =?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 20841620b..039d94c76 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Translations +* 🌐 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). * 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/how-to/index.md`. PR [#12523](https://github.com/fastapi/fastapi/pull/12523) by [@codingjenny](https://github.com/codingjenny). * 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/tutorial/index.md`. PR [#12524](https://github.com/fastapi/fastapi/pull/12524) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/how-to/index.md`. PR [#12468](https://github.com/fastapi/fastapi/pull/12468) by [@codingjenny](https://github.com/codingjenny). From cf65c423d1e59077bf39533788486c0da7339d07 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 24 Oct 2024 18:35:26 +0000 Subject: [PATCH 137/932] =?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 039d94c76..fd5bb0eb9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Translations +* 🌐 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). * 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/how-to/index.md`. PR [#12523](https://github.com/fastapi/fastapi/pull/12523) by [@codingjenny](https://github.com/codingjenny). * 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/tutorial/index.md`. PR [#12524](https://github.com/fastapi/fastapi/pull/12524) by [@codingjenny](https://github.com/codingjenny). From ec9b066e0bb3577eca3f2f02c5043a398ca28746 Mon Sep 17 00:00:00 2001 From: Renne Rocha Date: Thu, 24 Oct 2024 15:39:34 -0300 Subject: [PATCH 138/932] =?UTF-8?q?=F0=9F=93=9D=20Add=20External=20Link:?= =?UTF-8?q?=20FastAPI=20do=20Zero=20(#12533)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/external_links.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index dedbe87f4..9e411a631 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -339,6 +339,10 @@ Articles: link: https://qiita.com/mtitg/items/47770e9a562dd150631d title: FastAPI|DB接続してCRUDするPython製APIサーバーを構築 Portuguese: + - author: Eduardo Mendes + author_link: https://bolha.us/@dunossauro + link: https://fastapidozero.dunossauro.com/ + title: FastAPI do ZERO - author: Jessica Temporal author_link: https://jtemporal.com/socials link: https://jtemporal.com/dicas-para-migrar-de-flask-para-fastapi-e-vice-versa/ From 548f938280598ceed36decb361e2188b5a5f806b Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 24 Oct 2024 18:43:50 +0000 Subject: [PATCH 139/932] =?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 fd5bb0eb9..1c3cbf011 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add External Link: FastAPI do Zero. PR [#12533](https://github.com/fastapi/fastapi/pull/12533) by [@rennerocha](https://github.com/rennerocha). * 📝 Fix minor typos. PR [#12516](https://github.com/fastapi/fastapi/pull/12516) by [@kkirsche](https://github.com/kkirsche). * 🌐 Fix rendering issue in translations. PR [#12509](https://github.com/fastapi/fastapi/pull/12509) by [@alejsdev](https://github.com/alejsdev). From 55bcab6d75b2b1f1780f56f989fbfba1498b96d0 Mon Sep 17 00:00:00 2001 From: ilacftemp <159066669+ilacftemp@users.noreply.github.com> Date: Thu, 24 Oct 2024 15:52:36 -0300 Subject: [PATCH 140/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/how-to/separate-openapi-schemas.md?= =?UTF-8?q?`=20(#12518)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/how-to/separate-openapi-schemas.md | 258 ++++++++++++++++++ 1 file changed, 258 insertions(+) create mode 100644 docs/pt/docs/how-to/separate-openapi-schemas.md diff --git a/docs/pt/docs/how-to/separate-openapi-schemas.md b/docs/pt/docs/how-to/separate-openapi-schemas.md new file mode 100644 index 000000000..50d321d4c --- /dev/null +++ b/docs/pt/docs/how-to/separate-openapi-schemas.md @@ -0,0 +1,258 @@ +# Esquemas OpenAPI Separados para Entrada e Saída ou Não + +Ao usar **Pydantic v2**, o OpenAPI gerado é um pouco mais exato e **correto** do que antes. 😎 + +Inclusive, em alguns casos, ele terá até **dois JSON Schemas** no OpenAPI para o mesmo modelo Pydantic, para entrada e saída, dependendo se eles possuem **valores padrão**. + +Vamos ver como isso funciona e como alterar se for necessário. + +## Modelos Pydantic para Entrada e Saída + +Digamos que você tenha um modelo Pydantic com valores padrão, como este: + +//// tab | Python 3.10+ + +```Python hl_lines="7" +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} + +# Code below omitted 👇 +``` + +
+👀 Visualização completa do arquivo + +```Python +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` + +
+ +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} + +# Code below omitted 👇 +``` + +
+👀 Visualização completa do arquivo + +```Python +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` + +
+ +//// + +//// tab | Python 3.8+ + +```Python hl_lines="9" +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} + +# Code below omitted 👇 +``` + +
+👀 Visualização completa do arquivo + +```Python +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +
+ +//// + +### Modelo para Entrada + +Se você usar esse modelo como entrada, como aqui: + +//// tab | Python 3.10+ + +```Python hl_lines="14" +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} + +# Code below omitted 👇 +``` + +
+👀 Visualização completa do arquivo + +```Python +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` + +
+ +//// + +//// tab | Python 3.9+ + +```Python hl_lines="16" +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} + +# Code below omitted 👇 +``` + +
+👀 Visualização completa do arquivo + +```Python +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` + +
+ +//// + +//// tab | Python 3.8+ + +```Python hl_lines="16" +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} + +# Code below omitted 👇 +``` + +
+👀 Visualização completa do arquivo + +```Python +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +
+ +//// + +... então o campo `description` não será obrigatório. Porque ele tem um valor padrão de `None`. + +### Modelo de Entrada na Documentação + +Você pode confirmar que na documentação, o campo `description` não tem um **asterisco vermelho**, não é marcado como obrigatório: + +
+ +
+ +### Modelo para Saída + +Mas se você usar o mesmo modelo como saída, como aqui: + +//// tab | Python 3.10+ + +```Python hl_lines="19" +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="21" +{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="21" +{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} +``` + +//// + +... então, como `description` tem um valor padrão, se você **não retornar nada** para esse campo, ele ainda terá o **valor padrão**. + +### Modelo para Dados de Resposta de Saída + +Se você interagir com a documentação e verificar a resposta, mesmo que o código não tenha adicionado nada em um dos campos `description`, a resposta JSON contém o valor padrão (`null`): + +
+ +
+ +Isso significa que ele **sempre terá um valor**, só que às vezes o valor pode ser `None` (ou `null` em termos de JSON). + +Isso quer dizer que, os clientes que usam sua API não precisam verificar se o valor existe ou não, eles podem **assumir que o campo sempre estará lá**, mas que em alguns casos terá o valor padrão de `None`. + +A maneira de descrever isso no OpenAPI é marcar esse campo como **obrigatório**, porque ele sempre estará lá. + +Por causa disso, o JSON Schema para um modelo pode ser diferente dependendo se ele é usado para **entrada ou saída**: + +* para **entrada**, o `description` **não será obrigatório** +* para **saída**, ele será **obrigatório** (e possivelmente `None`, ou em termos de JSON, `null`) + +### Modelo para Saída na Documentação + +Você pode verificar o modelo de saída na documentação também, ambos `name` e `description` são marcados como **obrigatórios** com um **asterisco vermelho**: + +
+ +
+ +### Modelo para Entrada e Saída na Documentação + +E se você verificar todos os Schemas disponíveis (JSON Schemas) no OpenAPI, verá que há dois, um `Item-Input` e um `Item-Output`. + +Para `Item-Input`, `description` **não é obrigatório**, não tem um asterisco vermelho. + +Mas para `Item-Output`, `description` **é obrigatório**, tem um asterisco vermelho. + +
+ +
+ +Com esse recurso do **Pydantic v2**, sua documentação da API fica mais **precisa**, e se você tiver clientes e SDKs gerados automaticamente, eles serão mais precisos também, proporcionando uma melhor **experiência para desenvolvedores** e consistência. 🎉 + +## Não Separe Schemas + +Agora, há alguns casos em que você pode querer ter o **mesmo esquema para entrada e saída**. + +Provavelmente, o principal caso de uso para isso é se você já tem algum código de cliente/SDK gerado automaticamente e não quer atualizar todo o código de cliente/SDK gerado ainda, você provavelmente vai querer fazer isso em algum momento, mas talvez não agora. + +Nesse caso, você pode desativar esse recurso no **FastAPI**, com o parâmetro `separate_input_output_schemas=False`. + +/// info | Informação + +O suporte para `separate_input_output_schemas` foi adicionado no FastAPI `0.102.0`. 🤓 + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="10" +{!> ../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="12" +{!> ../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="12" +{!> ../../docs_src/separate_openapi_schemas/tutorial002.py!} +``` + +//// + +### Mesmo Esquema para Modelos de Entrada e Saída na Documentação + +E agora haverá um único esquema para entrada e saída para o modelo, apenas `Item`, e `description` **não será obrigatório**: + +
+ +
+ +Esse é o mesmo comportamento do Pydantic v1. 🤓 From a498582bb46811203b0a172759667c646bc0059c Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 24 Oct 2024 18:54:28 +0000 Subject: [PATCH 141/932] =?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 1c3cbf011..1720110ec 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/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). * 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/how-to/index.md`. PR [#12523](https://github.com/fastapi/fastapi/pull/12523) by [@codingjenny](https://github.com/codingjenny). From fd95b4ae6522909baf64364f8fdadf985db130fc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 26 Oct 2024 10:37:59 +0100 Subject: [PATCH 142/932] =?UTF-8?q?=E2=AC=86=20Bump=20cloudflare/wrangler-?= =?UTF-8?q?action=20from=203.9=20to=203.11=20(#12544)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [cloudflare/wrangler-action](https://github.com/cloudflare/wrangler-action) from 3.9 to 3.11. - [Release notes](https://github.com/cloudflare/wrangler-action/releases) - [Changelog](https://github.com/cloudflare/wrangler-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/cloudflare/wrangler-action/compare/v3.9...v3.11) --- updated-dependencies: - dependency-name: cloudflare/wrangler-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/deploy-docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 39ea7de52..e46786a53 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -64,7 +64,7 @@ jobs: BRANCH: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} # TODO: Use v3 when it's fixed, probably in v3.11 # https://github.com/cloudflare/wrangler-action/issues/307 - uses: cloudflare/wrangler-action@v3.9 + uses: cloudflare/wrangler-action@v3.11 # uses: cloudflare/wrangler-action@v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} From d60c52bc32b655e23809fa488864098cb3809ce4 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 26 Oct 2024 09:38:20 +0000 Subject: [PATCH 143/932] =?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 1720110ec..064d94d98 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -29,6 +29,7 @@ hide: ### Internal +* ⬆ Bump cloudflare/wrangler-action from 3.9 to 3.11. PR [#12544](https://github.com/fastapi/fastapi/pull/12544) by [@dependabot[bot]](https://github.com/apps/dependabot). * 👷 Update GitHub Action to deploy docs previews to handle missing deploy comments. PR [#12527](https://github.com/fastapi/fastapi/pull/12527) by [@tiangolo](https://github.com/tiangolo). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12505](https://github.com/fastapi/fastapi/pull/12505) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). From 89f06da526974646a6232115e15c7a05813f932f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 26 Oct 2024 13:45:10 +0200 Subject: [PATCH 144/932] =?UTF-8?q?=F0=9F=93=9D=20Fix=20link=20in=20OAuth2?= =?UTF-8?q?=20docs=20(#12550)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/security/oauth2-jwt.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index f454a8b28..6ae1507dc 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -72,7 +72,7 @@ It supports many secure hashing algorithms and utilities to work with them. The recommended algorithm is "Bcrypt". -Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install PassLib with Bcrypt: +Make sure you create a [virtual environment](../../virtual-environments.md){.internal-link target=_blank}, activate it, and then install PassLib with Bcrypt:
From ea88ab6cf1796bf0542c3f4f6227c8f6aa3cd776 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 26 Oct 2024 11:46:28 +0000 Subject: [PATCH 145/932] =?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 064d94d98..770e1a97e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Fix link in OAuth2 docs. PR [#12550](https://github.com/fastapi/fastapi/pull/12550) by [@tiangolo](https://github.com/tiangolo). * 📝 Add External Link: FastAPI do Zero. PR [#12533](https://github.com/fastapi/fastapi/pull/12533) by [@rennerocha](https://github.com/rennerocha). * 📝 Fix minor typos. PR [#12516](https://github.com/fastapi/fastapi/pull/12516) by [@kkirsche](https://github.com/kkirsche). * 🌐 Fix rendering issue in translations. PR [#12509](https://github.com/fastapi/fastapi/pull/12509) by [@alejsdev](https://github.com/alejsdev). From 71fcafd13c29fab216a432d4fdfd77555b14483e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 26 Oct 2024 13:47:53 +0200 Subject: [PATCH 146/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/python-types.md`=20(#12551)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/python-types.md | 40 +++++++++--------------------------- 1 file changed, 10 insertions(+), 30 deletions(-) diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md index ee192d8cb..6c28577cc 100644 --- a/docs/en/docs/python-types.md +++ b/docs/en/docs/python-types.md @@ -22,9 +22,7 @@ If you are a Python expert, and you already know everything about type hints, sk Let's start with a simple example: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} Calling this program outputs: @@ -38,9 +36,7 @@ The function does the following: * Converts the first letter of each one to upper case with `title()`. * Concatenates them with a space in the middle. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} ### Edit it @@ -82,9 +78,7 @@ That's it. Those are the "type hints": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} That is not the same as declaring default values like would be with: @@ -112,9 +106,7 @@ With that, you can scroll, seeing the options, until you find the one that "ring Check this function, it already has type hints: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} Because the editor knows the types of the variables, you don't only get completion, you also get error checks: @@ -122,9 +114,7 @@ Because the editor knows the types of the variables, you don't only get completi Now you know that you have to fix it, convert `age` to a string with `str(age)`: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} ## Declaring types @@ -143,9 +133,7 @@ You can use, for example: * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} ### Generic types with type parameters @@ -369,9 +357,7 @@ It's just about the words and names. But those words can affect how you and your As an example, let's take this function: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c.py!} -``` +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} The parameter `name` is defined as `Optional[str]`, but it is **not optional**, you cannot call the function without the parameter: @@ -387,9 +373,7 @@ say_hi(name=None) # This works, None is valid 🎉 The good news is, once you are on Python 3.10 you won't have to worry about that, as you will be able to simply use `|` to define unions of types: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c_py310.py!} -``` +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} And then you won't have to worry about names like `Optional` and `Union`. 😎 @@ -451,15 +435,11 @@ You can also declare a class as the type of a variable. Let's say you have a class `Person`, with a name: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} Then you can declare a variable to be of type `Person`: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} And then, again, you get all the editor support: From 56bc9a5eb4e150656518fdad689988539c339a74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 26 Oct 2024 13:48:16 +0200 Subject: [PATCH 147/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/tutorial/first-steps.md`=20(#12552)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/first-steps.md | 28 +++++++--------------------- 1 file changed, 7 insertions(+), 21 deletions(-) diff --git a/docs/en/docs/tutorial/first-steps.md b/docs/en/docs/tutorial/first-steps.md index 77728cebe..1c20b945a 100644 --- a/docs/en/docs/tutorial/first-steps.md +++ b/docs/en/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ The simplest FastAPI file could look like this: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Copy that to a file `main.py`. @@ -157,9 +155,7 @@ You could also use it to generate code automatically, for clients that communica ### Step 1: import `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` is a Python class that provides all the functionality for your API. @@ -173,9 +169,7 @@ You can use all the Date: Sat, 26 Oct 2024 11:49:36 +0000 Subject: [PATCH 148/932] =?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 770e1a97e..9e47695bd 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/python-types.md`. PR [#12551](https://github.com/fastapi/fastapi/pull/12551) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix link in OAuth2 docs. PR [#12550](https://github.com/fastapi/fastapi/pull/12550) by [@tiangolo](https://github.com/tiangolo). * 📝 Add External Link: FastAPI do Zero. PR [#12533](https://github.com/fastapi/fastapi/pull/12533) by [@rennerocha](https://github.com/rennerocha). * 📝 Fix minor typos. PR [#12516](https://github.com/fastapi/fastapi/pull/12516) by [@kkirsche](https://github.com/kkirsche). From 63c3eacf43fc39127d86d69baf5a8caa5f9507f9 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 26 Oct 2024 11:51:54 +0000 Subject: [PATCH 149/932] =?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 9e47695bd..98c6bcb82 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/first-steps.md`. PR [#12552](https://github.com/fastapi/fastapi/pull/12552) by [@tiangolo](https://github.com/tiangolo). * 📝 Update includes in `docs/en/docs/python-types.md`. PR [#12551](https://github.com/fastapi/fastapi/pull/12551) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix link in OAuth2 docs. PR [#12550](https://github.com/fastapi/fastapi/pull/12550) by [@tiangolo](https://github.com/tiangolo). * 📝 Add External Link: FastAPI do Zero. PR [#12533](https://github.com/fastapi/fastapi/pull/12533) by [@rennerocha](https://github.com/rennerocha). From 68d0a0412ec7c4ec7e3fe1840fd32d05fcebb338 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 26 Oct 2024 18:01:27 +0200 Subject: [PATCH 150/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/advanced/security/http-basic-auth.md`=20(#1255?= =?UTF-8?q?3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/advanced/security/http-basic-auth.md | 90 +------------------ 1 file changed, 3 insertions(+), 87 deletions(-) diff --git a/docs/en/docs/advanced/security/http-basic-auth.md b/docs/en/docs/advanced/security/http-basic-auth.md index fa652c52b..234e2f940 100644 --- a/docs/en/docs/advanced/security/http-basic-auth.md +++ b/docs/en/docs/advanced/security/http-basic-auth.md @@ -20,35 +20,7 @@ Then, when you type that username and password, the browser sends them in the he * It returns an object of type `HTTPBasicCredentials`: * It contains the `username` and `password` sent. -//// tab | Python 3.9+ - -```Python hl_lines="4 8 12" -{!> ../../docs_src/security/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="2 7 11" -{!> ../../docs_src/security/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="2 6 10" -{!> ../../docs_src/security/tutorial006.py!} -``` - -//// +{* ../../docs_src/security/tutorial006_an_py39.py hl[4,8,12] *} When you try to open the URL for the first time (or click the "Execute" button in the docs) the browser will ask you for your username and password: @@ -68,35 +40,7 @@ To handle that, we first convert the `username` and `password` to `bytes` encodi Then we can use `secrets.compare_digest()` to ensure that `credentials.username` is `"stanleyjobson"`, and that `credentials.password` is `"swordfish"`. -//// tab | Python 3.9+ - -```Python hl_lines="1 12-24" -{!> ../../docs_src/security/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 12-24" -{!> ../../docs_src/security/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 11-21" -{!> ../../docs_src/security/tutorial007.py!} -``` - -//// +{* ../../docs_src/security/tutorial007_an_py39.py hl[1,12:24] *} This would be similar to: @@ -160,32 +104,4 @@ That way, using `secrets.compare_digest()` in your application code, it will be After detecting that the credentials are incorrect, return an `HTTPException` with a status code 401 (the same returned when no credentials are provided) and add the header `WWW-Authenticate` to make the browser show the login prompt again: -//// tab | Python 3.9+ - -```Python hl_lines="26-30" -{!> ../../docs_src/security/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="26-30" -{!> ../../docs_src/security/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="23-27" -{!> ../../docs_src/security/tutorial007.py!} -``` - -//// +{* ../../docs_src/security/tutorial007_an_py39.py hl[26:30] *} From 6e85909311bfa43c7251bc6f2304333b3be36994 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 26 Oct 2024 16:01:48 +0000 Subject: [PATCH 151/932] =?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 98c6bcb82..4146331ee 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/advanced/security/http-basic-auth.md`. PR [#12553](https://github.com/fastapi/fastapi/pull/12553) by [@tiangolo](https://github.com/tiangolo). * 📝 Update includes in `docs/en/docs/tutorial/first-steps.md`. PR [#12552](https://github.com/fastapi/fastapi/pull/12552) by [@tiangolo](https://github.com/tiangolo). * 📝 Update includes in `docs/en/docs/python-types.md`. PR [#12551](https://github.com/fastapi/fastapi/pull/12551) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix link in OAuth2 docs. PR [#12550](https://github.com/fastapi/fastapi/pull/12550) by [@tiangolo](https://github.com/tiangolo). From 28e97b2651327acea331442449401f2f3e3c7973 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 26 Oct 2024 18:43:54 +0200 Subject: [PATCH 152/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/how-to/separate-openapi-schemas.md`=20(#12555)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/how-to/separate-openapi-schemas.md | 162 +----------------- 1 file changed, 4 insertions(+), 158 deletions(-) diff --git a/docs/en/docs/how-to/separate-openapi-schemas.md b/docs/en/docs/how-to/separate-openapi-schemas.md index 75fd3f9b6..9a27638fe 100644 --- a/docs/en/docs/how-to/separate-openapi-schemas.md +++ b/docs/en/docs/how-to/separate-openapi-schemas.md @@ -10,123 +10,13 @@ Let's see how that works and how to change it if you need to do that. Let's say you have a Pydantic model with default values, like this one: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} - -# Code below omitted 👇 -``` - -
-👀 Full file preview - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -
- -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} - -# Code below omitted 👇 -``` - -
-👀 Full file preview - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -
- -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} - -# Code below omitted 👇 -``` - -
-👀 Full file preview - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -
- -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *} ### Model for Input If you use this model as an input like here: -//// tab | Python 3.10+ - -```Python hl_lines="14" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} - -# Code below omitted 👇 -``` - -
-👀 Full file preview - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -
- -//// - -//// tab | Python 3.9+ - -```Python hl_lines="16" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} - -# Code below omitted 👇 -``` - -
-👀 Full file preview - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -
- -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} - -# Code below omitted 👇 -``` - -
-👀 Full file preview - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -
- -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *} ...then the `description` field will **not be required**. Because it has a default value of `None`. @@ -142,29 +32,7 @@ You can confirm that in the docs, the `description` field doesn't have a **red a But if you use the same model as an output, like here: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="21" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py hl[19] *} ...then because `description` has a default value, if you **don't return anything** for that field, it will still have that **default value**. @@ -223,29 +91,7 @@ Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓 /// -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/separate_openapi_schemas/tutorial002.py!} -``` - -//// +{* ../../docs_src/separate_openapi_schemas/tutorial002_py310.py hl[10] *} ### Same Schema for Input and Output Models in Docs From d93e431505363fb0f37322136b5d78bf46335f2b Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 26 Oct 2024 16:44:15 +0000 Subject: [PATCH 153/932] =?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 4146331ee..fd56925c9 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/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). * 📝 Update includes in `docs/en/docs/tutorial/first-steps.md`. PR [#12552](https://github.com/fastapi/fastapi/pull/12552) by [@tiangolo](https://github.com/tiangolo). * 📝 Update includes in `docs/en/docs/python-types.md`. PR [#12551](https://github.com/fastapi/fastapi/pull/12551) by [@tiangolo](https://github.com/tiangolo). From 162a32cc2f1099838bb1b3876b43964e3f987670 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 26 Oct 2024 18:50:52 +0200 Subject: [PATCH 154/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/how-to/configure-swagger-ui.md`=20(#12556)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/how-to/configure-swagger-ui.md | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/docs/en/docs/how-to/configure-swagger-ui.md b/docs/en/docs/how-to/configure-swagger-ui.md index 2c649c152..a8a8de48f 100644 --- a/docs/en/docs/how-to/configure-swagger-ui.md +++ b/docs/en/docs/how-to/configure-swagger-ui.md @@ -18,9 +18,7 @@ Without changing the settings, syntax highlighting is enabled by default: But you can disable it by setting `syntaxHighlight` to `False`: -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial001.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *} ...and then Swagger UI won't show the syntax highlighting anymore: @@ -30,9 +28,7 @@ But you can disable it by setting `syntaxHighlight` to `False`: The same way you could set the syntax highlighting theme with the key `"syntaxHighlight.theme"` (notice that it has a dot in the middle): -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial002.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *} That configuration would change the syntax highlighting color theme: @@ -44,17 +40,13 @@ FastAPI includes some default configuration parameters appropriate for most of t It includes these default configurations: -```Python -{!../../fastapi/openapi/docs.py[ln:7-23]!} -``` +{* ../../fastapi/openapi/docs.py ln[8:23] hl[17:23] *} You can override any of them by setting a different value in the argument `swagger_ui_parameters`. For example, to disable `deepLinking` you could pass these settings to `swagger_ui_parameters`: -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial003.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *} ## Other Swagger UI Parameters From 44cfb2f4f5be67499e17a9e7ec0b2faadeb51af4 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 26 Oct 2024 16:51:17 +0000 Subject: [PATCH 155/932] =?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 fd56925c9..d0bb66ee6 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/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). * 📝 Update includes in `docs/en/docs/tutorial/first-steps.md`. PR [#12552](https://github.com/fastapi/fastapi/pull/12552) by [@tiangolo](https://github.com/tiangolo). 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 156/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=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 157/932] =?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 158/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 159/932] =?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 160/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 161/932] =?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 162/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 163/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 164/932] =?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 165/932] =?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 166/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/sql-databases.md`=20(#125?= =?UTF-8?q?30)?= 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 167/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/de/docs/advanced/security/http-basic-auth.md`=20(#1256?= =?UTF-8?q?1)?= 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 168/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 169/932] =?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 170/932] =?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 171/932] =?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 172/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 173/932] =?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 174/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 175/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 176/932] =?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 177/932] =?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 178/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 179/932] =?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 180/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 181/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/advanced/additional-status-codes.md`=20(#12577?= =?UTF-8?q?)?= 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 182/932] =?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 183/932] =?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 184/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 185/932] =?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 186/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 187/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20synt?= =?UTF-8?q?ax=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 188/932] =?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 189/932] =?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 190/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 191/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 192/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 193/932] =?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 194/932] =?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 195/932] =?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 196/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 197/932] =?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 198/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/fr/docs/tutorial/query-params-str-validations.md`=20(#?= =?UTF-8?q?12591)?= 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 199/932] =?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 200/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 201/932] =?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 202/932] =?UTF-8?q?=F0=9F=93=9D=20=20Update=20includes=20i?= =?UTF-8?q?n=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 203/932] =?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 204/932] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Update=20logic=20t?= =?UTF-8?q?o=20import=20and=20check=20`python-multipart`=20for=20compatibi?= =?UTF-8?q?lity=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 205/932] =?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 206/932] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?5.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 207/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20Translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/advanced/response-change-status-code.m?= =?UTF-8?q?d`=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 208/932] =?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 209/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 210/932] =?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 211/932] =?UTF-8?q?=F0=9F=8E=A8=20Adjust=20spacing=20(#126?= =?UTF-8?q?35)?= 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 212/932] =?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 213/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 214/932] =?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 215/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 216/932] =?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 217/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 218/932] =?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 219/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/fr/docs/tutorial/path-params-numeric-validations.md`?= =?UTF-8?q?=20(#12601)?= 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 220/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 221/932] =?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 222/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 223/932] =?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 224/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 225/932] =?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 226/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 227/932] =?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 228/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`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 229/932] =?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 230/932] =?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 231/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 232/932] =?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 233/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`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 234/932] =?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 235/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`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 236/932] =?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 237/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=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 238/932] =?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 From 93bf4c9c2dd77f523f8d2af4e9bcda7d310a06f3 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 28 Oct 2024 20:31:44 +0000 Subject: [PATCH 239/932] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#12707)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/astral-sh/ruff-pre-commit: v0.7.0 → v0.7.1](https://github.com/astral-sh/ruff-pre-commit/compare/v0.7.0...v0.7.1) Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 779018ff9..84bec0421 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.7.0 + rev: v0.7.1 hooks: - id: ruff args: From e1d724ab926ebaa8541f8d76bde7e025e7a52f77 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 28 Oct 2024 20:32:12 +0000 Subject: [PATCH 240/932] =?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 84ffb2e8d..e7bea3c76 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -29,6 +29,10 @@ hide: * 🌐 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). +### 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 ### Refactors From 3f822818b25c042280cbecce1968ca11006ba8e4 Mon Sep 17 00:00:00 2001 From: kim-sangah Date: Tue, 29 Oct 2024 19:32:45 +0900 Subject: [PATCH 241/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20Translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/advanced/response-cookies.md`=20(#1254?= =?UTF-8?q?6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/advanced/response-cookies.md | 53 +++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 docs/ko/docs/advanced/response-cookies.md diff --git a/docs/ko/docs/advanced/response-cookies.md b/docs/ko/docs/advanced/response-cookies.md new file mode 100644 index 000000000..3f87b320a --- /dev/null +++ b/docs/ko/docs/advanced/response-cookies.md @@ -0,0 +1,53 @@ +# 응답 쿠키 + +## `Response` 매개변수 사용하기 + +*경로 작동 함수*에서 `Response` 타입의 매개변수를 선언할 수 있습니다. + +그런 다음 해당 *임시* 응답 객체에서 쿠키를 설정할 수 있습니다. + +```Python hl_lines="1 8-9" +{!../../docs_src/response_cookies/tutorial002.py!} +``` + +그런 다음 필요한 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다. + +그리고 `response_model`을 선언했다면 반환한 객체를 거르고 변환하는 데 여전히 사용됩니다. + +**FastAPI**는 그 *임시* 응답에서 쿠키(또한 헤더 및 상태 코드)를 추출하고, 반환된 값이 포함된 최종 응답에 이를 넣습니다. 이 값은 `response_model`로 걸러지게 됩니다. + +또한 의존관계에서 `Response` 매개변수를 선언하고, 해당 의존성에서 쿠키(및 헤더)를 설정할 수도 있습니다. + +## `Response`를 직접 반환하기 + +코드에서 `Response`를 직접 반환할 때도 쿠키를 생성할 수 있습니다. + +이를 위해 [Response를 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 설명한 대로 응답을 생성할 수 있습니다. + +그런 다음 쿠키를 설정하고 반환하면 됩니다: +```Python hl_lines="1 18" +{!../../docs_src/response_directly/tutorial002.py!} +``` +/// tip + +`Response` 매개변수를 사용하지 않고 응답을 직접 반환하는 경우, FastAPI는 이를 직접 반환한다는 점에 유의하세요. + +따라서 데이터가 올바른 유형인지 확인해야 합니다. 예: `JSONResponse`를 반환하는 경우, JSON과 호환되는지 확인하세요. + +또한 `response_model`로 걸러져야 할 데이터가 전달되지 않도록 확인하세요. + +/// + +### 추가 정보 + +/// note | "기술적 세부사항" + +`from starlette.responses import Response` 또는 `from starlette.responses import JSONResponse`를 사용할 수도 있습니다. + +**FastAPI**는 개발자의 편의를 위해 `fastapi.responses`로 동일한 `starlette.responses`를 제공합니다. 그러나 대부분의 응답은 Starlette에서 직접 제공됩니다. + +또한 `Response`는 헤더와 쿠키를 설정하는 데 자주 사용되므로, **FastAPI**는 이를 `fastapi.Response`로도 제공합니다. + +/// + +사용 가능한 모든 매개변수와 옵션은 Starlette 문서에서 확인할 수 있습니다. From 3f3637ba73d0e15ce2d57910697aed7f152316f6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 29 Oct 2024 10:33:16 +0000 Subject: [PATCH 242/932] =?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 e7bea3c76..e547d8b58 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/advanced/response-cookies.md`. PR [#12546](https://github.com/fastapi/fastapi/pull/12546) by [@kim-sangah](https://github.com/kim-sangah). * 🌐 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). From 46a085ebe7dd24129023a197f2eff6e9e8089afe Mon Sep 17 00:00:00 2001 From: LKY <74170199+kwang1215@users.noreply.github.com> Date: Tue, 29 Oct 2024 19:36:06 +0900 Subject: [PATCH 243/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/tutorial/metadata.md`=20(#12541)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/tutorial/metadata.md | 131 ++++++++++++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 docs/ko/docs/tutorial/metadata.md diff --git a/docs/ko/docs/tutorial/metadata.md b/docs/ko/docs/tutorial/metadata.md new file mode 100644 index 000000000..87531152c --- /dev/null +++ b/docs/ko/docs/tutorial/metadata.md @@ -0,0 +1,131 @@ + +# 메타데이터 및 문서화 URL + +**FastAPI** 응용 프로그램에서 다양한 메타데이터 구성을 사용자 맞춤 설정할 수 있습니다. + +## API에 대한 메타데이터 + +OpenAPI 명세 및 자동화된 API 문서 UI에 사용되는 다음 필드를 설정할 수 있습니다: + +| 매개변수 | 타입 | 설명 | +|----------|------|-------| +| `title` | `str` | API의 제목입니다. | +| `summary` | `str` | API에 대한 짧은 요약입니다. OpenAPI 3.1.0, FastAPI 0.99.0부터 사용 가능 | +| `description` | `str` | API에 대한 짧은 설명입니다. 마크다운을 사용할 수 있습니다. | +| `version` | `string` | API의 버전입니다. OpenAPI의 버전이 아닌, 여러분의 애플리케이션의 버전을 나타냅니다. 예: `2.5.0` | +| `terms_of_service` | `str` | API 이용 약관의 URL입니다. 제공하는 경우 URL 형식이어야 합니다. | +| `contact` | `dict` | 노출된 API에 대한 연락처 정보입니다. 여러 필드를 포함할 수 있습니다.
contact 필드
매개변수타입설명
namestr연락처 인물/조직의 식별명입니다.
urlstr연락처 정보가 담긴 URL입니다. URL 형식이어야 합니다.
emailstr연락처 인물/조직의 이메일 주소입니다. 이메일 주소 형식이어야 합니다.
| +| `license_info` | `dict` | 노출된 API의 라이선스 정보입니다. 여러 필드를 포함할 수 있습니다.
license_info 필드
매개변수타입설명
namestr필수 (license_info가 설정된 경우). API에 사용된 라이선스 이름입니다.
identifierstrAPI에 대한 SPDX 라이선스 표현입니다. identifier 필드는 url 필드와 상호 배타적입니다. OpenAPI 3.1.0, FastAPI 0.99.0부터 사용 가능
urlstrAPI에 사용된 라이선스의 URL입니다. URL 형식이어야 합니다.
| + +다음과 같이 설정할 수 있습니다: + +```Python hl_lines="3-16 19-32" +{!../../docs_src/metadata/tutorial001.py!} +``` + +/// tip + +`description` 필드에 마크다운을 사용할 수 있으며, 출력에서 렌더링됩니다. + +/// + +이 구성을 사용하면 문서 자동화(로 생성된) API 문서는 다음과 같이 보입니다: + + + +## 라이선스 식별자 + +OpenAPI 3.1.0 및 FastAPI 0.99.0부터 `license_info`에 `identifier`를 URL 대신 설정할 수 있습니다. + +예: + +```Python hl_lines="31" +{!../../docs_src/metadata/tutorial001_1.py!} +``` + +## 태그에 대한 메타데이터 + +`openapi_tags` 매개변수를 사용하여 경로 작동을 그룹화하는 데 사용되는 태그에 추가 메타데이터를 추가할 수 있습니다. + +리스트는 각 태그에 대해 하나의 딕셔너리를 포함해야 합니다. + +각 딕셔너리에는 다음이 포함될 수 있습니다: + +* `name` (**필수**): `tags` 매개변수에서 *경로 작동*과 `APIRouter`에 사용된 태그 이름과 동일한 `str`입니다. +* `description`: 태그에 대한 간단한 설명을 담은 `str`입니다. 마크다운을 사용할 수 있으며 문서 UI에 표시됩니다. +* `externalDocs`: 외부 문서를 설명하는 `dict`이며: + * `description`: 외부 문서에 대한 간단한 설명을 담은 `str`입니다. + * `url` (**필수**): 외부 문서의 URL을 담은 `str`입니다. + +### 태그에 대한 메타데이터 생성 + +`users` 및 `items`에 대한 태그 예시와 함께 메타데이터를 생성하고 이를 `openapi_tags` 매개변수로 전달해 보겠습니다: + +```Python hl_lines="3-16 18" +{!../../docs_src/metadata/tutorial004.py!} +``` + +설명 안에 마크다운을 사용할 수 있습니다. 예를 들어 "login"은 굵게(**login**) 표시되고, "fancy"는 기울임꼴(_fancy_)로 표시됩니다. + +/// tip + +사용 중인 모든 태그에 메타데이터를 추가할 필요는 없습니다. + +/// + +### 태그 사용 + +`tags` 매개변수를 *경로 작동* 및 `APIRouter`와 함께 사용하여 태그에 할당할 수 있습니다: + +```Python hl_lines="21 26" +{!../../docs_src/metadata/tutorial004.py!} +``` + +/// info + +태그에 대한 자세한 내용은 [경로 작동 구성](path-operation-configuration.md#tags){.internal-link target=_blank}에서 읽어보세요. + +/// + +### 문서 확인 + +이제 문서를 확인하면 모든 추가 메타데이터가 표시됩니다: + + + +### 태그 순서 + +각 태그 메타데이터 딕셔너리의 순서는 문서 UI에 표시되는 순서를 정의합니다. + +예를 들어, 알파벳 순서상 `users`는 `items` 뒤에 오지만, 우리는 `users` 메타데이터를 리스트의 첫 번째 딕셔너리로 추가했기 때문에 먼저 표시됩니다. + +## OpenAPI URL + +OpenAPI 구조는 기본적으로 `/openapi.json`에서 제공됩니다. + +`openapi_url` 매개변수를 통해 이를 설정할 수 있습니다. + +예를 들어, 이를 `/api/v1/openapi.json`에 제공하도록 설정하려면: + +```Python hl_lines="3" +{!../../docs_src/metadata/tutorial002.py!} +``` + +OpenAPI 구조를 완전히 비활성화하려면 `openapi_url=None`으로 설정할 수 있으며, 이를 사용하여 문서화 사용자 인터페이스도 비활성화됩니다. + +## 문서화 URL + +포함된 두 가지 문서화 사용자 인터페이스를 설정할 수 있습니다: + +* **Swagger UI**: `/docs`에서 제공됩니다. + * `docs_url` 매개변수로 URL을 설정할 수 있습니다. + * `docs_url=None`으로 설정하여 비활성화할 수 있습니다. +* **ReDoc**: `/redoc`에서 제공됩니다. + * `redoc_url` 매개변수로 URL을 설정할 수 있습니다. + * `redoc_url=None`으로 설정하여 비활성화할 수 있습니다. + +예를 들어, Swagger UI를 `/documentation`에서 제공하고 ReDoc을 비활성화하려면: + +```Python hl_lines="3" +{!../../docs_src/metadata/tutorial003.py!} +``` From 6e07910cc4112bea61473fe8f69a272fdeb5e526 Mon Sep 17 00:00:00 2001 From: Lincoln Melo <81188429+LinkolnR@users.noreply.github.com> Date: Tue, 29 Oct 2024 07:36:14 -0300 Subject: [PATCH 244/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/metadata.md`=20(#12538)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/metadata.md | 132 ++++++++++++++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 docs/pt/docs/tutorial/metadata.md diff --git a/docs/pt/docs/tutorial/metadata.md b/docs/pt/docs/tutorial/metadata.md new file mode 100644 index 000000000..5db2882b9 --- /dev/null +++ b/docs/pt/docs/tutorial/metadata.md @@ -0,0 +1,132 @@ +# Metadados e Urls de Documentos + +Você pode personalizar várias configurações de metadados na sua aplicação **FastAPI**. + +## Metadados para API + +Você pode definir os seguintes campos que são usados na especificação OpenAPI e nas interfaces automáticas de documentação da API: + +| Parâmetro | Tipo | Descrição | +|------------|------|-------------| +| `title` | `str` | O título da API. | +| `summary` | `str` | Um breve resumo da API. Disponível desde OpenAPI 3.1.0, FastAPI 0.99.0. | +| `description` | `str` | Uma breve descrição da API. Pode usar Markdown. | +| `version` | `string` | A versão da API. Esta é a versão da sua aplicação, não do OpenAPI. Por exemplo, `2.5.0`. | +| `terms_of_service` | `str` | Uma URL para os Termos de Serviço da API. Se fornecido, deve ser uma URL. | +| `contact` | `dict` | As informações de contato da API exposta. Pode conter vários campos.
Campos de contact
ParâmetroTipoDescrição
namestrO nome identificador da pessoa/organização de contato.
urlstrA URL que aponta para as informações de contato. DEVE estar no formato de uma URL.
emailstrO endereço de e-mail da pessoa/organização de contato. DEVE estar no formato de um endereço de e-mail.
| +| `license_info` | `dict` | As informações de licença para a API exposta. Ela pode conter vários campos.
Campos de license_info
ParâmetroTipoDescrição
namestrOBRIGATÓRIO (se um license_info for definido). O nome da licença usada para a API.
identifierstrUma expressão de licença SPDX para a API. O campo identifier é mutuamente exclusivo do campo url. Disponível desde OpenAPI 3.1.0, FastAPI 0.99.0.
urlstrUma URL para a licença usada para a API. DEVE estar no formato de uma URL.
| + +Você pode defini-los da seguinte maneira: + +```Python hl_lines="3-16 19-32" +{!../../docs_src/metadata/tutorial001.py!} +``` + +/// tip | Dica + +Você pode escrever Markdown no campo `description` e ele será renderizado na saída. + +/// + +Com essa configuração, a documentação automática da API se pareceria com: + + + +## Identificador de Licença + +Desde o OpenAPI 3.1.0 e FastAPI 0.99.0, você também pode definir o license_info com um identifier em vez de uma url. + +Por exemplo: + +```Python hl_lines="31" +{!../../docs_src/metadata/tutorial001_1.py!} +``` + +## Metadados para tags + +Você também pode adicionar metadados adicionais para as diferentes tags usadas para agrupar suas operações de rota com o parâmetro `openapi_tags`. + +Ele recebe uma lista contendo um dicionário para cada tag. + +Cada dicionário pode conter: + +* `name` (**obrigatório**): uma `str` com o mesmo nome da tag que você usa no parâmetro `tags` nas suas *operações de rota* e `APIRouter`s. +* `description`: uma `str` com uma breve descrição da tag. Pode conter Markdown e será exibido na interface de documentação. +* `externalDocs`: um `dict` descrevendo a documentação externa com: + * `description`: uma `str` com uma breve descrição da documentação externa. + * `url` (**obrigatório**): uma `str` com a URL da documentação externa. + +### Criar Metadados para tags + +Vamos tentar isso em um exemplo com tags para `users` e `items`. + +Crie metadados para suas tags e passe-os para o parâmetro `openapi_tags`: + +```Python hl_lines="3-16 18" +{!../../docs_src/metadata/tutorial004.py!} +``` + +Observe que você pode usar Markdown dentro das descrições. Por exemplo, "login" será exibido em negrito (**login**) e "fancy" será exibido em itálico (_fancy_). + +/// tip | Dica + +Você não precisa adicionar metadados para todas as tags que você usa. + +/// + +### Use suas tags + +Use o parâmetro `tags` com suas *operações de rota* (e `APIRouter`s) para atribuí-los a diferentes tags: + +```Python hl_lines="21 26" +{!../../docs_src/metadata/tutorial004.py!} +``` + +/// info | Informação + +Leia mais sobre tags em [Configuração de Operação de Caminho](path-operation-configuration.md#tags){.internal-link target=_blank}. + +/// + +### Cheque os documentos + +Agora, se você verificar a documentação, ela exibirá todos os metadados adicionais: + + + +### Ordem das tags + +A ordem de cada dicionário de metadados de tag também define a ordem exibida na interface de documentação. + +Por exemplo, embora `users` apareça após `items` em ordem alfabética, ele é exibido antes deles, porque adicionamos seus metadados como o primeiro dicionário na lista. + +## URL da OpenAPI + +Por padrão, o esquema OpenAPI é servido em `/openapi.json`. + +Mas você pode configurá-lo com o parâmetro `openapi_url`. + +Por exemplo, para defini-lo para ser servido em `/api/v1/openapi.json`: + +```Python hl_lines="3" +{!../../docs_src/metadata/tutorial002.py!} +``` + +Se você quiser desativar completamente o esquema OpenAPI, pode definir `openapi_url=None`, o que também desativará as interfaces de documentação que o utilizam. + +## URLs da Documentação + +Você pode configurar as duas interfaces de documentação incluídas: + +* **Swagger UI**: acessível em `/docs`. + * Você pode definir sua URL com o parâmetro `docs_url`. + * Você pode desativá-la definindo `docs_url=None`. +* **ReDoc**: acessível em `/redoc`. + * Você pode definir sua URL com o parâmetro `redoc_url`. + * Você pode desativá-la definindo `redoc_url=None`. + +Por exemplo, para definir o Swagger UI para ser servido em `/documentation` e desativar o ReDoc: + +```Python hl_lines="3" +{!../../docs_src/metadata/tutorial003.py!} +``` From 8cae611101fb4b1e6804df032c020758447a7ded Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 29 Oct 2024 10:36:58 +0000 Subject: [PATCH 245/932] =?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 e547d8b58..b6d679ae3 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/tutorial/metadata.md`. PR [#12541](https://github.com/fastapi/fastapi/pull/12541) by [@kwang1215](https://github.com/kwang1215). * 🌐 Add Korean Translation for `docs/ko/docs/advanced/response-cookies.md`. PR [#12546](https://github.com/fastapi/fastapi/pull/12546) by [@kim-sangah](https://github.com/kim-sangah). * 🌐 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). From c8f5755d0a14f6013a3667f3414753cbe1604660 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 29 Oct 2024 10:39:18 +0000 Subject: [PATCH 246/932] =?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 b6d679ae3..ee044f228 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -26,6 +26,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/metadata.md`. PR [#12538](https://github.com/fastapi/fastapi/pull/12538) by [@LinkolnR](https://github.com/LinkolnR). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/metadata.md`. PR [#12541](https://github.com/fastapi/fastapi/pull/12541) by [@kwang1215](https://github.com/kwang1215). * 🌐 Add Korean Translation for `docs/ko/docs/advanced/response-cookies.md`. PR [#12546](https://github.com/fastapi/fastapi/pull/12546) by [@kim-sangah](https://github.com/kim-sangah). * 🌐 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). From 268eac9e16cccf2b60bcc1d4a70ff3b15b6958b9 Mon Sep 17 00:00:00 2001 From: Krishna Madhavan Date: Tue, 29 Oct 2024 16:32:16 +0530 Subject: [PATCH 247/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/advanced/security/oauth2-scopes.md`=20(#12572)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/advanced/security/oauth2-scopes.md | 528 +----------------- 1 file changed, 8 insertions(+), 520 deletions(-) diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index 3db284d02..5ba0b1c14 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -62,71 +62,7 @@ For OAuth2 they are just strings. First, let's quickly see the parts that change from the examples in the main **Tutorial - User Guide** for [OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Now using OAuth2 scopes: -//// tab | Python 3.10+ - -```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:125,129:135,140,156] *} Now let's review those changes step by step. @@ -136,71 +72,7 @@ The first change is that now we are declaring the OAuth2 security scheme with tw The `scopes` parameter receives a `dict` with each scope as a key and the description as the value: -//// tab | Python 3.10+ - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="64-67" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="62-65" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *} Because we are now declaring those scopes, they will show up in the API docs when you log-in/authorize. @@ -226,71 +98,7 @@ But in your application, for security, you should make sure you only add the sco /// -//// tab | Python 3.10+ - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="157" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="155" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[156] *} ## Declare scopes in *path operations* and dependencies @@ -316,71 +124,7 @@ We are doing it here to demonstrate how **FastAPI** handles scopes declared at d /// -//// tab | Python 3.10+ - -```Python hl_lines="5 140 171" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="5 140 171" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 141 172" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="4 139 168" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="5 140 169" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="5 140 169" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[5,140,171] *} /// info | "Technical Details" @@ -406,71 +150,7 @@ We also declare a special parameter of type `SecurityScopes`, imported from `fas This `SecurityScopes` class is similar to `Request` (`Request` was used to get the request object directly). -//// tab | Python 3.10+ - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 107" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8 105" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *} ## Use the `scopes` @@ -484,71 +164,7 @@ We create an `HTTPException` that we can reuse (`raise`) later at several points In this exception, we include the scopes required (if any) as a string separated by spaces (using `scope_str`). We put that string containing the scopes in the `WWW-Authenticate` header (this is part of the spec). -//// tab | Python 3.10+ - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="107 109-117" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="105 107-115" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *} ## Verify the `username` and data shape @@ -564,71 +180,7 @@ Instead of, for example, a `dict`, or something else, as it could break the appl We also verify that we have a user with that username, and if not, we raise that same exception we created before. -//// tab | Python 3.10+ - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="48 118-129" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="46 116-127" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:128] *} ## Verify the `scopes` @@ -636,71 +188,7 @@ We now verify that all the scopes required, by this dependency and all the depen For this, we use `security_scopes.scopes`, that contains a `list` with all these scopes as `str`. -//// tab | Python 3.10+ - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="130-136" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="128-134" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[129:135] *} ## Dependency tree and scopes From 25c63800f6c5c76b8514d6f3c3b3178c12e24471 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 29 Oct 2024 11:02:39 +0000 Subject: [PATCH 248/932] =?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 ee044f228..f510f6c30 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/security/oauth2-scopes.md`. PR [#12572](https://github.com/fastapi/fastapi/pull/12572) by [@krishnamadhavan](https://github.com/krishnamadhavan). * 📝 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). From c5a9d3ac28cd21a010608f36c9967c7185a54904 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Pedro=20Pereira=20Holanda?= Date: Tue, 29 Oct 2024 08:47:10 -0300 Subject: [PATCH 249/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20Trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/custom-response.md`=20(#1?= =?UTF-8?q?2631)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/custom-response.md | 344 +++++++++++++++++++++++ 1 file changed, 344 insertions(+) create mode 100644 docs/pt/docs/advanced/custom-response.md diff --git a/docs/pt/docs/advanced/custom-response.md b/docs/pt/docs/advanced/custom-response.md new file mode 100644 index 000000000..5f673d7ce --- /dev/null +++ b/docs/pt/docs/advanced/custom-response.md @@ -0,0 +1,344 @@ +# Resposta Personalizada - HTML, Stream, File e outras + +Por padrão, o **FastAPI** irá retornar respostas utilizando `JSONResponse`. + +Mas você pode sobrescrever esse comportamento utilizando `Response` diretamente, como visto em [Retornando uma Resposta Diretamente](response-directly.md){.internal-link target=_blank}. + +Mas se você retornar uma `Response` diretamente (ou qualquer subclasse, como `JSONResponse`), os dados não serão convertidos automaticamente (mesmo que você declare um `response_model`), e a documentação não será gerada automaticamente (por exemplo, incluindo o "media type", no cabeçalho HTTP `Content-Type` como parte do esquema OpenAPI gerado). + +Mas você também pode declarar a `Response` que você deseja utilizar (e.g. qualquer subclasse de `Response`), em um *decorador de operação de rota* utilizando o parâmetro `response_class`. + +Os conteúdos que você retorna em sua *função de operador de rota* serão colocados dentro dessa `Response`. + +E se a `Response` tiver um media type JSON (`application/json`), como é o caso com `JSONResponse` e `UJSONResponse`, os dados que você retornar serão automaticamente convertidos (e filtrados) com qualquer `response_model` do Pydantic que for declarado em sua *função de operador de rota*. + +/// note | Nota + +Se você utilizar uma classe de Resposta sem media type, o FastAPI esperará que sua resposta não tenha conteúdo, então ele não irá documentar o formato da resposta na documentação OpenAPI gerada. + +/// + +## Utilizando `ORJSONResponse` + +Por exemplo, se você precisa bastante de performance, você pode instalar e utilizar o `orjson` e definir a resposta para ser uma `ORJSONResponse`. + +Importe a classe, ou subclasse, de `Response` que você deseja utilizar e declare ela no *decorador de operação de rota*. + +Para respostas grandes, retornar uma `Response` diretamente é muito mais rápido que retornar um dicionário. + +Isso ocorre por que, por padrão, o FastAPI irá verificar cada item dentro do dicionário e garantir que ele seja serializável para JSON, utilizando o mesmo[Codificador Compatível com JSON](../tutorial/encoder.md){.internal-link target=_blank} explicado no tutorial. Isso permite que você retorne **objetos abstratos**, como modelos do banco de dados, por exemplo. + +Mas se você tem certeza que o conteúdo que você está retornando é **serializável com JSON**, você pode passá-lo diretamente para a classe de resposta e evitar o trabalho extra que o FastAPI teria ao passar o conteúdo pelo `jsonable_encoder` antes de passar para a classe de resposta. + +```Python hl_lines="2 7" +{!../../docs_src/custom_response/tutorial001b.py!} +``` + +/// info | Informação + +O parâmetro `response_class` também será usado para definir o "media type" da resposta. + +Neste caso, o cabeçalho HTTP `Content-Type` irá ser definido como `application/json`. + +E será documentado como tal no OpenAPI. + +/// + +/// tip | Dica + +A `ORJSONResponse` está disponível apenas no FastAPI, e não no Starlette. + +/// + +## Resposta HTML + +Para retornar uma resposta com HTML diretamente do **FastAPI**, utilize `HTMLResponse`. + +* Importe `HTMLResponse` +* Passe `HTMLResponse` como o parâmetro de `response_class` do seu *decorador de operação de rota*. + +```Python hl_lines="2 7" +{!../../docs_src/custom_response/tutorial002.py!} +``` + +/// info | Informação + +O parâmetro `response_class` também será usado para definir o "media type" da resposta. + +Neste caso, o cabeçalho HTTP `Content-Type` será definido como `text/html`. + +E será documentado como tal no OpenAPI. + +/// + +### Retornando uma `Response` + +Como visto em [Retornando uma Resposta Diretamente](response-directly.md){.internal-link target=_blank}, você também pode sobrescrever a resposta diretamente na sua *operação de rota*, ao retornar ela. + +O mesmo exemplo de antes, retornando uma `HTMLResponse`, poderia parecer com: + +```Python hl_lines="2 7 19" +{!../../docs_src/custom_response/tutorial003.py!} +``` + +/// warning | Aviso + +Uma `Response` retornada diretamente em sua *função de operação de rota* não será documentada no OpenAPI (por exemplo, o `Content-Type` não será documentado) e não será visível na documentação interativa automática. + +/// + +/// info | Informação + +Obviamente, o cabeçalho `Content-Type`, o código de status, etc, virão do objeto `Response` que você retornou. + +/// + +### Documentar no OpenAPI e sobrescrever `Response` + +Se você deseja sobrescrever a resposta dentro de uma função, mas ao mesmo tempo documentar o "media type" no OpenAPI, você pode utilizar o parâmetro `response_class` E retornar um objeto `Response`. + +A `response_class` será usada apenas para documentar o OpenAPI da *operação de rota*, mas sua `Response` será usada como foi definida. + +##### Retornando uma `HTMLResponse` diretamente + +Por exemplo, poderia ser algo como: + +```Python hl_lines="7 21 23" +{!../../docs_src/custom_response/tutorial004.py!} +``` + +Neste exemplo, a função `generate_html_response()` já cria e retorna uma `Response` em vez de retornar o HTML em uma `str`. + +Ao retornar o resultado chamando `generate_html_response()`, você já está retornando uma `Response` que irá sobrescrever o comportamento padrão do **FastAPI**. + +Mas se você passasse uma `HTMLResponse` em `response_class` também, o **FastAPI** saberia como documentar isso no OpenAPI e na documentação interativa como um HTML com `text/html`: + + + +## Respostas disponíveis + +Aqui estão algumas dos tipos de resposta disponíveis. + +Lembre-se que você pode utilizar `Response` para retornar qualquer outra coisa, ou até mesmo criar uma subclasse personalizada. + +/// note | Detalhes Técnicos + +Você também pode utilizar `from starlette.responses import HTMLResponse`. + +O **FastAPI** provê a mesma `starlette.responses` como `fastapi.responses` apenas como uma facilidade para você, desenvolvedor. Mas a maioria das respostas disponíveis vêm diretamente do Starlette. + +/// + +### `Response` + +A classe principal de respostas, todas as outras respostas herdam dela. + +Você pode retorná-la diretamente. + +Ela aceita os seguintes parâmetros: + +* `content` - Uma sequência de caracteres (`str`) ou `bytes`. +* `status_code` - Um código de status HTTP do tipo `int`. +* `headers` - Um dicionário `dict` de strings. +* `media_type` - Uma `str` informando o media type. E.g. `"text/html"`. + +O FastAPI (Starlette, na verdade) irá incluir o cabeçalho Content-Length automaticamente. Ele também irá incluir o cabeçalho Content-Type, baseado no `media_type` e acrescentando uma codificação para tipos textuais. + +```Python hl_lines="1 18" +{!../../docs_src/response_directly/tutorial002.py!} +``` + +### `HTMLResponse` + +Usa algum texto ou sequência de bytes e retorna uma resposta HTML. Como você leu acima. + +### `PlainTextResponse` + +Usa algum texto ou sequência de bytes para retornar uma resposta de texto não formatado. + +```Python hl_lines="2 7 9" +{!../../docs_src/custom_response/tutorial005.py!} +``` + +### `JSONResponse` + +Pega alguns dados e retorna uma resposta com codificação `application/json`. + +É a resposta padrão utilizada no **FastAPI**, como você leu acima. + +### `ORJSONResponse` + +Uma alternativa mais rápida de resposta JSON utilizando o `orjson`, como você leu acima. + +/// info | Informação + +Essa resposta requer a instalação do pacote `orjson`, com o comando `pip install orjson`, por exemplo. + +/// + +### `UJSONResponse` + +Uma alternativa de resposta JSON utilizando a biblioteca `ujson`. + +/// info | Informação + +Essa resposta requer a instalação do pacote `ujson`, com o comando `pip install ujson`, por exemplo. + +/// + +/// warning | Aviso + +`ujson` é menos cauteloso que a implementação nativa do Python na forma que os casos especiais são tratados + +/// + +```Python hl_lines="2 7" +{!../../docs_src/custom_response/tutorial001.py!} +``` + +/// tip | Dica + +É possível que `ORJSONResponse` seja uma alternativa mais rápida. + +/// + +### `RedirectResponse` + +Retorna um redirecionamento HTTP. Utiliza o código de status 307 (Redirecionamento Temporário) por padrão. + +Você pode retornar uma `RedirectResponse` diretamente: + +```Python hl_lines="2 9" +{!../../docs_src/custom_response/tutorial006.py!} +``` + +--- + +Ou você pode utilizá-la no parâmetro `response_class`: + +```Python hl_lines="2 7 9" +{!../../docs_src/custom_response/tutorial006b.py!} +``` + +Se você fizer isso, então você pode retornar a URL diretamente da sua *função de operação de rota* + +Neste caso, o `status_code` utilizada será o padrão de `RedirectResponse`, que é `307`. + +--- + +Você também pode utilizar o parâmetro `status_code` combinado com o parâmetro `response_class`: + +```Python hl_lines="2 7 9" +{!../../docs_src/custom_response/tutorial006c.py!} +``` + +### `StreamingResponse` + +Recebe uma gerador assíncrono ou um gerador/iterador comum e retorna o corpo da requisição continuamente (stream). + +```Python hl_lines="2 14" +{!../../docs_src/custom_response/tutorial007.py!} +``` + +#### Utilizando `StreamingResponse` com objetos semelhantes a arquivos + +Se você tiver um objeto semelhante a um arquivo (e.g. o objeto retornado por `open()`), você pode criar uma função geradora para iterar sobre esse objeto. + +Dessa forma, você não precisa ler todo o arquivo na memória primeiro, e você pode passar essa função geradora para `StreamingResponse` e retorná-la. + +Isso inclui muitas bibliotecas que interagem com armazenamento em nuvem, processamento de vídeos, entre outras. + +```{ .python .annotate hl_lines="2 10-12 14" } +{!../../docs_src/custom_response/tutorial008.py!} +``` + +1. Essa é a função geradora. É definida como "função geradora" porque contém declarações `yield` nela. +2. Ao utilizar o bloco `with`, nós garantimos que o objeto semelhante a um arquivo é fechado após a função geradora ser finalizada. Isto é, após a resposta terminar de ser enivada. +3. Essa declaração `yield from` informa a função para iterar sobre essa coisa nomeada de `file_like`. E então, para cada parte iterada, fornece essa parte como se viesse dessa função geradora (`iterfile`). + + Então, é uma função geradora que transfere o trabalho de "geração" para alguma outra coisa interna. + + Fazendo dessa forma, podemos colocá-la em um bloco `with`, e assim garantir que o objeto semelhante a um arquivo é fechado quando a função termina. + +/// tip | Dica + +Perceba que aqui estamos utilizando o `open()` da biblioteca padrão que não suporta `async` e `await`, e declaramos a operação de rota com o `def` básico. + +/// + +### `FileResponse` + +Envia um arquivo de forma assíncrona e contínua (stream). +* +Recebe um conjunto de argumentos do construtor diferente dos outros tipos de resposta: + +* `path` - O caminho do arquivo que será transmitido +* `headers` - quaisquer cabeçalhos que serão incluídos, como um dicionário. +* `media_type` - Uma string com o media type. Se não for definida, o media type é inferido a partir do nome ou caminho do arquivo. +* `filename` - Se for definido, é incluído no cabeçalho `Content-Disposition`. + +Respostas de Arquivos incluem o tamanho do arquivo, data da última modificação e ETags apropriados, nos cabeçalhos `Content-Length`, `Last-Modified` e `ETag`, respectivamente. + +```Python hl_lines="2 10" +{!../../docs_src/custom_response/tutorial009.py!} +``` + +Você também pode usar o parâmetro `response_class`: + +```Python hl_lines="2 8 10" +{!../../docs_src/custom_response/tutorial009b.py!} +``` + +Nesse caso, você pode retornar o caminho do arquivo diretamente da sua *função de operação de rota*. + +## Classe de resposta personalizada + +Você pode criar sua própria classe de resposta, herdando de `Response` e usando essa nova classe. + +Por exemplo, vamos supor que você queira utilizar o `orjson`, mas com algumas configurações personalizadas que não estão incluídas na classe `ORJSONResponse`. + +Vamos supor também que você queira retornar um JSON indentado e formatado, então você quer utilizar a opção `orjson.OPT_INDENT_2` do orjson. + +Você poderia criar uma classe `CustomORJSONResponse`. A principal coisa a ser feita é sobrecarregar o método render da classe Response, `Response.render(content)`, que retorna o conteúdo em bytes, para retornar o conteúdo que você deseja: + +```Python hl_lines="9-14 17" +{!../../docs_src/custom_response/tutorial009c.py!} +``` + +Agora em vez de retornar: + +```json +{"message": "Hello World"} +``` + +...essa resposta retornará: + +```json +{ + "message": "Hello World" +} +``` + +Obviamente, você provavelmente vai encontrar maneiras muito melhores de se aproveitar disso do que a formatação de JSON. 😉 + +## Classe de resposta padrão + +Quando você criar uma instância da classe **FastAPI** ou um `APIRouter` você pode especificar qual classe de resposta utilizar por padrão. + +O padrão que define isso é o `default_response_class`. + +No exemplo abaixo, o **FastAPI** irá utilizar `ORJSONResponse` por padrão, em todas as *operações de rota*, em vez de `JSONResponse`. + +```Python hl_lines="2 4" +{!../../docs_src/custom_response/tutorial010.py!} +``` + +/// tip | Dica + +Você ainda pode substituir `response_class` em *operações de rota* como antes. + +/// + +## Documentação adicional + +Você também pode declarar o media type e muitos outros detalhes no OpenAPI utilizando `responses`: [Retornos Adicionais no OpenAPI](additional-responses.md){.internal-link target=_blank}. From 8dc523b1efda92d878796c22f9a4a88f4a03605a Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 29 Oct 2024 11:47:36 +0000 Subject: [PATCH 250/932] =?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 f510f6c30..ae4567f00 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Portuguese Translation for `docs/pt/docs/advanced/custom-response.md`. PR [#12631](https://github.com/fastapi/fastapi/pull/12631) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/metadata.md`. PR [#12538](https://github.com/fastapi/fastapi/pull/12538) by [@LinkolnR](https://github.com/LinkolnR). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/metadata.md`. PR [#12541](https://github.com/fastapi/fastapi/pull/12541) by [@kwang1215](https://github.com/kwang1215). * 🌐 Add Korean Translation for `docs/ko/docs/advanced/response-cookies.md`. PR [#12546](https://github.com/fastapi/fastapi/pull/12546) by [@kim-sangah](https://github.com/kim-sangah). From ece28bc8db18d9b0ea176855730ba2773f044a8b Mon Sep 17 00:00:00 2001 From: Luis Rodrigues <103431660+devluisrodrigues@users.noreply.github.com> Date: Wed, 30 Oct 2024 16:52:32 -0300 Subject: [PATCH 251/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/request-files.md`=20(#127?= =?UTF-8?q?06)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/request-files.md | 176 +++++++++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 docs/pt/docs/tutorial/request-files.md diff --git a/docs/pt/docs/tutorial/request-files.md b/docs/pt/docs/tutorial/request-files.md new file mode 100644 index 000000000..d230f1feb --- /dev/null +++ b/docs/pt/docs/tutorial/request-files.md @@ -0,0 +1,176 @@ +# Arquivos de Requisição + +Você pode definir arquivos para serem enviados pelo cliente usando `File`. + +/// info | Informação + +Para receber arquivos enviados, primeiro instale o `python-multipart`. + +Garanta que você criou um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, o ativou e então o instalou, por exemplo: + +```console +$ pip install python-multipart +``` + +Isso é necessário, visto que os arquivos enviados são enviados como "dados de formulário". + +/// + +## Importe `File` + +Importe `File` e `UploadFile` de `fastapi`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} + +## Definir Parâmetros `File` + +Crie parâmetros de arquivo da mesma forma que você faria para `Body` ou `Form`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} + +/// info | Informação + +`File` é uma classe que herda diretamente de `Form`. + +Mas lembre-se que quando você importa `Query`, `Path`, `File` e outros de `fastapi`, eles são, na verdade, funções que retornam classes especiais. + +/// + +/// tip | Dica + +Para declarar corpos de arquivos, você precisa usar `File`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta ou parâmetros de corpo (JSON). + +/// + +Os arquivos serão enviados como "dados de formulário". + +Se você declarar o tipo do parâmetro da função da sua *operação de rota* como `bytes`, o **FastAPI** lerá o arquivo para você e você receberá o conteúdo como `bytes`. + +Mantenha em mente que isso significa que todo o conteúdo será armazenado na memória. Isso funcionará bem para arquivos pequenos. + +Mas há muitos casos em que você pode se beneficiar do uso de `UploadFile`. + +## Parâmetros de Arquivo com `UploadFile` + +Defina um parâmetro de arquivo com um tipo de `UploadFile`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} + +Utilizar `UploadFile` tem várias vantagens sobre `bytes`: + +* Você não precisa utilizar o `File()` no valor padrão do parâmetro. +* Ele utiliza um arquivo "spooled": + * Um arquivo armazenado na memória até um limite máximo de tamanho, e após passar esse limite, ele será armazenado no disco. +* Isso significa que funcionará bem para arquivos grandes como imagens, vídeos, binários grandes, etc., sem consumir toda a memória. +* Você pode receber metadados do arquivo enviado. +* Ele tem uma file-like interface `assíncrona`. +* Ele expõe um objeto python `SpooledTemporaryFile` que você pode passar diretamente para outras bibliotecas que esperam um objeto semelhante a um arquivo("file-like"). + +### `UploadFile` + +`UploadFile` tem os seguintes atributos: + +* `filename`: Uma `str` com o nome do arquivo original que foi enviado (por exemplo, `myimage.jpg`). +* `content_type`: Uma `str` com o tipo de conteúdo (tipo MIME / tipo de mídia) (por exemplo, `image/jpeg`). +* `file`: Um `SpooledTemporaryFile` (um file-like objeto). Este é o objeto de arquivo Python que você pode passar diretamente para outras funções ou bibliotecas que esperam um objeto semelhante a um arquivo("file-like"). + +`UploadFile` tem os seguintes métodos `assíncronos`. Todos eles chamam os métodos de arquivo correspondentes por baixo dos panos (usando o `SpooledTemporaryFile` interno). + +* `write(data)`: Escreve `data` (`str` ou `bytes`) no arquivo. +* `read(size)`: Lê `size` (`int`) bytes/caracteres do arquivo. +* `seek(offset)`: Vai para o byte na posição `offset` (`int`) no arquivo. + * Por exemplo, `await myfile.seek(0)` irá para o início do arquivo. + * Isso é especialmente útil se você executar `await myfile.read()` uma vez e precisar ler o conteúdo novamente. +* `close()`: Fecha o arquivo. + +Como todos esses métodos são métodos `assíncronos`, você precisa "aguardar" por eles. + +Por exemplo, dentro de uma função de *operação de rota* `assíncrona`, você pode obter o conteúdo com: + +```Python +contents = await myfile.read() +``` + +Se você estiver dentro de uma função de *operação de rota* normal `def`, você pode acessar o `UploadFile.file` diretamente, por exemplo: + +```Python +contents = myfile.file.read() +``` + +/// note | Detalhes Técnicos do `async` + +Quando você usa os métodos `async`, o **FastAPI** executa os métodos de arquivo em um threadpool e aguarda por eles. + +/// + +/// note | "Detalhes Técnicos do Starlette" + +O `UploadFile` do ***FastAPI** herda diretamente do `UploadFile` do **Starlette** , mas adiciona algumas partes necessárias para torná-lo compatível com o **Pydantic** e as outras partes do FastAPI. + +/// + +## O que é "Form Data" + +O jeito que os formulários HTML (`
`) enviam os dados para o servidor normalmente usa uma codificação "especial" para esses dados, a qual é diferente do JSON. + +**FastAPI** se certificará de ler esses dados do lugar certo, ao invés de JSON. + +/// note | "Detalhes Técnicos" + +Dados de formulários normalmente são codificados usando o "media type" (tipo de mídia) `application/x-www-form-urlencoded` quando não incluem arquivos. + +Mas quando o formulário inclui arquivos, ele é codificado como `multipart/form-data`. Se você usar `File`, o **FastAPI** saberá que tem que pegar os arquivos da parte correta do corpo da requisição. + +Se você quiser ler mais sobre essas codificações e campos de formulário, vá para a MDN web docs para POST. + +/// + +/// warning | Aviso + +Você pode declarar múltiplos parâmetros `File` e `Form` em uma *operação de rota*, mas você não pode declarar campos `Body` que você espera receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`. + +Isso não é uma limitação do **FastAPI**, é parte do protocolo HTTP. + +/// + +## Upload de Arquivo Opcional + +Você pode tornar um arquivo opcional usando anotações de tipo padrão e definindo um valor padrão de `None`: + +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} + +## `UploadFile` com Metadados Adicionais + +Você também pode usar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais: + +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} + +## Uploads de Múltiplos Arquivos + +É possível realizar o upload de vários arquivos ao mesmo tempo. + +Eles serão associados ao mesmo "campo de formulário" enviado usando "dados de formulário". + +Para usar isso, declare uma lista de `bytes` ou `UploadFile`: + +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} + +Você receberá, tal como declarado, uma `list` de `bytes` ou `UploadFile`. + +/// note | "Detalhes Técnicos" + +Você pode também pode usar `from starlette.responses import HTMLResponse`. + +**FastAPI** providencia o mesmo `starlette.responses` que `fastapi.responses` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vem diretamente do Starlette. + +/// + +### Uploads de Múltiplos Arquivos com Metadados Adicionais + +Da mesma forma de antes, você pode usar `File()` para definir parâmetros adicionais, mesmo para `UploadFile`: + +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} + +## Recapitulando + +Utilize `File`, `bytes` e `UploadFile` para declarar arquivos a serem enviados na requisição, enviados como dados de formulário. From 872feaccbe065c243e15d76efce33f25ba07e73c Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 30 Oct 2024 19:52:53 +0000 Subject: [PATCH 252/932] =?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 ae4567f00..4ff93b7bd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/request-files.md`. PR [#12706](https://github.com/fastapi/fastapi/pull/12706) by [@devluisrodrigues](https://github.com/devluisrodrigues). * 🌐 Add Portuguese Translation for `docs/pt/docs/advanced/custom-response.md`. PR [#12631](https://github.com/fastapi/fastapi/pull/12631) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/metadata.md`. PR [#12538](https://github.com/fastapi/fastapi/pull/12538) by [@LinkolnR](https://github.com/LinkolnR). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/metadata.md`. PR [#12541](https://github.com/fastapi/fastapi/pull/12541) by [@kwang1215](https://github.com/kwang1215). From 5be5ea92c0257cb1a0de61c0ab9b51285bf7f60e Mon Sep 17 00:00:00 2001 From: Fernando Alzueta Date: Wed, 30 Oct 2024 16:53:03 -0300 Subject: [PATCH 253/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/openapi-callbacks.md`=20(?= =?UTF-8?q?#12705)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/openapi-callbacks.md | 194 +++++++++++++++++++++ 1 file changed, 194 insertions(+) create mode 100644 docs/pt/docs/advanced/openapi-callbacks.md diff --git a/docs/pt/docs/advanced/openapi-callbacks.md b/docs/pt/docs/advanced/openapi-callbacks.md new file mode 100644 index 000000000..c66ababa0 --- /dev/null +++ b/docs/pt/docs/advanced/openapi-callbacks.md @@ -0,0 +1,194 @@ +# Callbacks na OpenAPI + +Você poderia criar uma API com uma *operação de rota* que poderia acionar uma solicitação a uma *API externa* criada por outra pessoa (provavelmente o mesmo desenvolvedor que estaria *usando* sua API). + +O processo que acontece quando seu aplicativo de API chama a *API externa* é chamado de "callback". Porque o software que o desenvolvedor externo escreveu envia uma solicitação para sua API e então sua API *chama de volta*, enviando uma solicitação para uma *API externa* (que provavelmente foi criada pelo mesmo desenvolvedor). + +Nesse caso, você poderia querer documentar como essa API externa *deveria* ser. Que *operação de rota* ela deveria ter, que corpo ela deveria esperar, que resposta ela deveria retornar, etc. + +## Um aplicativo com callbacks + +Vamos ver tudo isso com um exemplo. + +Imagine que você tem um aplicativo que permite criar faturas. + +Essas faturas terão um `id`, `title` (opcional), `customer` e `total`. + +O usuário da sua API (um desenvolvedor externo) criará uma fatura em sua API com uma solicitação POST. + +Então sua API irá (vamos imaginar): + +* Enviar uma solicitação de pagamento para o desenvolvedor externo. +* Coletar o dinheiro. +* Enviar a notificação de volta para o usuário da API (o desenvolvedor externo). +* Isso será feito enviando uma solicitação POST (de *sua API*) para alguma *API externa* fornecida por esse desenvolvedor externo (este é o "callback"). + +## O aplicativo **FastAPI** normal + +Vamos primeiro ver como o aplicativo da API normal se pareceria antes de adicionar o callback. + +Ele terá uma *operação de rota* que receberá um corpo `Invoice`, e um parâmetro de consulta `callback_url` que conterá a URL para o callback. + +Essa parte é bastante normal, a maior parte do código provavelmente já é familiar para você: + +```Python hl_lines="9-13 36-53" +{!../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +/// tip | Dica + +O parâmetro de consulta `callback_url` usa um tipo Pydantic Url. + +/// + +A única coisa nova é o argumento `callbacks=invoices_callback_router.routes` no decorador da *operação de rota*. Veremos o que é isso a seguir. + +## Documentando o callback + +O código real do callback dependerá muito do seu próprio aplicativo de API. + +E provavelmente variará muito de um aplicativo para o outro. + +Poderia ser apenas uma ou duas linhas de código, como: + +```Python +callback_url = "https://example.com/api/v1/invoices/events/" +httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) +``` + +Mas possivelmente a parte mais importante do callback é garantir que o usuário da sua API (o desenvolvedor externo) implemente a *API externa* corretamente, de acordo com os dados que *sua API* vai enviar no corpo da solicitação do callback, etc. + +Então, o que faremos a seguir é adicionar o código para documentar como essa *API externa* deve ser para receber o callback de *sua API*. + +A documentação aparecerá na interface do Swagger em `/docs` em sua API, e permitirá que os desenvolvedores externos saibam como construir a *API externa*. + +Esse exemplo não implementa o callback em si (que poderia ser apenas uma linha de código), apenas a parte da documentação. + +/// tip | Dica + +O callback real é apenas uma solicitação HTTP. + +Quando implementando o callback por você mesmo, você pode usar algo como HTTPX ou Requisições. + +/// + +## Escrevendo o código de documentação do callback + +Esse código não será executado em seu aplicativo, nós só precisamos dele para *documentar* como essa *API externa* deveria ser. + +Mas, você já sabe como criar facilmente documentação automática para uma API com o **FastAPI**. + +Então vamos usar esse mesmo conhecimento para documentar como a *API externa* deveria ser... criando as *operações de rota* que a *API externa* deveria implementar (as que sua API irá chamar). + +/// tip | Dica + +Quando escrever o código para documentar um callback, pode ser útil imaginar que você é aquele *desenvolvedor externo*. E que você está atualmente implementando a *API externa*, não *sua API*. + +Adotar temporariamente esse ponto de vista (do *desenvolvedor externo*) pode ajudar a sentir que é mais óbvio onde colocar os parâmetros, o modelo Pydantic para o corpo, para a resposta, etc. para essa *API externa*. + +/// + +### Criar um `APIRouter` para o callback + +Primeiramente crie um novo `APIRouter` que conterá um ou mais callbacks. + +```Python hl_lines="3 25" +{!../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +### Crie a *operação de rota* do callback + +Para criar a *operação de rota* do callback, use o mesmo `APIRouter` que você criou acima. + +Ele deve parecer exatamente como uma *operação de rota* normal do FastAPI: + +* Ele provavelmente deveria ter uma declaração do corpo que deveria receber, por exemplo. `body: InvoiceEvent`. +* E também deveria ter uma declaração de um código de status de resposta, por exemplo. `response_model=InvoiceEventReceived`. + +```Python hl_lines="16-18 21-22 28-32" +{!../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +Há 2 diferenças principais de uma *operação de rota* normal: + +* Ela não necessita ter nenhum código real, porque seu aplicativo nunca chamará esse código. Ele é usado apenas para documentar a *API externa*. Então, a função poderia ter apenas `pass`. +* A *rota* pode conter uma expressão OpenAPI 3 (veja mais abaixo) onde pode usar variáveis com parâmetros e partes da solicitação original enviada para *sua API*. + +### A expressão do caminho do callback + +A *rota* do callback pode ter uma expressão OpenAPI 3 que pode conter partes da solicitação original enviada para *sua API*. + +Nesse caso, é a `str`: + +```Python +"{$callback_url}/invoices/{$request.body.id}" +``` + +Então, se o usuário da sua API (o desenvolvedor externo) enviar uma solicitação para *sua API* para: + +``` +https://yourapi.com/invoices/?callback_url=https://www.external.org/events +``` + +com um corpo JSON de: + +```JSON +{ + "id": "2expen51ve", + "customer": "Mr. Richie Rich", + "total": "9999" +} +``` + +então *sua API* processará a fatura e, em algum momento posterior, enviará uma solicitação de callback para o `callback_url` (a *API externa*): + +``` +https://www.external.org/events/invoices/2expen51ve +``` + +com um corpo JSON contendo algo como: + +```JSON +{ + "description": "Payment celebration", + "paid": true +} +``` + +e esperaria uma resposta daquela *API externa* com um corpo JSON como: + +```JSON +{ + "ok": true +} +``` + +/// tip | Dica + +Perceba como a URL de callback usada contém a URL recebida como um parâmetro de consulta em `callback_url` (`https://www.external.org/events`) e também o `id` da fatura de dentro do corpo JSON (`2expen51ve`). + +/// + +### Adicionar o roteador de callback + +Nesse ponto você tem a(s) *operação de rota de callback* necessária(s) (a(s) que o *desenvolvedor externo* deveria implementar na *API externa*) no roteador de callback que você criou acima. + +Agora use o parâmetro `callbacks` no decorador da *operação de rota de sua API* para passar o atributo `.routes` (que é na verdade apenas uma `list` de rotas/*operações de rota*) do roteador de callback que você criou acima: + +```Python hl_lines="35" +{!../../docs_src/openapi_callbacks/tutorial001.py!} +``` + +/// tip | Dica + +Perceba que você não está passando o roteador em si (`invoices_callback_router`) para `callback=`, mas o atributo `.routes`, como em `invoices_callback_router.routes`. + +/// + +### Verifique a documentação + +Agora você pode iniciar seu aplicativo e ir para http://127.0.0.1:8000/docs. + +Você verá sua documentação incluindo uma seção "Callbacks" para sua *operação de rota* que mostra como a *API externa* deveria ser: + + From 067ec21580e4aa81973a173cbc5c3158966cb2c5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 30 Oct 2024 19:54:20 +0000 Subject: [PATCH 254/932] =?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 4ff93b7bd..90fef213d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/openapi-callbacks.md`. PR [#12705](https://github.com/fastapi/fastapi/pull/12705) by [@devfernandoa](https://github.com/devfernandoa). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/request-files.md`. PR [#12706](https://github.com/fastapi/fastapi/pull/12706) by [@devluisrodrigues](https://github.com/devluisrodrigues). * 🌐 Add Portuguese Translation for `docs/pt/docs/advanced/custom-response.md`. PR [#12631](https://github.com/fastapi/fastapi/pull/12631) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/metadata.md`. PR [#12538](https://github.com/fastapi/fastapi/pull/12538) by [@LinkolnR](https://github.com/LinkolnR). From 3184b5c7011759fb573e331aa7a09a14cf089cc5 Mon Sep 17 00:00:00 2001 From: Luis Rodrigues <103431660+devluisrodrigues@users.noreply.github.com> Date: Wed, 30 Oct 2024 17:00:22 -0300 Subject: [PATCH 255/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/middleware.md`=20(#12704)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/middleware.md | 96 +++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 docs/pt/docs/advanced/middleware.md diff --git a/docs/pt/docs/advanced/middleware.md b/docs/pt/docs/advanced/middleware.md new file mode 100644 index 000000000..8167f7d27 --- /dev/null +++ b/docs/pt/docs/advanced/middleware.md @@ -0,0 +1,96 @@ +# Middleware Avançado + +No tutorial principal você leu como adicionar [Middleware Personalizado](../tutorial/middleware.md){.internal-link target=_blank} à sua aplicação. + +E então você também leu como lidar com [CORS com o `CORSMiddleware`](../tutorial/cors.md){.internal-link target=_blank}. + +Nesta seção, veremos como usar outros middlewares. + +## Adicionando middlewares ASGI + +Como o **FastAPI** é baseado no Starlette e implementa a especificação ASGI, você pode usar qualquer middleware ASGI. + +O middleware não precisa ser feito para o FastAPI ou Starlette para funcionar, desde que siga a especificação ASGI. + +No geral, os middlewares ASGI são classes que esperam receber um aplicativo ASGI como o primeiro argumento. + +Então, na documentação de middlewares ASGI de terceiros, eles provavelmente dirão para você fazer algo como: + +```Python +from unicorn import UnicornMiddleware + +app = SomeASGIApp() + +new_app = UnicornMiddleware(app, some_config="rainbow") +``` + +Mas, o FastAPI (na verdade, o Starlette) fornece uma maneira mais simples de fazer isso que garante que os middlewares internos lidem com erros do servidor e que os manipuladores de exceções personalizados funcionem corretamente. + +Para isso, você usa `app.add_middleware()` (como no exemplo para CORS). + +```Python +from fastapi import FastAPI +from unicorn import UnicornMiddleware + +app = FastAPI() + +app.add_middleware(UnicornMiddleware, some_config="rainbow") +``` + +`app.add_middleware()` recebe uma classe de middleware como o primeiro argumento e quaisquer argumentos adicionais a serem passados para o middleware. + +## Middlewares Integrados + +**FastAPI** inclui vários middlewares para casos de uso comuns, veremos a seguir como usá-los. + +/// note | Detalhes Técnicos + +Para o próximo exemplo, você também poderia usar `from starlette.middleware.something import SomethingMiddleware`. + +**FastAPI** fornece vários middlewares em `fastapi.middleware` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria dos middlewares disponíveis vem diretamente do Starlette. + +/// + +## `HTTPSRedirectMiddleware` + +Garante que todas as requisições devem ser `https` ou `wss`. + +Qualquer requisição para `http` ou `ws` será redirecionada para o esquema seguro. + +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} + +## `TrustedHostMiddleware` + +Garante que todas as requisições recebidas tenham um cabeçalho `Host` corretamente configurado, a fim de proteger contra ataques de cabeçalho de host HTTP. + +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} + +Os seguintes argumentos são suportados: + +* `allowed_hosts` - Uma lista de nomes de domínio que são permitidos como nomes de host. Domínios com coringa, como `*.example.com`, são suportados para corresponder a subdomínios. Para permitir qualquer nome de host, use `allowed_hosts=["*"]` ou omita o middleware. + +Se uma requisição recebida não for validada corretamente, uma resposta `400` será enviada. + +## `GZipMiddleware` + +Gerencia respostas GZip para qualquer requisição que inclua `"gzip"` no cabeçalho `Accept-Encoding`. + +O middleware lidará com respostas padrão e de streaming. + +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} + +Os seguintes argumentos são suportados: + +* `minimum_size` - Não comprima respostas menores que este tamanho mínimo em bytes. O padrão é `500`. +* `compresslevel` - Usado durante a compressão GZip. É um inteiro variando de 1 a 9. O padrão é `9`. Um valor menor resulta em uma compressão mais rápida, mas em arquivos maiores, enquanto um valor maior resulta em uma compressão mais lenta, mas em arquivos menores. + +## Outros middlewares + +Há muitos outros middlewares ASGI. + +Por exemplo: + +* Uvicorn's `ProxyHeadersMiddleware` +* MessagePack + +Para checar outros middlewares disponíveis, confira Documentação de Middlewares do Starlette e a Lista Incrível do ASGI. From e93b27452bb60bc0390516d433314372bf9d7fe8 Mon Sep 17 00:00:00 2001 From: namjimin_43 Date: Thu, 31 Oct 2024 05:00:57 +0900 Subject: [PATCH 256/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/advanced/response-directly.md`=20(#126?= =?UTF-8?q?74)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/advanced/response-directly.md | 67 ++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 docs/ko/docs/advanced/response-directly.md diff --git a/docs/ko/docs/advanced/response-directly.md b/docs/ko/docs/advanced/response-directly.md new file mode 100644 index 000000000..20389ff2a --- /dev/null +++ b/docs/ko/docs/advanced/response-directly.md @@ -0,0 +1,67 @@ +# 응답을 직접 반환하기 + +**FastAPI**에서 *경로 작업(path operation)*을 생성할 때, 일반적으로 `dict`, `list`, Pydantic 모델, 데이터베이스 모델 등의 데이터를 반환할 수 있습니다. + +기본적으로 **FastAPI**는 [JSON 호환 가능 인코더](../tutorial/encoder.md){.internal-link target=_blank}에 설명된 `jsonable_encoder`를 사용해 해당 반환 값을 자동으로 `JSON`으로 변환합니다. + +그런 다음, JSON 호환 데이터(예: `dict`)를 `JSONResponse`에 넣어 사용자의 응답을 전송하는 방식으로 처리됩니다. + +그러나 *경로 작업*에서 `JSONResponse`를 직접 반환할 수도 있습니다. + +예를 들어, 사용자 정의 헤더나 쿠키를 반환해야 하는 경우에 유용할 수 있습니다. + +## `Response` 반환하기 + +사실, `Response` 또는 그 하위 클래스를 반환할 수 있습니다. + +/// tip + +`JSONResponse` 자체도 `Response`의 하위 클래스입니다. + +/// + +그리고 `Response`를 반환하면 **FastAPI**가 이를 그대로 전달합니다. + +Pydantic 모델로 데이터 변환을 수행하지 않으며, 내용을 다른 형식으로 변환하지 않습니다. + +이로 인해 많은 유연성을 얻을 수 있습니다. 어떤 데이터 유형이든 반환할 수 있고, 데이터 선언이나 유효성 검사를 재정의할 수 있습니다. + +## `Response`에서 `jsonable_encoder` 사용하기 + +**FastAPI**는 반환하는 `Response`에 아무런 변환을 하지 않으므로, 그 내용이 준비되어 있어야 합니다. + +예를 들어, Pydantic 모델을 `dict`로 변환해 `JSONResponse`에 넣지 않으면 JSON 호환 유형으로 변환된 데이터 유형(예: `datetime`, `UUID` 등)이 사용되지 않습니다. + +이러한 경우, 데이터를 응답에 전달하기 전에 `jsonable_encoder`를 사용하여 변환할 수 있습니다: + +```Python hl_lines="6-7 21-22" +{!../../docs_src/response_directly/tutorial001.py!} +``` + +/// note | "기술적 세부 사항" + +`from starlette.responses import JSONResponse`를 사용할 수도 있습니다. + +**FastAPI**는 개발자의 편의를 위해 `starlette.responses`를 `fastapi.responses`로 제공합니다. 그러나 대부분의 가능한 응답은 Starlette에서 직접 제공합니다. + +/// + +## 사용자 정의 `Response` 반환하기 +위 예제는 필요한 모든 부분을 보여주지만, 아직 유용하지는 않습니다. 사실 데이터를 직접 반환하면 **FastAPI**가 이를 `JSONResponse`에 넣고 `dict`로 변환하는 등 모든 작업을 자동으로 처리합니다. + +이제, 사용자 정의 응답을 반환하는 방법을 알아보겠습니다. + +예를 들어 XML 응답을 반환하고 싶다고 가정해보겠습니다. + +XML 내용을 문자열에 넣고, 이를 `Response`에 넣어 반환할 수 있습니다: + +```Python hl_lines="1 18" +{!../../docs_src/response_directly/tutorial002.py!} +``` + +## 참고 사항 +`Response`를 직접 반환할 때, 그 데이터는 자동으로 유효성 검사되거나, 변환(직렬화)되거나, 문서화되지 않습니다. + +그러나 [OpenAPI에서 추가 응답](additional-responses.md){.internal-link target=_blank}에서 설명된 대로 문서화할 수 있습니다. + +이후 단락에서 자동 데이터 변환, 문서화 등을 사용하면서 사용자 정의 `Response`를 선언하는 방법을 확인할 수 있습니다. From 2f7a860ee04e6a98eb7005585c862422f228a12e Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 30 Oct 2024 20:02:34 +0000 Subject: [PATCH 257/932] =?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 90fef213d..b3035dbdd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/middleware.md`. PR [#12704](https://github.com/fastapi/fastapi/pull/12704) by [@devluisrodrigues](https://github.com/devluisrodrigues). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/openapi-callbacks.md`. PR [#12705](https://github.com/fastapi/fastapi/pull/12705) by [@devfernandoa](https://github.com/devfernandoa). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/request-files.md`. PR [#12706](https://github.com/fastapi/fastapi/pull/12706) by [@devluisrodrigues](https://github.com/devluisrodrigues). * 🌐 Add Portuguese Translation for `docs/pt/docs/advanced/custom-response.md`. PR [#12631](https://github.com/fastapi/fastapi/pull/12631) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). From bf838898448ae760cf4aae91066e29a24dee4548 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 30 Oct 2024 20:02:57 +0000 Subject: [PATCH 258/932] =?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 b3035dbdd..bd9d6476f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/advanced/response-directly.md`. PR [#12674](https://github.com/fastapi/fastapi/pull/12674) by [@9zimin9](https://github.com/9zimin9). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/middleware.md`. PR [#12704](https://github.com/fastapi/fastapi/pull/12704) by [@devluisrodrigues](https://github.com/devluisrodrigues). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/openapi-callbacks.md`. PR [#12705](https://github.com/fastapi/fastapi/pull/12705) by [@devfernandoa](https://github.com/devfernandoa). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/request-files.md`. PR [#12706](https://github.com/fastapi/fastapi/pull/12706) by [@devluisrodrigues](https://github.com/devluisrodrigues). From 05c8ed3312cd3a9993abebd1955c9be7887b0cfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 31 Oct 2024 10:13:26 +0100 Subject: [PATCH 259/932] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors:=20add?= =?UTF-8?q?=20Render=20(#12733)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + docs/en/data/sponsors.yml | 3 +++ docs/en/data/sponsors_badge.yml | 1 + docs/en/docs/deployment/cloud.md | 1 + docs/en/docs/img/sponsors/render-banner.svg | 25 +++++++++++++++++++++ docs/en/docs/img/sponsors/render.svg | 24 ++++++++++++++++++++ docs/en/overrides/main.html | 6 +++++ 7 files changed, 61 insertions(+) create mode 100644 docs/en/docs/img/sponsors/render-banner.svg create mode 100644 docs/en/docs/img/sponsors/render.svg diff --git a/README.md b/README.md index a12e740f7..62eeda03b 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ The key features are: + diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 6db9c509a..1c83579e2 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -29,6 +29,9 @@ gold: - url: https://liblab.com?utm_source=fastapi title: liblab - Generate SDKs from FastAPI img: https://fastapi.tiangolo.com/img/sponsors/liblab.png + - url: https://docs.render.com/deploy-fastapi?utm_source=deploydoc&utm_medium=referral&utm_campaign=fastapi + title: Deploy & scale any full-stack web app on Render. Focus on building apps, not infra. + img: https://fastapi.tiangolo.com/img/sponsors/render.svg silver: - url: https://github.com/deepset-ai/haystack/ title: Build powerful search from composable, open source building blocks diff --git a/docs/en/data/sponsors_badge.yml b/docs/en/data/sponsors_badge.yml index d45028aaa..7470b0238 100644 --- a/docs/en/data/sponsors_badge.yml +++ b/docs/en/data/sponsors_badge.yml @@ -31,3 +31,4 @@ logins: - zuplo-oss - Kong - speakeasy-api + - jess-render diff --git a/docs/en/docs/deployment/cloud.md b/docs/en/docs/deployment/cloud.md index 41ada859d..471808851 100644 --- a/docs/en/docs/deployment/cloud.md +++ b/docs/en/docs/deployment/cloud.md @@ -15,3 +15,4 @@ You might want to try their services and follow their guides: * Platform.sh * Porter * Coherence +* Render diff --git a/docs/en/docs/img/sponsors/render-banner.svg b/docs/en/docs/img/sponsors/render-banner.svg new file mode 100644 index 000000000..b8b1ed2e9 --- /dev/null +++ b/docs/en/docs/img/sponsors/render-banner.svg @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/en/docs/img/sponsors/render.svg b/docs/en/docs/img/sponsors/render.svg new file mode 100644 index 000000000..4a830482d --- /dev/null +++ b/docs/en/docs/img/sponsors/render.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 462907e7c..70a05831f 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -82,6 +82,12 @@
+ {% endblock %} From 086e3ca54b09d9e331cc0c60399be22856cbf69e Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 31 Oct 2024 09:13:53 +0000 Subject: [PATCH 260/932] =?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 bd9d6476f..9a5a7533f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -40,6 +40,7 @@ hide: ### Internal +* 🔧 Update sponsors: add Render. PR [#12733](https://github.com/fastapi/fastapi/pull/12733) by [@tiangolo](https://github.com/tiangolo). * ⬆ [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 From bb7921be252b5fa95162ccbcb6c4fff8af1f8153 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=ADdia?= Date: Thu, 31 Oct 2024 09:17:45 -0300 Subject: [PATCH 261/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/security/simple-oauth2.md?= =?UTF-8?q?`=20(#12520)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/tutorial/security/simple-oauth2.md | 539 ++++++++++++++++++ 1 file changed, 539 insertions(+) create mode 100644 docs/pt/docs/tutorial/security/simple-oauth2.md diff --git a/docs/pt/docs/tutorial/security/simple-oauth2.md b/docs/pt/docs/tutorial/security/simple-oauth2.md new file mode 100644 index 000000000..4e55f8c25 --- /dev/null +++ b/docs/pt/docs/tutorial/security/simple-oauth2.md @@ -0,0 +1,539 @@ +# Simples OAuth2 com senha e Bearer + +Agora vamos construir a partir do capítulo anterior e adicionar as partes que faltam para ter um fluxo de segurança completo. + +## Pegue o `username` (nome de usuário) e `password` (senha) + +É utilizado o utils de segurança da **FastAPI** para obter o `username` e a `password`. + +OAuth2 especifica que ao usar o "password flow" (fluxo de senha), que estamos usando, o cliente/usuário deve enviar os campos `username` e `password` como dados do formulário. + +E a especificação diz que os campos devem ser nomeados assim. Portanto, `user-name` ou `email` não funcionariam. + +Mas não se preocupe, você pode mostrá-lo como quiser aos usuários finais no frontend. + +E seus modelos de banco de dados podem usar qualquer outro nome que você desejar. + +Mas para a *operação de rota* de login, precisamos usar esses nomes para serem compatíveis com a especificação (e poder, por exemplo, usar o sistema integrado de documentação da API). + +A especificação também afirma que o `username` e a `password` devem ser enviados como dados de formulário (portanto, não há JSON aqui). + +### `scope` + +A especificação também diz que o cliente pode enviar outro campo de formulário "`scope`" (Escopo). + +O nome do campo do formulário é `scope` (no singular), mas na verdade é uma longa string com "escopos" separados por espaços. + +Cada “scope” é apenas uma string (sem espaços). + +Normalmente são usados para declarar permissões de segurança específicas, por exemplo: + +* `users:read` ou `users:write` são exemplos comuns. +* `instagram_basic` é usado pelo Facebook e Instagram. +* `https://www.googleapis.com/auth/drive` é usado pelo Google. + +/// info | Informação + +No OAuth2, um "scope" é apenas uma string que declara uma permissão específica necessária. + +Não importa se tem outros caracteres como `:` ou se é uma URL. + +Esses detalhes são específicos da implementação. + +Para OAuth2 são apenas strings. + +/// + +## Código para conseguir o `username` e a `password` + +Agora vamos usar os utilitários fornecidos pelo **FastAPI** para lidar com isso. + +### `OAuth2PasswordRequestForm` + +Primeiro, importe `OAuth2PasswordRequestForm` e use-o como uma dependência com `Depends` na *operação de rota* para `/token`: + +//// tab | Python 3.10+ + +```Python hl_lines="4 78" +{!> ../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="4 78" +{!> ../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="4 79" +{!> ../../docs_src/security/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="2 74" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="4 76" +{!> ../../docs_src/security/tutorial003.py!} +``` + +//// + +`OAuth2PasswordRequestForm` é uma dependência de classe que declara um corpo de formulário com: + +* O `username`. +* A `password`. +* Um campo `scope` opcional como uma string grande, composta de strings separadas por espaços. +* Um `grant_type` (tipo de concessão) opcional. + +/// tip | Dica + +A especificação OAuth2 na verdade *requer* um campo `grant_type` com um valor fixo de `password`, mas `OAuth2PasswordRequestForm` não o impõe. + +Se você precisar aplicá-lo, use `OAuth2PasswordRequestFormStrict` em vez de `OAuth2PasswordRequestForm`. + +/// + +* Um `client_id` opcional (não precisamos dele em nosso exemplo). +* Um `client_secret` opcional (não precisamos dele em nosso exemplo). + +/// info | Informação + +O `OAuth2PasswordRequestForm` não é uma classe especial para **FastAPI** como é `OAuth2PasswordBearer`. + +`OAuth2PasswordBearer` faz com que **FastAPI** saiba que é um esquema de segurança. Portanto, é adicionado dessa forma ao OpenAPI. + +Mas `OAuth2PasswordRequestForm` é apenas uma dependência de classe que você mesmo poderia ter escrito ou poderia ter declarado os parâmetros do `Form` (formulário) diretamente. + +Mas como é um caso de uso comum, ele é fornecido diretamente pelo **FastAPI**, apenas para facilitar. + +/// + +### Use os dados do formulário + +/// tip | Dica + +A instância da classe de dependência `OAuth2PasswordRequestForm` não terá um atributo `scope` com a string longa separada por espaços, em vez disso, terá um atributo `scopes` com a lista real de strings para cada escopo enviado. + +Não estamos usando `scopes` neste exemplo, mas a funcionalidade está disponível se você precisar. + +/// + +Agora, obtenha os dados do usuário do banco de dados (falso), usando o `username` do campo do formulário. + +Se não existir tal usuário, retornaremos um erro dizendo "Incorrect username or password" (Nome de usuário ou senha incorretos). + +Para o erro, usamos a exceção `HTTPException`: + +//// tab | Python 3.10+ + +```Python hl_lines="3 79-81" +{!> ../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="3 79-81" +{!> ../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="3 80-82" +{!> ../../docs_src/security/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="1 75-77" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="3 77-79" +{!> ../../docs_src/security/tutorial003.py!} +``` + +//// + +### Confira a password (senha) + +Neste ponto temos os dados do usuário do nosso banco de dados, mas não verificamos a senha. + +Vamos colocar esses dados primeiro no modelo `UserInDB` do Pydantic. + +Você nunca deve salvar senhas em texto simples, portanto, usaremos o sistema de hashing de senhas (falsas). + +Se as senhas não corresponderem, retornaremos o mesmo erro. + +#### Hashing de senha + +"Hashing" significa: converter algum conteúdo (uma senha neste caso) em uma sequência de bytes (apenas uma string) que parece algo sem sentido. + +Sempre que você passa exatamente o mesmo conteúdo (exatamente a mesma senha), você obtém exatamente a mesma sequência aleatória de caracteres. + +Mas você não pode converter a sequência aleatória de caracteres de volta para a senha. + +##### Porque usar hashing de senha + +Se o seu banco de dados for roubado, o ladrão não terá as senhas em texto simples dos seus usuários, apenas os hashes. + +Assim, o ladrão não poderá tentar usar essas mesmas senhas em outro sistema (como muitos usuários usam a mesma senha em todos os lugares, isso seria perigoso). + +//// tab | Python 3.10+ + +```Python hl_lines="82-85" +{!> ../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="82-85" +{!> ../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="83-86" +{!> ../../docs_src/security/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="78-81" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="80-83" +{!> ../../docs_src/security/tutorial003.py!} +``` + +//// + +#### Sobre `**user_dict` + +`UserInDB(**user_dict)` significa: + +*Passe as keys (chaves) e values (valores) de `user_dict` diretamente como argumentos de valor-chave, equivalente a:* + +```Python +UserInDB( + username = user_dict["username"], + email = user_dict["email"], + full_name = user_dict["full_name"], + disabled = user_dict["disabled"], + hashed_password = user_dict["hashed_password"], +) +``` + +/// info | Informação + +Para uma explicação mais completa de `**user_dict`, verifique [a documentação para **Extra Models**](../extra-models.md#about-user_indict){.internal-link target=_blank}. + +/// + +## Retorne o token + +A resposta do endpoint `token` deve ser um objeto JSON. + +Deve ter um `token_type`. No nosso caso, como estamos usando tokens "Bearer", o tipo de token deve ser "`bearer`". + +E deve ter um `access_token`, com uma string contendo nosso token de acesso. + +Para este exemplo simples, seremos completamente inseguros e retornaremos o mesmo `username` do token. + +/// tip | Dica + +No próximo capítulo, você verá uma implementação realmente segura, com hash de senha e tokens JWT. + +Mas, por enquanto, vamos nos concentrar nos detalhes específicos de que precisamos. + +/// + +//// tab | Python 3.10+ + +```Python hl_lines="87" +{!> ../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="87" +{!> ../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="88" +{!> ../../docs_src/security/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="83" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="85" +{!> ../../docs_src/security/tutorial003.py!} +``` + +//// + +/// tip | Dica + +Pela especificação, você deve retornar um JSON com um `access_token` e um `token_type`, o mesmo que neste exemplo. + +Isso é algo que você mesmo deve fazer em seu código e certifique-se de usar essas chaves JSON. + +É quase a única coisa que você deve se lembrar de fazer corretamente, para estar em conformidade com as especificações. + +De resto, **FastAPI** cuida disso para você. + +/// + +## Atualize as dependências + +Agora vamos atualizar nossas dependências. + +Queremos obter o `user_user` *somente* se este usuário estiver ativo. + +Portanto, criamos uma dependência adicional `get_current_active_user` que por sua vez usa `get_current_user` como dependência. + +Ambas as dependências retornarão apenas um erro HTTP se o usuário não existir ou se estiver inativo. + +Portanto, em nosso endpoint, só obteremos um usuário se o usuário existir, tiver sido autenticado corretamente e estiver ativo: + +//// tab | Python 3.10+ + +```Python hl_lines="58-66 69-74 94" +{!> ../../docs_src/security/tutorial003_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="58-66 69-74 94" +{!> ../../docs_src/security/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="59-67 70-75 95" +{!> ../../docs_src/security/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="56-64 67-70 88" +{!> ../../docs_src/security/tutorial003_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated`, se possível. + +/// + +```Python hl_lines="58-66 69-72 90" +{!> ../../docs_src/security/tutorial003.py!} +``` + +//// + +/// info | Informação + +O cabeçalho adicional `WWW-Authenticate` com valor `Bearer` que estamos retornando aqui também faz parte da especificação. + +Qualquer código de status HTTP (erro) 401 "UNAUTHORIZED" também deve retornar um cabeçalho `WWW-Authenticate`. + +No caso de tokens ao portador (nosso caso), o valor desse cabeçalho deve ser `Bearer`. + +Na verdade, você pode pular esse cabeçalho extra e ainda funcionaria. + +Mas é fornecido aqui para estar em conformidade com as especificações. + +Além disso, pode haver ferramentas que esperam e usam isso (agora ou no futuro) e que podem ser úteis para você ou seus usuários, agora ou no futuro. + +Esse é o benefício dos padrões... + +/// + +## Veja em ação + +Abra o docs interativo: http://127.0.0.1:8000/docs. + +### Autenticação + +Clique no botão "Authorize". + +Use as credenciais: + +User: `johndoe` + +Password: `secret` + + + +Após autenticar no sistema, você verá assim: + + + +### Obtenha seus próprios dados de usuário + +Agora use a operação `GET` com o caminho `/users/me`. + +Você obterá os dados do seu usuário, como: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false, + "hashed_password": "fakehashedsecret" +} +``` + + + +Se você clicar no ícone de cadeado, sair e tentar a mesma operação novamente, receberá um erro HTTP 401 de: + +```JSON +{ + "detail": "Not authenticated" +} +``` + +### Usuário inativo + +Agora tente com um usuário inativo, autentique-se com: + +User: `alice` + +Password: `secret2` + +E tente usar a operação `GET` com o caminho `/users/me`. + +Você receberá um erro "Usuário inativo", como: + +```JSON +{ + "detail": "Inactive user" +} +``` + +## Recaptulando + +Agora você tem as ferramentas para implementar um sistema de segurança completo baseado em `username` e `password` para sua API. + +Usando essas ferramentas, você pode tornar o sistema de segurança compatível com qualquer banco de dados e com qualquer usuário ou modelo de dados. + +O único detalhe que falta é que ainda não é realmente "seguro". + +No próximo capítulo você verá como usar uma biblioteca de hashing de senha segura e tokens JWT. From 868720a7986b72e08c66cf4a695a48844bf0625a Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 31 Oct 2024 12:18:10 +0000 Subject: [PATCH 262/932] =?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 9a5a7533f..6574f7de6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/simple-oauth2.md`. PR [#12520](https://github.com/fastapi/fastapi/pull/12520) by [@LidiaDomingos](https://github.com/LidiaDomingos). * 🌐 Add Korean translation for `docs/ko/docs/advanced/response-directly.md`. PR [#12674](https://github.com/fastapi/fastapi/pull/12674) by [@9zimin9](https://github.com/9zimin9). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/middleware.md`. PR [#12704](https://github.com/fastapi/fastapi/pull/12704) by [@devluisrodrigues](https://github.com/devluisrodrigues). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/openapi-callbacks.md`. PR [#12705](https://github.com/fastapi/fastapi/pull/12705) by [@devfernandoa](https://github.com/devfernandoa). From b7102a267598354faa01aef63b96f03c49af025d Mon Sep 17 00:00:00 2001 From: Fernando Alzueta Date: Thu, 31 Oct 2024 09:20:59 -0300 Subject: [PATCH 263/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/websockets.md`=20(#12703)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/websockets.md | 188 ++++++++++++++++++++++++++++ 1 file changed, 188 insertions(+) create mode 100644 docs/pt/docs/advanced/websockets.md diff --git a/docs/pt/docs/advanced/websockets.md b/docs/pt/docs/advanced/websockets.md new file mode 100644 index 000000000..694f2bb5d --- /dev/null +++ b/docs/pt/docs/advanced/websockets.md @@ -0,0 +1,188 @@ +# WebSockets + +Você pode usar WebSockets com **FastAPI**. + +## Instalando `WebSockets` + +Garanta que você criou um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, o ativou e instalou o `websockets`: + +
+ +```console +$ pip install websockets + +---> 100% +``` + +
+ +## Cliente WebSockets + +### Em produção + +Em seu sistema de produção, você provavelmente tem um frontend criado com um framework moderno como React, Vue.js ou Angular. + +E para comunicar usando WebSockets com seu backend, você provavelmente usaria as utilidades do seu frontend. + +Ou você pode ter um aplicativo móvel nativo que se comunica diretamente com seu backend WebSocket, em código nativo. + +Ou você pode ter qualquer outra forma de comunicar com o endpoint WebSocket. + +--- + +Mas para este exemplo, usaremos um documento HTML muito simples com algum JavaScript, tudo dentro de uma string longa. + +Esse, é claro, não é o ideal e você não o usaria para produção. + +Na produção, você teria uma das opções acima. + +Mas é a maneira mais simples de focar no lado do servidor de WebSockets e ter um exemplo funcional: + +```Python hl_lines="2 6-38 41-43" +{!../../docs_src/websockets/tutorial001.py!} +``` + +## Criando um `websocket` + +Em sua aplicação **FastAPI**, crie um `websocket`: + +{*../../docs_src/websockets/tutorial001.py hl[46:47]*} + +/// note | Detalhes Técnicos + +Você também poderia usar `from starlette.websockets import WebSocket`. + +A **FastAPI** fornece o mesmo `WebSocket` diretamente apenas como uma conveniência para você, o desenvolvedor. Mas ele vem diretamente do Starlette. + +/// + +## Aguardar por mensagens e enviar mensagens + +Em sua rota WebSocket você pode esperar (`await`) por mensagens e enviar mensagens. + +{*../../docs_src/websockets/tutorial001.py hl[48:52]*} + +Você pode receber e enviar dados binários, de texto e JSON. + +## Tente você mesmo + +Se seu arquivo for nomeado `main.py`, execute sua aplicação com: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Abra seu navegador em: http://127.0.0.1:8000. + +Você verá uma página simples como: + + + +Você pode digitar mensagens na caixa de entrada e enviá-las: + + + +E sua aplicação **FastAPI** com WebSockets responderá de volta: + + + +Você pode enviar (e receber) muitas mensagens: + + + +E todas elas usarão a mesma conexão WebSocket. + +## Usando `Depends` e outros + +Nos endpoints WebSocket você pode importar do `fastapi` e usar: + +* `Depends` +* `Security` +* `Cookie` +* `Header` +* `Path` +* `Query` + +Eles funcionam da mesma forma que para outros endpoints FastAPI/*operações de rota*: + +{*../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82]*} + +/// info | Informação + +Como isso é um WebSocket, não faz muito sentido levantar uma `HTTPException`, em vez disso levantamos uma `WebSocketException`. + +Você pode usar um código de fechamento dos códigos válidos definidos na especificação. + +/// + +### Tente os WebSockets com dependências + +Se seu arquivo for nomeado `main.py`, execute sua aplicação com: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Abrar seu browser em: http://127.0.0.1:8000. + +Lá você pode definir: + +* O "Item ID", usado na rota. +* O "Token" usado como um parâmetro de consulta. + +/// tip | Dica + +Perceba que a consulta `token` será manipulada por uma dependência. + +/// + +Com isso você pode conectar o WebSocket e então enviar e receber mensagens: + + + +## Lidando com desconexões e múltiplos clientes + +Quando uma conexão WebSocket é fechada, o `await websocket.receive_text()` levantará uma exceção `WebSocketDisconnect`, que você pode então capturar e lidar como neste exemplo. + +{*../../docs_src/websockets/tutorial003_py39.py hl[79:81]*} + +Para testar: + +* Abrar o aplicativo com várias abas do navegador. +* Escreva mensagens a partir delas. +* Então feche uma das abas. + +Isso levantará a exceção `WebSocketDisconnect`, e todos os outros clientes receberão uma mensagem como: + +``` +Client #1596980209979 left the chat +``` + +/// tip | Dica + +O app acima é um exemplo mínimo e simples para demonstrar como lidar e transmitir mensagens para várias conexões WebSocket. + +Mas tenha em mente que, como tudo é manipulado na memória, em uma única lista, ele só funcionará enquanto o processo estiver em execução e só funcionará com um único processo. + +Se você precisa de algo fácil de integrar com o FastAPI, mas que seja mais robusto, suportado por Redis, PostgreSQL ou outros, verifique o encode/broadcaster. + +/// + +## Mais informações + +Para aprender mais sobre as opções, verifique a documentação do Starlette para: + +* A classe `WebSocket`. +* Manipulação de WebSockets baseada em classes. From 42c002e4ec62cf319d932bae8b229294c1c124f5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 31 Oct 2024 12:21:22 +0000 Subject: [PATCH 264/932] =?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 6574f7de6..85aa085ad 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/websockets.md`. PR [#12703](https://github.com/fastapi/fastapi/pull/12703) by [@devfernandoa](https://github.com/devfernandoa). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/simple-oauth2.md`. PR [#12520](https://github.com/fastapi/fastapi/pull/12520) by [@LidiaDomingos](https://github.com/LidiaDomingos). * 🌐 Add Korean translation for `docs/ko/docs/advanced/response-directly.md`. PR [#12674](https://github.com/fastapi/fastapi/pull/12674) by [@9zimin9](https://github.com/9zimin9). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/middleware.md`. PR [#12704](https://github.com/fastapi/fastapi/pull/12704) by [@devluisrodrigues](https://github.com/devluisrodrigues). From 14b087cd36792f04d34419c6d29b832a62303aa9 Mon Sep 17 00:00:00 2001 From: Chol_rang Date: Fri, 1 Nov 2024 03:56:37 +0900 Subject: [PATCH 265/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/advanced/wsgi.md`=20(#12659)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/advanced/wsgi.md | 37 +++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 docs/ko/docs/advanced/wsgi.md diff --git a/docs/ko/docs/advanced/wsgi.md b/docs/ko/docs/advanced/wsgi.md new file mode 100644 index 000000000..87aabf203 --- /dev/null +++ b/docs/ko/docs/advanced/wsgi.md @@ -0,0 +1,37 @@ +# WSGI 포함하기 - Flask, Django 그 외 + +[서브 응용 프로그램 - 마운트](sub-applications.md){.internal-link target=_blank}, [프록시 뒤편에서](behind-a-proxy.md){.internal-link target=_blank}에서 보았듯이 WSGI 응용 프로그램들을 다음과 같이 마운트 할 수 있습니다. + +`WSGIMiddleware`를 사용하여 WSGI 응용 프로그램(예: Flask, Django 등)을 감쌀 수 있습니다. + +## `WSGIMiddleware` 사용하기 + +`WSGIMiddleware`를 불러와야 합니다. + +그런 다음, WSGI(예: Flask) 응용 프로그램을 미들웨어로 포장합니다. + +그 후, 해당 경로에 마운트합니다. + +```Python hl_lines="2-3 23" +{!../../docs_src/wsgi/tutorial001.py!} +``` + +## 확인하기 + +이제 `/v1/` 경로에 있는 모든 요청은 Flask 응용 프로그램에서 처리됩니다. + +그리고 나머지는 **FastAPI**에 의해 처리됩니다. + +실행하면 http://localhost:8000/v1/으로 이동해서 Flask의 응답을 볼 수 있습니다: + +```txt +Hello, World from Flask! +``` + +그리고 다음으로 이동하면 http://localhost:8000/v2 Flask의 응답을 볼 수 있습니다: + +```JSON +{ + "message": "Hello World" +} +``` From a18ab763223ef19c1b00d3838e5b087d22dc81c7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 31 Oct 2024 18:56:59 +0000 Subject: [PATCH 266/932] =?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 85aa085ad..590e4423b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/advanced/wsgi.md`. PR [#12659](https://github.com/fastapi/fastapi/pull/12659) by [@Limsunoh](https://github.com/Limsunoh). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/websockets.md`. PR [#12703](https://github.com/fastapi/fastapi/pull/12703) by [@devfernandoa](https://github.com/devfernandoa). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/simple-oauth2.md`. PR [#12520](https://github.com/fastapi/fastapi/pull/12520) by [@LidiaDomingos](https://github.com/LidiaDomingos). * 🌐 Add Korean translation for `docs/ko/docs/advanced/response-directly.md`. PR [#12674](https://github.com/fastapi/fastapi/pull/12674) by [@9zimin9](https://github.com/9zimin9). From 808196f2a36ba94a9b1ac315b8d426175cbe2d38 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 1 Nov 2024 11:16:34 +0000 Subject: [PATCH 267/932] =?UTF-8?q?=E2=AC=86=20Update=20pytest=20requireme?= =?UTF-8?q?nt=20from=20<8.0.0,>=3D7.1.3=20to=20>=3D7.1.3,<9.0.0=20(#12745)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Updates the requirements on [pytest](https://github.com/pytest-dev/pytest) to permit the latest version. - [Release notes](https://github.com/pytest-dev/pytest/releases) - [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst) - [Commits](https://github.com/pytest-dev/pytest/compare/7.1.3...8.3.3) --- updated-dependencies: - dependency-name: pytest dependency-type: direct:production ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-tests.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-tests.txt b/requirements-tests.txt index 189fcaf7e..f8c860ee8 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -1,6 +1,6 @@ -e .[all] -r requirements-docs-tests.txt -pytest >=7.1.3,<8.0.0 +pytest >=7.1.3,<9.0.0 coverage[toml] >= 6.5.0,< 8.0 mypy ==1.8.0 dirty-equals ==0.6.0 From 4695b8d07f4e8c07349716a957b31f6235cbda65 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 1 Nov 2024 11:16:55 +0000 Subject: [PATCH 268/932] =?UTF-8?q?=E2=AC=86=20Bump=20pillow=20from=2010.4?= =?UTF-8?q?.0=20to=2011.0.0=20(#12746)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pillow](https://github.com/python-pillow/Pillow) from 10.4.0 to 11.0.0. - [Release notes](https://github.com/python-pillow/Pillow/releases) - [Changelog](https://github.com/python-pillow/Pillow/blob/main/CHANGES.rst) - [Commits](https://github.com/python-pillow/Pillow/compare/10.4.0...11.0.0) --- updated-dependencies: - dependency-name: pillow dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs.txt b/requirements-docs.txt index 1639159af..6f2fa3ee7 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -8,7 +8,7 @@ pyyaml >=5.3.1,<7.0.0 # For Material for MkDocs, Chinese search jieba==0.42.1 # For image processing by Material for MkDocs -pillow==10.4.0 +pillow==11.0.0 # For image processing by Material for MkDocs cairosvg==2.7.1 mkdocstrings[python]==0.26.1 From c4a2201a6bd3816730ac07c35c99df36c61de713 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 1 Nov 2024 11:16:58 +0000 Subject: [PATCH 269/932] =?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 590e4423b..6b9a50502 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Internal +* ⬆ Update pytest requirement from <8.0.0,>=7.1.3 to >=7.1.3,<9.0.0. PR [#12745](https://github.com/fastapi/fastapi/pull/12745) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Update sponsors: add Render. PR [#12733](https://github.com/fastapi/fastapi/pull/12733) by [@tiangolo](https://github.com/tiangolo). * ⬆ [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). From fd98edcdd5325f8a5acc0ffc2edd4d9bd548a60b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 1 Nov 2024 11:17:12 +0000 Subject: [PATCH 270/932] =?UTF-8?q?=E2=AC=86=20Update=20flask=20requiremen?= =?UTF-8?q?t=20from=20<3.0.0,>=3D1.1.2=20to=20>=3D1.1.2,<4.0.0=20(#12747)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Updates the requirements on [flask](https://github.com/pallets/flask) to permit the latest version. - [Release notes](https://github.com/pallets/flask/releases) - [Changelog](https://github.com/pallets/flask/blob/main/CHANGES.rst) - [Commits](https://github.com/pallets/flask/compare/1.1.2...3.0.3) --- updated-dependencies: - dependency-name: flask dependency-type: direct:production ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-tests.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-tests.txt b/requirements-tests.txt index f8c860ee8..95ec09884 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -5,7 +5,7 @@ coverage[toml] >= 6.5.0,< 8.0 mypy ==1.8.0 dirty-equals ==0.6.0 sqlmodel==0.0.22 -flask >=1.1.2,<3.0.0 +flask >=1.1.2,<4.0.0 anyio[trio] >=3.2.1,<4.0.0 PyJWT==2.8.0 pyyaml >=5.3.1,<7.0.0 From 54fa592dacfe33bc788d289a1fb3db8f3a84e0f9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 1 Nov 2024 11:17:22 +0000 Subject: [PATCH 271/932] =?UTF-8?q?=E2=AC=86=20Bump=20typer=20from=200.12.?= =?UTF-8?q?3=20to=200.12.5=20(#12748)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [typer](https://github.com/fastapi/typer) from 0.12.3 to 0.12.5. - [Release notes](https://github.com/fastapi/typer/releases) - [Changelog](https://github.com/fastapi/typer/blob/master/docs/release-notes.md) - [Commits](https://github.com/fastapi/typer/compare/0.12.3...0.12.5) --- updated-dependencies: - dependency-name: typer dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs.txt b/requirements-docs.txt index 6f2fa3ee7..9754eaa4a 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -3,7 +3,7 @@ mkdocs-material==9.5.18 mdx-include >=1.4.1,<2.0.0 mkdocs-redirects>=1.2.1,<1.3.0 -typer == 0.12.3 +typer == 0.12.5 pyyaml >=5.3.1,<7.0.0 # For Material for MkDocs, Chinese search jieba==0.42.1 From 70f50442d95fdb73c61b676fb46fc9ed594e66ee Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 1 Nov 2024 11:17:26 +0000 Subject: [PATCH 272/932] =?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 6b9a50502..a241e0d2a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Internal +* ⬆ Bump pillow from 10.4.0 to 11.0.0. PR [#12746](https://github.com/fastapi/fastapi/pull/12746) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Update pytest requirement from <8.0.0,>=7.1.3 to >=7.1.3,<9.0.0. PR [#12745](https://github.com/fastapi/fastapi/pull/12745) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Update sponsors: add Render. PR [#12733](https://github.com/fastapi/fastapi/pull/12733) by [@tiangolo](https://github.com/tiangolo). * ⬆ [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). From fd40d00748d1781b2a53bba79f9241144f9a4765 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 1 Nov 2024 11:17:36 +0000 Subject: [PATCH 273/932] =?UTF-8?q?=E2=AC=86=20Update=20pre-commit=20requi?= =?UTF-8?q?rement=20from=20<4.0.0,>=3D2.17.0=20to=20>=3D2.17.0,<5.0.0=20(#?= =?UTF-8?q?12749)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Updates the requirements on [pre-commit](https://github.com/pre-commit/pre-commit) to permit the latest version. - [Release notes](https://github.com/pre-commit/pre-commit/releases) - [Changelog](https://github.com/pre-commit/pre-commit/blob/main/CHANGELOG.md) - [Commits](https://github.com/pre-commit/pre-commit/compare/v2.17.0...v4.0.1) --- updated-dependencies: - dependency-name: pre-commit dependency-type: direct:production ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 8e1fef341..9180bf1be 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,6 @@ -e .[all] -r requirements-tests.txt -r requirements-docs.txt -pre-commit >=2.17.0,<4.0.0 +pre-commit >=2.17.0,<5.0.0 # For generating screenshots playwright From 6670e8af6851563265f61cae8196a902711b4130 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 1 Nov 2024 11:18:59 +0000 Subject: [PATCH 274/932] =?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 a241e0d2a..893185808 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Internal +* ⬆ Update flask requirement from <3.0.0,>=1.1.2 to >=1.1.2,<4.0.0. PR [#12747](https://github.com/fastapi/fastapi/pull/12747) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pillow from 10.4.0 to 11.0.0. PR [#12746](https://github.com/fastapi/fastapi/pull/12746) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Update pytest requirement from <8.0.0,>=7.1.3 to >=7.1.3,<9.0.0. PR [#12745](https://github.com/fastapi/fastapi/pull/12745) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Update sponsors: add Render. PR [#12733](https://github.com/fastapi/fastapi/pull/12733) by [@tiangolo](https://github.com/tiangolo). From 1f150346388e7f94fc1499d0f70ac847f0463087 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 1 Nov 2024 11:19:50 +0000 Subject: [PATCH 275/932] =?UTF-8?q?=E2=AC=86=20Bump=20pypa/gh-action-pypi-?= =?UTF-8?q?publish=20from=201.10.3=20to=201.11.0=20(#12721)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.10.3 to 1.11.0. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.10.3...v1.11.0) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index c8ea4e18c..694d68c69 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -35,7 +35,7 @@ jobs: TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.10.3 + uses: pypa/gh-action-pypi-publish@v1.11.0 - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} From eba967c65acdccfa19b2e6633f96b59e4024d412 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 1 Nov 2024 11:20:24 +0000 Subject: [PATCH 276/932] =?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 893185808..64f563ef4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Internal +* ⬆ Bump typer from 0.12.3 to 0.12.5. PR [#12748](https://github.com/fastapi/fastapi/pull/12748) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Update flask requirement from <3.0.0,>=1.1.2 to >=1.1.2,<4.0.0. PR [#12747](https://github.com/fastapi/fastapi/pull/12747) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pillow from 10.4.0 to 11.0.0. PR [#12746](https://github.com/fastapi/fastapi/pull/12746) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Update pytest requirement from <8.0.0,>=7.1.3 to >=7.1.3,<9.0.0. PR [#12745](https://github.com/fastapi/fastapi/pull/12745) by [@dependabot[bot]](https://github.com/apps/dependabot). From 3739999b7650997366e9b63b223170d9e08c9e41 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 1 Nov 2024 11:21:54 +0000 Subject: [PATCH 277/932] =?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 64f563ef4..4822a9cc7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Internal +* ⬆ Update pre-commit requirement from <4.0.0,>=2.17.0 to >=2.17.0,<5.0.0. PR [#12749](https://github.com/fastapi/fastapi/pull/12749) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump typer from 0.12.3 to 0.12.5. PR [#12748](https://github.com/fastapi/fastapi/pull/12748) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Update flask requirement from <3.0.0,>=1.1.2 to >=1.1.2,<4.0.0. PR [#12747](https://github.com/fastapi/fastapi/pull/12747) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pillow from 10.4.0 to 11.0.0. PR [#12746](https://github.com/fastapi/fastapi/pull/12746) by [@dependabot[bot]](https://github.com/apps/dependabot). From d4ab06a2b6b59bd264c0cc43367c5a68174e8f88 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 1 Nov 2024 11:25:57 +0000 Subject: [PATCH 278/932] =?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 4822a9cc7..d072c618d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Internal +* ⬆ Bump pypa/gh-action-pypi-publish from 1.10.3 to 1.11.0. PR [#12721](https://github.com/fastapi/fastapi/pull/12721) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Update pre-commit requirement from <4.0.0,>=2.17.0 to >=2.17.0,<5.0.0. PR [#12749](https://github.com/fastapi/fastapi/pull/12749) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump typer from 0.12.3 to 0.12.5. PR [#12748](https://github.com/fastapi/fastapi/pull/12748) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Update flask requirement from <3.0.0,>=1.1.2 to >=1.1.2,<4.0.0. PR [#12747](https://github.com/fastapi/fastapi/pull/12747) by [@dependabot[bot]](https://github.com/apps/dependabot). From 3ff4da5387912b9b6cbaf5f5e46c57999a37ff19 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 6 Nov 2024 18:14:55 +0000 Subject: [PATCH 279/932] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#12766)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/astral-sh/ruff-pre-commit: v0.7.1 → v0.7.2](https://github.com/astral-sh/ruff-pre-commit/compare/v0.7.1...v0.7.2) Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 84bec0421..d90e7281e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.7.1 + rev: v0.7.2 hooks: - id: ruff args: From 7eda7e28a694066c8e55fd3c7beb537af55bcc39 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 6 Nov 2024 18:15:12 +0000 Subject: [PATCH 280/932] =?UTF-8?q?=E2=AC=86=20Bump=20cloudflare/wrangler-?= =?UTF-8?q?action=20from=203.11=20to=203.12=20(#12777)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [cloudflare/wrangler-action](https://github.com/cloudflare/wrangler-action) from 3.11 to 3.12. - [Release notes](https://github.com/cloudflare/wrangler-action/releases) - [Changelog](https://github.com/cloudflare/wrangler-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/cloudflare/wrangler-action/compare/v3.11...v3.12) --- updated-dependencies: - dependency-name: cloudflare/wrangler-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/deploy-docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index e46786a53..387063f12 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -64,7 +64,7 @@ jobs: BRANCH: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} # TODO: Use v3 when it's fixed, probably in v3.11 # https://github.com/cloudflare/wrangler-action/issues/307 - uses: cloudflare/wrangler-action@v3.11 + uses: cloudflare/wrangler-action@v3.12 # uses: cloudflare/wrangler-action@v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} From 4d3e1cd22aaea9fdcccd276479a4997fd361d702 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 6 Nov 2024 18:15:17 +0000 Subject: [PATCH 281/932] =?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 d072c618d..8c1723d2e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Internal +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12766](https://github.com/fastapi/fastapi/pull/12766) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * ⬆ Bump pypa/gh-action-pypi-publish from 1.10.3 to 1.11.0. PR [#12721](https://github.com/fastapi/fastapi/pull/12721) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Update pre-commit requirement from <4.0.0,>=2.17.0 to >=2.17.0,<5.0.0. PR [#12749](https://github.com/fastapi/fastapi/pull/12749) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump typer from 0.12.3 to 0.12.5. PR [#12748](https://github.com/fastapi/fastapi/pull/12748) by [@dependabot[bot]](https://github.com/apps/dependabot). From c8bcb633ccaadbfe3b1c18568476aa1dd3cd7a96 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 6 Nov 2024 18:15:30 +0000 Subject: [PATCH 282/932] =?UTF-8?q?=E2=AC=86=20Bump=20pypa/gh-action-pypi-?= =?UTF-8?q?publish=20from=201.11.0=20to=201.12.0=20(#12781)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.11.0 to 1.12.0. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.11.0...v1.12.0) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 694d68c69..a26d2d563 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -35,7 +35,7 @@ jobs: TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.11.0 + uses: pypa/gh-action-pypi-publish@v1.12.0 - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} From 45579ad78c08909b1d46fe31be4047a860186c14 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 6 Nov 2024 18:15:59 +0000 Subject: [PATCH 283/932] =?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 8c1723d2e..2722f1457 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Internal +* ⬆ Bump cloudflare/wrangler-action from 3.11 to 3.12. PR [#12777](https://github.com/fastapi/fastapi/pull/12777) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12766](https://github.com/fastapi/fastapi/pull/12766) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * ⬆ Bump pypa/gh-action-pypi-publish from 1.10.3 to 1.11.0. PR [#12721](https://github.com/fastapi/fastapi/pull/12721) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Update pre-commit requirement from <4.0.0,>=2.17.0 to >=2.17.0,<5.0.0. PR [#12749](https://github.com/fastapi/fastapi/pull/12749) by [@dependabot[bot]](https://github.com/apps/dependabot). From 845a2ecd3910f557de3d86cedeb837d82975b39c Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 6 Nov 2024 18:17:40 +0000 Subject: [PATCH 284/932] =?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 2722f1457..32c212d70 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -43,6 +43,7 @@ hide: ### Internal +* ⬆ Bump pypa/gh-action-pypi-publish from 1.11.0 to 1.12.0. PR [#12781](https://github.com/fastapi/fastapi/pull/12781) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump cloudflare/wrangler-action from 3.11 to 3.12. PR [#12777](https://github.com/fastapi/fastapi/pull/12777) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12766](https://github.com/fastapi/fastapi/pull/12766) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * ⬆ Bump pypa/gh-action-pypi-publish from 1.10.3 to 1.11.0. PR [#12721](https://github.com/fastapi/fastapi/pull/12721) by [@dependabot[bot]](https://github.com/apps/dependabot). From d0e0b27f732aecfdde325585016a3de0c9a03e65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Pedro=20Pereira=20Holanda?= Date: Wed, 6 Nov 2024 15:21:50 -0300 Subject: [PATCH 285/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/path-operation-advanced-c?= =?UTF-8?q?onfiguration.md`=20(#12762)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../path-operation-advanced-configuration.md | 212 ++++++++++++++++++ 1 file changed, 212 insertions(+) create mode 100644 docs/pt/docs/advanced/path-operation-advanced-configuration.md diff --git a/docs/pt/docs/advanced/path-operation-advanced-configuration.md b/docs/pt/docs/advanced/path-operation-advanced-configuration.md new file mode 100644 index 000000000..04f5cc9a3 --- /dev/null +++ b/docs/pt/docs/advanced/path-operation-advanced-configuration.md @@ -0,0 +1,212 @@ +# Configuração Avançada da Operação de Rota + +## operationId do OpenAPI + +/// warning | Aviso + +Se você não é um "especialista" no OpenAPI, você provavelmente não precisa disso. + +/// + +Você pode definir o `operationId` do OpenAPI que será utilizado na sua *operação de rota* com o parâmetro `operation_id`. + +Você precisa ter certeza que ele é único para cada operação. + +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} + +### Utilizando o nome da *função de operação de rota* como o operationId + +Se você quiser utilizar o nome das funções da sua API como `operationId`s, você pode iterar sobre todos esses nomes e sobrescrever o `operationId` em cada *operação de rota* utilizando o `APIRoute.name` dela. + +Você deve fazer isso depois de adicionar todas as suas *operações de rota*. + +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *} + +/// tip | Dica + +Se você chamar `app.openapi()` manualmente, os `operationId`s devem ser atualizados antes dessa chamada. + +/// + +/// warning | Aviso + +Se você fizer isso, você tem que ter certeza de que cada uma das suas *funções de operação de rota* tem um nome único. + +Mesmo que elas estejam em módulos (arquivos Python) diferentes. + +/// + +## Excluir do OpenAPI + +Para excluir uma *operação de rota* do esquema OpenAPI gerado (e por consequência, dos sistemas de documentação automáticos), utilize o parâmetro `include_in_schema` e defina ele como `False`: + +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} + +## Descrição avançada a partir de docstring + +Você pode limitar as linhas utilizadas a partir de uma docstring de uma *função de operação de rota* para o OpenAPI. + +Adicionar um `\f` (um caractere de escape para alimentação de formulário) faz com que o **FastAPI** restrinja a saída utilizada pelo OpenAPI até esse ponto. + +Ele não será mostrado na documentação, mas outras ferramentas (como o Sphinx) serão capazes de utilizar o resto do texto. + +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} + +## Respostas Adicionais + +Você provavelmente já viu como declarar o `response_model` e `status_code` para uma *operação de rota*. + +Isso define os metadados sobre a resposta principal da *operação de rota*. + +Você também pode declarar respostas adicionais, com seus modelos, códigos de status, etc. + +Existe um capítulo inteiro da nossa documentação sobre isso, você pode ler em [Retornos Adicionais no OpenAPI](additional-responses.md){.internal-link target=_blank}. + +## Extras do OpenAPI + +Quando você declara uma *operação de rota* na sua aplicação, o **FastAPI** irá gerar os metadados relevantes da *operação de rota* automaticamente para serem incluídos no esquema do OpenAPI. + +/// note | Nota + +Na especificação do OpenAPI, isso é chamado de um Objeto de Operação. + +/// + +Ele possui toda a informação sobre a *operação de rota* e é usado para gerar a documentação automaticamente. + +Ele inclui os atributos `tags`, `parameters`, `requestBody`, `responses`, etc. + +Esse esquema específico para uma *operação de rota* normalmente é gerado automaticamente pelo **FastAPI**, mas você também pode estender ele. + +/// tip | Dica + +Esse é um ponto de extensão de baixo nível. + +Caso você só precise declarar respostas adicionais, uma forma conveniente de fazer isso é com [Retornos Adicionais no OpenAPI](additional-responses.md){.internal-link target=_blank}. + +/// + +Você pode estender o esquema do OpenAPI para uma *operação de rota* utilizando o parâmetro `openapi_extra`. + +### Extensões do OpenAPI + +Esse parâmetro `openapi_extra` pode ser útil, por exemplo, para declarar [Extensões do OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions): + +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} + +Se você abrir os documentos criados automaticamente para a API, sua extensão aparecerá no final da *operação de rota* específica. + + + +E se você olhar o esquema OpenAPI resultante (na rota `/openapi.json` da sua API), você verá que a sua extensão também faz parte da *operação de rota* específica: + +```JSON hl_lines="22" +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + } + }, + "x-aperture-labs-portal": "blue" + } + } + } +} +``` + +### Esquema de *operação de rota* do OpenAPI personalizado + +O dicionário em `openapi_extra` vai ter todos os seus níveis mesclados dentro do esquema OpenAPI gerado automaticamente para a *operação de rota*. + +Então, você pode adicionar dados extras para o esquema gerado automaticamente. + +Por exemplo, você poderia optar por ler e validar a requisição com seu próprio código, sem utilizar funcionalidades automatizadas do FastAPI com o Pydantic, mas você ainda pode quere definir a requisição no esquema OpenAPI. + +Você pode fazer isso com `openapi_extra`: + +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[19:36,39:40] *} + +Nesse exemplo, nós não declaramos nenhum modelo do Pydantic. Na verdade, o corpo da requisição não está nem mesmo analisado como JSON, ele é lido diretamente como `bytes` e a função `magic_data_reader()` seria a responsável por analisar ele de alguma forma. + +De toda forma, nós podemos declarar o esquema esperado para o corpo da requisição. + +### Tipo de conteúdo do OpenAPI personalizado + +Utilizando esse mesmo truque, você pode utilizar um modelo Pydantic para definir o esquema JSON que é então incluído na seção do esquema personalizado do OpenAPI na *operação de rota*. + +E você pode fazer isso até mesmo quando os dados da requisição não seguem o formato JSON. + +Por exemplo, nesta aplicação nós não usamos a funcionalidade integrada ao FastAPI de extrair o esquema JSON dos modelos Pydantic nem a validação automática do JSON. Na verdade, estamos declarando o tipo do conteúdo da requisição como YAML, em vez de JSON: + +//// tab | Pydantic v2 + +```Python hl_lines="17-22 24" +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +``` + +//// + +//// tab | Pydantic v1 + +```Python hl_lines="17-22 24" +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +``` + +//// + +/// info | Informação + +Na versão 1 do Pydantic, o método para obter o esquema JSON de um modelo é `Item.schema()`, na versão 2 do Pydantic, o método é `Item.model_json_schema()` + +/// + +Entretanto, mesmo que não utilizemos a funcionalidade integrada por padrão, ainda estamos usando um modelo Pydantic para gerar um esquema JSON manualmente para os dados que queremos receber no formato YAML. + +Então utilizamos a requisição diretamente, e extraímos o corpo como `bytes`. Isso significa que o FastAPI não vai sequer tentar analisar o corpo da requisição como JSON. + +E então no nosso código, nós analisamos o conteúdo YAML diretamente, e estamos utilizando o mesmo modelo Pydantic para validar o conteúdo YAML: + +//// tab | Pydantic v2 + +```Python hl_lines="26-33" +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} +``` + +//// + +//// tab | Pydantic v1 + +```Python hl_lines="26-33" +{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} +``` + +//// + +/// info | Informação + +Na versão 1 do Pydantic, o método para analisar e validar um objeto era `Item.parse_obj()`, na versão 2 do Pydantic, o método é chamado de `Item.model_validate()`. + +/// + +///tip | Dica + +Aqui reutilizamos o mesmo modelo do Pydantic. + +Mas da mesma forma, nós poderíamos ter validado de alguma outra forma. + +/// From 0c7296b19ed5cecbafb01a8d0592bcd66e703153 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 6 Nov 2024 18:24:11 +0000 Subject: [PATCH 286/932] =?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 32c212d70..d7b1134d2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/path-operation-advanced-configuration.md`. PR [#12762](https://github.com/fastapi/fastapi/pull/12762) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Korean translation for `docs/ko/docs/advanced/wsgi.md`. PR [#12659](https://github.com/fastapi/fastapi/pull/12659) by [@Limsunoh](https://github.com/Limsunoh). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/websockets.md`. PR [#12703](https://github.com/fastapi/fastapi/pull/12703) by [@devfernandoa](https://github.com/devfernandoa). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/simple-oauth2.md`. PR [#12520](https://github.com/fastapi/fastapi/pull/12520) by [@LidiaDomingos](https://github.com/LidiaDomingos). From 731c85a876f33327ad1b3a280b406703852bb0d9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 7 Nov 2024 20:32:35 +0000 Subject: [PATCH 287/932] =?UTF-8?q?=E2=AC=86=20Bump=20pypa/gh-action-pypi-?= =?UTF-8?q?publish=20from=201.12.0=20to=201.12.2=20(#12788)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.12.0 to 1.12.2. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.12.0...v1.12.2) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index a26d2d563..fc61c3fca 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -35,7 +35,7 @@ jobs: TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.12.0 + uses: pypa/gh-action-pypi-publish@v1.12.2 - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} From f2c7b8772183256e62c9c1ac0b4e44e467fdc55a Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 7 Nov 2024 20:32:59 +0000 Subject: [PATCH 288/932] =?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 d7b1134d2..57d58696c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -44,6 +44,7 @@ hide: ### Internal +* ⬆ Bump pypa/gh-action-pypi-publish from 1.12.0 to 1.12.2. PR [#12788](https://github.com/fastapi/fastapi/pull/12788) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pypa/gh-action-pypi-publish from 1.11.0 to 1.12.0. PR [#12781](https://github.com/fastapi/fastapi/pull/12781) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump cloudflare/wrangler-action from 3.11 to 3.12. PR [#12777](https://github.com/fastapi/fastapi/pull/12777) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12766](https://github.com/fastapi/fastapi/pull/12766) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). From 23c352246757e9c960571caddd6be3ba1cbe440b Mon Sep 17 00:00:00 2001 From: kim-sangah Date: Fri, 8 Nov 2024 05:38:25 +0900 Subject: [PATCH 289/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/security/index.md`=20(#12743)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/security/index.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 docs/ko/docs/security/index.md diff --git a/docs/ko/docs/security/index.md b/docs/ko/docs/security/index.md new file mode 100644 index 000000000..5a6c733f0 --- /dev/null +++ b/docs/ko/docs/security/index.md @@ -0,0 +1,19 @@ +# 고급 보안 + +## 추가 기능 + +[자습서 - 사용자 가이드: 보안](../../tutorial/security/index.md){.internal-link target=_blank} 문서에서 다룬 내용 외에도 보안 처리를 위한 몇 가지 추가 기능이 있습니다. + +/// tip + +다음 섹션은 **반드시 "고급"** 기능은 아닙니다. + +그리고 여러분의 사용 사례에 따라, 적합한 해결책이 그 중 하나에 있을 가능성이 있습니다. + +/// + +## 먼저 자습서 읽기 + +다음 섹션은 이미 [자습서 - 사용자 가이드: 보안](../../tutorial/security/index.md){.internal-link target=_blank} 문서를 읽었다고 가정합니다. + +이 섹션들은 모두 동일한 개념을 바탕으로 하며, 추가 기능을 제공합니다. From 569c54cb9a80b41fe7c770815b8d77bfc50820c0 Mon Sep 17 00:00:00 2001 From: namjimin_43 Date: Fri, 8 Nov 2024 05:38:31 +0900 Subject: [PATCH 290/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/advanced/testing-events.md`=20(#12741)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/advanced/testing-events.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 docs/ko/docs/advanced/testing-events.md diff --git a/docs/ko/docs/advanced/testing-events.md b/docs/ko/docs/advanced/testing-events.md new file mode 100644 index 000000000..dc082412a --- /dev/null +++ b/docs/ko/docs/advanced/testing-events.md @@ -0,0 +1,7 @@ +# 이벤트 테스트: 시작 - 종료 + +테스트에서 이벤트 핸들러(`startup` 및 `shutdown`)를 실행해야 하는 경우, `with` 문과 함께 `TestClient`를 사용할 수 있습니다. + +```Python hl_lines="9-12 20-24" +{!../../docs_src/app_testing/tutorial003.py!} +``` From 3a2ec11e807ec6e0e1e3350d342c0ad87b122027 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 7 Nov 2024 20:38:47 +0000 Subject: [PATCH 291/932] =?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 57d58696c..8b982817a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/security/index.md`. PR [#12743](https://github.com/fastapi/fastapi/pull/12743) by [@kim-sangah](https://github.com/kim-sangah). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/path-operation-advanced-configuration.md`. PR [#12762](https://github.com/fastapi/fastapi/pull/12762) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Korean translation for `docs/ko/docs/advanced/wsgi.md`. PR [#12659](https://github.com/fastapi/fastapi/pull/12659) by [@Limsunoh](https://github.com/Limsunoh). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/websockets.md`. PR [#12703](https://github.com/fastapi/fastapi/pull/12703) by [@devfernandoa](https://github.com/devfernandoa). From b3d3f0e7234574b006d4468dfcdd406d8cd5a629 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 7 Nov 2024 20:39:11 +0000 Subject: [PATCH 292/932] =?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 8b982817a..912b75974 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/advanced/testing-events.md`. PR [#12741](https://github.com/fastapi/fastapi/pull/12741) by [@9zimin9](https://github.com/9zimin9). * 🌐 Add Korean translation for `docs/ko/docs/security/index.md`. PR [#12743](https://github.com/fastapi/fastapi/pull/12743) by [@kim-sangah](https://github.com/kim-sangah). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/path-operation-advanced-configuration.md`. PR [#12762](https://github.com/fastapi/fastapi/pull/12762) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Korean translation for `docs/ko/docs/advanced/wsgi.md`. PR [#12659](https://github.com/fastapi/fastapi/pull/12659) by [@Limsunoh](https://github.com/Limsunoh). From c5ff950dfc37d26a436dc7d1ea7827350df0721c Mon Sep 17 00:00:00 2001 From: LKY <74170199+kwang1215@users.noreply.github.com> Date: Fri, 8 Nov 2024 05:40:19 +0900 Subject: [PATCH 293/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/advanced/using=5Frequest=5Fdirectly.md?= =?UTF-8?q?`=20(#12738)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/advanced/using-request-directly.md | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 docs/ko/docs/advanced/using-request-directly.md diff --git a/docs/ko/docs/advanced/using-request-directly.md b/docs/ko/docs/advanced/using-request-directly.md new file mode 100644 index 000000000..027ea9fad --- /dev/null +++ b/docs/ko/docs/advanced/using-request-directly.md @@ -0,0 +1,58 @@ +# `Request` 직접 사용하기 + +지금까지 요청에서 필요한 부분을 각 타입으로 선언하여 사용해 왔습니다. + +다음과 같은 곳에서 데이터를 가져왔습니다: + +* 경로의 파라미터로부터. +* 헤더. +* 쿠키. +* 기타 등등. + +이렇게 함으로써, **FastAPI**는 데이터를 검증하고 변환하며, API에 대한 문서를 자동화로 생성합니다. + +하지만 `Request` 객체에 직접 접근해야 하는 상황이 있을 수 있습니다. + +## `Request` 객체에 대한 세부 사항 + +**FastAPI**는 실제로 내부에 **Starlette**을 사용하며, 그 위에 여러 도구를 덧붙인 구조입니다. 따라서 여러분이 필요할 때 Starlette의 `Request` 객체를 직접 사용할 수 있습니다. + +`Request` 객체에서 데이터를 직접 가져오는 경우(예: 본문을 읽기)에는 FastAPI가 해당 데이터를 검증하거나 변환하지 않으며, 문서화(OpenAPI를 통한 문서 자동화(로 생성된) API 사용자 인터페이스)도 되지 않습니다. + +그러나 다른 매개변수(예: Pydantic 모델을 사용한 본문)는 여전히 검증, 변환, 주석 추가 등이 이루어집니다. + +하지만 특정한 경우에는 `Request` 객체에 직접 접근하는 것이 유용할 수 있습니다. + +## `Request` 객체를 직접 사용하기 + +여러분이 클라이언트의 IP 주소/호스트 정보를 *경로 작동 함수* 내부에서 가져와야 한다고 가정해 보겠습니다. + +이를 위해서는 요청에 직접 접근해야 합니다. + +```Python hl_lines="1 7-8" +{!../../docs_src/using_request_directly/tutorial001.py!} +``` + +*경로 작동 함수* 매개변수를 `Request` 타입으로 선언하면 **FastAPI**가 해당 매개변수에 `Request` 객체를 전달하는 것을 알게 됩니다. + +/// tip | 팁 + +이 경우, 요청 매개변수와 함께 경로 매개변수를 선언한 것을 볼 수 있습니다. + +따라서, 경로 매개변수는 추출되고 검증되며 지정된 타입으로 변환되고 OpenAPI로 주석이 추가됩니다. + +이와 같은 방식으로, 다른 매개변수들을 평소처럼 선언하면서, 부가적으로 `Request`도 가져올 수 있습니다. + +/// + +## `Request` 설명서 + +여러분은 `Request` 객체에 대한 더 자세한 내용을 공식 Starlette 설명서 사이트에서 읽어볼 수 있습니다. + +/// note | 기술 세부사항 + +`from starlette.requests import Request`를 사용할 수도 있습니다. + +**FastAPI**는 여러분(개발자)를 위한 편의를 위해 이를 직접 제공하지만, 실제로는 Starlette에서 가져온 것입니다. + +/// From 2fcae5f10832bc89f9a1f7974270cc83bedf8c40 Mon Sep 17 00:00:00 2001 From: sptcnl <119477585+sptcnl@users.noreply.github.com> Date: Fri, 8 Nov 2024 05:41:38 +0900 Subject: [PATCH 294/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/how-to/conditional-openapi.md`=20(#127?= =?UTF-8?q?31)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/how-to/conditional-openapi.md | 61 ++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 docs/ko/docs/how-to/conditional-openapi.md diff --git a/docs/ko/docs/how-to/conditional-openapi.md b/docs/ko/docs/how-to/conditional-openapi.md new file mode 100644 index 000000000..79c7f0dd2 --- /dev/null +++ b/docs/ko/docs/how-to/conditional-openapi.md @@ -0,0 +1,61 @@ +# 조건부적인 OpenAPI + +필요한 경우, 설정 및 환경 변수를 사용하여 환경에 따라 조건부로 OpenAPI를 구성하고 완전히 비활성화할 수도 있습니다. + +## 보안, API 및 docs에 대해서 + +프로덕션에서, 문서화된 사용자 인터페이스(UI)를 숨기는 것이 API를 보호하는 방법이 *되어서는 안 됩니다*. + +이는 API에 추가적인 보안을 제공하지 않으며, *경로 작업*은 여전히 동일한 위치에서 사용 할 수 있습니다. + +코드에 보안 결함이 있다면, 그 결함은 여전히 존재할 것입니다. + +문서를 숨기는 것은 API와 상호작용하는 방법을 이해하기 어렵게 만들며, 프로덕션에서 디버깅을 더 어렵게 만들 수 있습니다. 이는 단순히 '모호성에 의한 보안'의 한 형태로 간주될 수 있습니다. + +API를 보호하고 싶다면, 예를 들어 다음과 같은 더 나은 방법들이 있습니다: + +* 요청 본문과 응답에 대해 잘 정의된 Pydantic 모델을 사용하도록 하세요. + +* 종속성을 사용하여 필요한 권한과 역할을 구성하세요. + +* 평문 비밀번호를 절대 저장하지 말고, 오직 암호화된 비밀번호만 저장하세요. + +* Passlib과 JWT 토큰과 같은 잘 알려진 암호화 도구들을 구현하고 사용하세요. + +* 필요한 곳에 OAuth2 범위를 사용하여 더 세분화된 권한 제어를 추가하세요. + +* 등등.... + +그럼에도 불구하고, 특정 환경(예: 프로덕션)에서 또는 환경 변수의 설정에 따라 API 문서를 비활성화해야 하는 매우 특정한 사용 사례가 있을 수 있습니다. + +## 설정 및 환경변수의 조건부 OpenAPI + +동일한 Pydantic 설정을 사용하여 생성된 OpenAPI 및 문서 UI를 쉽게 구성할 수 있습니다. + +예를 들어: + +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} + +여기서 `openapi_url` 설정을 기본값인 `"/openapi.json"`으로 선언합니다. + +그런 뒤, 우리는 `FastAPI` 앱을 만들 때 그것을 사용합니다. + +환경 변수 `OPENAPI_URL`을 빈 문자열로 설정하여 OpenAPI(문서 UI 포함)를 비활성화할 수도 있습니다. 예를 들어: + +
+ +```console +$ OPENAPI_URL= uvicorn main:app + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +그리고 `/openapi.json`, `/docs` 또는 `/redoc`의 URL로 이동하면 `404 Not Found`라는 오류가 다음과 같이 표시됩니다: + +```JSON +{ + "detail": "Not Found" +} +``` From 4565466f3494ad4c0a56927994087e238fc4a13a Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 7 Nov 2024 20:43:27 +0000 Subject: [PATCH 295/932] =?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 912b75974..1adf634da 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/advanced/using_request_directly.md`. PR [#12738](https://github.com/fastapi/fastapi/pull/12738) by [@kwang1215](https://github.com/kwang1215). * 🌐 Add Korean translation for `docs/ko/docs/advanced/testing-events.md`. PR [#12741](https://github.com/fastapi/fastapi/pull/12741) by [@9zimin9](https://github.com/9zimin9). * 🌐 Add Korean translation for `docs/ko/docs/security/index.md`. PR [#12743](https://github.com/fastapi/fastapi/pull/12743) by [@kim-sangah](https://github.com/kim-sangah). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/path-operation-advanced-configuration.md`. PR [#12762](https://github.com/fastapi/fastapi/pull/12762) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). From 321053bdef17bbe3dffba0c324a9f6215411fcfe Mon Sep 17 00:00:00 2001 From: kim-sangah Date: Fri, 8 Nov 2024 05:43:46 +0900 Subject: [PATCH 296/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/advanced/advanced-dependencies.md`=20(?= =?UTF-8?q?#12675)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ko/docs/advanced/advanced-dependencies.md | 179 ++++++++++++++++++ 1 file changed, 179 insertions(+) create mode 100644 docs/ko/docs/advanced/advanced-dependencies.md diff --git a/docs/ko/docs/advanced/advanced-dependencies.md b/docs/ko/docs/advanced/advanced-dependencies.md new file mode 100644 index 000000000..aa5a332f8 --- /dev/null +++ b/docs/ko/docs/advanced/advanced-dependencies.md @@ -0,0 +1,179 @@ +# 고급 의존성 + +## 매개변수화된 의존성 + +지금까지 본 모든 의존성은 고정된 함수 또는 클래스입니다. + +하지만 여러 개의 함수나 클래스를 선언하지 않고도 의존성에 매개변수를 설정해야 하는 경우가 있을 수 있습니다. + +예를 들어, `q` 쿼리 매개변수가 특정 고정된 내용을 포함하고 있는지 확인하는 의존성을 원한다고 가정해 봅시다. + +이때 해당 고정된 내용을 매개변수화할 수 있길 바랍니다. + +## "호출 가능한" 인스턴스 + +Python에는 클래스의 인스턴스를 "호출 가능"하게 만드는 방법이 있습니다. + +클래스 자체(이미 호출 가능함)가 아니라 해당 클래스의 인스턴스에 대해 호출 가능하게 하는 것입니다. + +이를 위해 `__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 | 참고 + +가능하다면 `Annotated` 버전을 사용하는 것이 좋습니다. + +/// + +```Python hl_lines="10" +{!> ../../docs_src/dependencies/tutorial011.py!} +``` + +//// + +이 경우, **FastAPI**는 추가 매개변수와 하위 의존성을 확인하기 위해 `__call__`을 사용하게 되며, +나중에 *경로 연산 함수*에서 매개변수에 값을 전달할 때 이를 호출하게 됩니다. + +## 인스턴스 매개변수화하기 + +이제 `__init__`을 사용하여 의존성을 "매개변수화"할 수 있는 인스턴스의 매개변수를 선언할 수 있습니다: + +//// 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 | 참고 + +가능하다면 `Annotated` 버전을 사용하는 것이 좋습니다. + +/// + +```Python hl_lines="7" +{!> ../../docs_src/dependencies/tutorial011.py!} +``` + +//// + +이 경우, **FastAPI**는 `__init__`에 전혀 관여하지 않으며, 우리는 이 메서드를 코드에서 직접 사용하게 됩니다. + +## 인스턴스 생성하기 + +다음과 같이 이 클래스의 인스턴스를 생성할 수 있습니다: + +//// 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 | 참고 + +가능하다면 `Annotated` 버전을 사용하는 것이 좋습니다. + +/// + +```Python hl_lines="16" +{!> ../../docs_src/dependencies/tutorial011.py!} +``` + +//// + +이렇게 하면 `checker.fixed_content` 속성에 `"bar"`라는 값을 담아 의존성을 "매개변수화"할 수 있습니다. + +## 인스턴스를 의존성으로 사용하기 + +그런 다음, `Depends(FixedContentQueryChecker)` 대신 `Depends(checker)`에서 이 `checker` 인스턴스를 사용할 수 있으며, +클래스 자체가 아닌 인스턴스 `checker`가 의존성이 됩니다. + +의존성을 해결할 때 **FastAPI**는 이 `checker`를 다음과 같이 호출합니다: + +```Python +checker(q="somequery") +``` + +...그리고 이때 반환되는 값을 *경로 연산 함수*의 `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 | 참고 + +가능하다면 `Annotated` 버전을 사용하는 것이 좋습니다. + +/// + +```Python hl_lines="20" +{!> ../../docs_src/dependencies/tutorial011.py!} +``` + +//// + +/// tip | 참고 + +이 모든 과정이 복잡하게 느껴질 수 있습니다. 그리고 지금은 이 방법이 얼마나 유용한지 명확하지 않을 수도 있습니다. + +이 예시는 의도적으로 간단하게 만들었지만, 전체 구조가 어떻게 작동하는지 보여줍니다. + +보안 관련 장에서는 이와 같은 방식으로 구현된 편의 함수들이 있습니다. + +이 모든 과정을 이해했다면, 이러한 보안 도구들이 내부적으로 어떻게 작동하는지 이미 파악한 것입니다. + +/// From 1b8030945fff1bcbda098e81d8612ac8412d906f Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 7 Nov 2024 20:45:49 +0000 Subject: [PATCH 297/932] =?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 1adf634da..4ca504c12 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/how-to/conditional-openapi.md`. PR [#12731](https://github.com/fastapi/fastapi/pull/12731) by [@sptcnl](https://github.com/sptcnl). * 🌐 Add Korean translation for `docs/ko/docs/advanced/using_request_directly.md`. PR [#12738](https://github.com/fastapi/fastapi/pull/12738) by [@kwang1215](https://github.com/kwang1215). * 🌐 Add Korean translation for `docs/ko/docs/advanced/testing-events.md`. PR [#12741](https://github.com/fastapi/fastapi/pull/12741) by [@9zimin9](https://github.com/9zimin9). * 🌐 Add Korean translation for `docs/ko/docs/security/index.md`. PR [#12743](https://github.com/fastapi/fastapi/pull/12743) by [@kim-sangah](https://github.com/kim-sangah). From 745c073a6b37bbbb9c262eed79bacfae54f9e1a9 Mon Sep 17 00:00:00 2001 From: Saeye Lee <62229734+saeye@users.noreply.github.com> Date: Fri, 8 Nov 2024 05:46:14 +0900 Subject: [PATCH 298/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/history-design-future.md`=20(#12646)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/history-design-future.md | 81 +++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 docs/ko/docs/history-design-future.md diff --git a/docs/ko/docs/history-design-future.md b/docs/ko/docs/history-design-future.md new file mode 100644 index 000000000..6680a46e7 --- /dev/null +++ b/docs/ko/docs/history-design-future.md @@ -0,0 +1,81 @@ +# 역사, 디자인 그리고 미래 + +어느 날, [한 FastAPI 사용자](https://github.com/fastapi/fastapi/issues/3#issuecomment-454956920)가 이렇게 물었습니다: + +> 이 프로젝트의 역사를 알려 주실 수 있나요? 몇 주 만에 멋진 결과를 낸 것 같아요. [...] + +여기서 그 역사에 대해 간단히 설명하겠습니다. + +--- + +## 대안 + +저는 여러 해 동안 머신러닝, 분산 시스템, 비동기 작업, NoSQL 데이터베이스 같은 복잡한 요구사항을 가진 API를 개발하며 여러 팀을 이끌어 왔습니다. + +이 과정에서 많은 대안을 조사하고, 테스트하며, 사용해야 했습니다. **FastAPI**의 역사는 그 이전에 나왔던 여러 도구의 역사와 밀접하게 연관되어 있습니다. + +[대안](alternatives.md){.internal-link target=_blank} 섹션에서 언급된 것처럼: + +> **FastAPI**는 이전에 나왔던 많은 도구들의 노력 없이는 존재하지 않았을 것입니다. +> +> 이전에 개발된 여러 도구들이 이 프로젝트에 영감을 주었습니다. +> +> 저는 오랫동안 새로운 프레임워크를 만드는 것을 피하고자 했습니다. 처음에는 **FastAPI**가 제공하는 기능들을 다양한 프레임워크와 플러그인, 도구들을 조합해 해결하려 했습니다. +> +> 하지만 결국에는 이 모든 기능을 통합하는 도구가 필요해졌습니다. 이전 도구들로부터 최고의 아이디어들을 모으고, 이를 최적의 방식으로 조합해야만 했습니다. 이는 :term:Python 3.6+ 타입 힌트 와 같은, 이전에는 사용할 수 없었던 언어 기능이 가능했기 때문입니다. + +--- + +## 조사 + +여러 대안을 사용해 보며 다양한 도구에서 배운 점들을 모아 저와 개발팀에게 가장 적합한 방식을 찾았습니다. + +예를 들어, 표준 :term:Python 타입 힌트 에 기반하는 것이 이상적이라는 점이 명확했습니다. + +또한, 이미 존재하는 표준을 활용하는 것이 가장 좋은 접근법이라 판단했습니다. + +그래서 **FastAPI**의 코드를 작성하기 전에 몇 달 동안 OpenAPI, JSON Schema, OAuth2 명세를 연구하며 이들의 관계와 겹치는 부분, 차이점을 이해했습니다. + +--- + +## 디자인 + +그 후, **FastAPI** 사용자가 될 개발자로서 사용하고 싶은 개발자 "API"를 디자인했습니다. + +[Python Developer Survey](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools)에 따르면 약 80%의 Python 개발자가 PyCharm, VS Code, Jedi 기반 편집기 등에서 개발합니다. 이 과정에서 여러 아이디어를 테스트했습니다. + +대부분의 다른 편집기도 유사하게 동작하기 때문에, **FastAPI**의 이점은 거의 모든 편집기에서 누릴 수 있습니다. + +이 과정을 통해 코드 중복을 최소화하고, 모든 곳에서 자동 완성, 타입 검사, 에러 확인 기능이 제공되는 최적의 방식을 찾아냈습니다. + +이 모든 것은 개발자들에게 최고의 개발 경험을 제공하기 위해 설계되었습니다. + +--- + +## 필요조건 + +여러 대안을 테스트한 후, [Pydantic](https://docs.pydantic.dev/)을 사용하기로 결정했습니다. + +이후 저는 **Pydantic**이 JSON Schema와 완벽히 호환되도록 개선하고, 다양한 제약 조건 선언을 지원하며, 여러 편집기에서의 자동 완성과 타입 검사 기능을 향상하기 위해 기여했습니다. + +또한, 또 다른 주요 필요조건이었던 [Starlette](https://www.starlette.io/)에도 기여했습니다. + +--- + +## 개발 + +**FastAPI**를 개발하기 시작할 즈음에는 대부분의 준비가 이미 완료된 상태였습니다. 설계가 정의되었고, 필요조건과 도구가 준비되었으며, 표준과 명세에 대한 지식도 충분했습니다. + +--- + +## 미래 + +현시점에서 **FastAPI**가 많은 사람들에게 유용하다는 것이 명백해졌습니다. + +여러 용도에 더 적합한 도구로서 기존 대안보다 선호되고 있습니다. +이미 많은 개발자와 팀들이 **FastAPI**에 의존해 프로젝트를 진행 중입니다 (저와 제 팀도 마찬가지입니다). + +하지만 여전히 개선해야 할 점과 추가할 기능들이 많이 남아 있습니다. + +**FastAPI**는 밝은 미래로 나아가고 있습니다. +그리고 [여러분의 도움](help-fastapi.md){.internal-link target=_blank}은 큰 힘이 됩니다. From 3ff6cfd544ac4fca6ec76d87ffc0a2eae4707691 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 7 Nov 2024 20:48:35 +0000 Subject: [PATCH 299/932] =?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 4ca504c12..fe1789a70 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/advanced/advanced-dependencies.md`. PR [#12675](https://github.com/fastapi/fastapi/pull/12675) by [@kim-sangah](https://github.com/kim-sangah). * 🌐 Add Korean translation for `docs/ko/docs/how-to/conditional-openapi.md`. PR [#12731](https://github.com/fastapi/fastapi/pull/12731) by [@sptcnl](https://github.com/sptcnl). * 🌐 Add Korean translation for `docs/ko/docs/advanced/using_request_directly.md`. PR [#12738](https://github.com/fastapi/fastapi/pull/12738) by [@kwang1215](https://github.com/kwang1215). * 🌐 Add Korean translation for `docs/ko/docs/advanced/testing-events.md`. PR [#12741](https://github.com/fastapi/fastapi/pull/12741) by [@9zimin9](https://github.com/9zimin9). From 647a0dcad31133e9f812303c500a311e62897a91 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 7 Nov 2024 20:52:31 +0000 Subject: [PATCH 300/932] =?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 fe1789a70..78e98cbc1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/history-design-future.md`. PR [#12646](https://github.com/fastapi/fastapi/pull/12646) by [@saeye](https://github.com/saeye). * 🌐 Add Korean translation for `docs/ko/docs/advanced/advanced-dependencies.md`. PR [#12675](https://github.com/fastapi/fastapi/pull/12675) by [@kim-sangah](https://github.com/kim-sangah). * 🌐 Add Korean translation for `docs/ko/docs/how-to/conditional-openapi.md`. PR [#12731](https://github.com/fastapi/fastapi/pull/12731) by [@sptcnl](https://github.com/sptcnl). * 🌐 Add Korean translation for `docs/ko/docs/advanced/using_request_directly.md`. PR [#12738](https://github.com/fastapi/fastapi/pull/12738) by [@kwang1215](https://github.com/kwang1215). From d28bae06e4b73feb98282874d6031c3ba6dd7b64 Mon Sep 17 00:00:00 2001 From: Hyunjun KIM Date: Fri, 8 Nov 2024 05:57:27 +0900 Subject: [PATCH 301/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`/docs/ko/docs/environment-variables.md`=20(#12526)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/environment-variables.md | 298 ++++++++++++++++++++++++++ 1 file changed, 298 insertions(+) create mode 100644 docs/ko/docs/environment-variables.md diff --git a/docs/ko/docs/environment-variables.md b/docs/ko/docs/environment-variables.md new file mode 100644 index 000000000..09c2fd6d3 --- /dev/null +++ b/docs/ko/docs/environment-variables.md @@ -0,0 +1,298 @@ +# 환경 변수 + +/// tip | "팁" + +만약 "환경 변수"가 무엇이고, 어떻게 사용하는지 알고 계시다면, 이 챕터를 스킵하셔도 좋습니다. + +/// + +환경 변수는 파이썬 코드의 **바깥**인, **운영 체제**에 존재하는 변수입니다. 파이썬 코드나 다른 프로그램에서 읽을 수 있습니다. + +환경 변수는 애플리케이션 **설정**을 처리하거나, 파이썬의 **설치** 과정의 일부로 유용합니다. + +## 환경 변수를 만들고 사용하기 + +파이썬 없이도, **셸 (터미널)** 에서 환경 변수를 **생성** 하고 사용할 수 있습니다. + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// You could create an env var MY_NAME with +$ export MY_NAME="Wade Wilson" + +// Then you could use it with other programs, like +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Create an env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Use it with other programs, like +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## 파이썬에서 환경 변수 읽기 + +파이썬 **바깥**인 터미널에서(다른 도구로도 가능) 환경 변수를 생성도 할 수도 있고, 이를 **파이썬에서 읽을 수 있습니다.** + +예를 들어 다음과 같은 `main.py` 파일이 있다고 합시다: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip | "팁" + +`os.getenv()` 의 두 번째 인자는 반환할 기본값입니다. + +여기서는 `"World"`를 넣었기에 기본값으로써 사용됩니다. 넣지 않으면 `None` 이 기본값으로 사용됩니다. + +/// + +그러면 해당 파이썬 프로그램을 다음과 같이 호출할 수 있습니다: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ export MY_NAME="Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ $Env:MY_NAME = "Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
+ +//// + +환경변수는 코드 바깥에서 설정될 수 있지만, 코드에서 읽을 수 있고, 나머지 파일과 함께 저장(`git`에 커밋)할 필요가 없으므로, 구성이나 **설정** 에 사용하는 것이 일반적입니다. + +**특정 프로그램 호출**에 대해서만 사용할 수 있는 환경 변수를 만들 수도 있습니다. 해당 프로그램에서만 사용할 수 있고, 해당 프로그램이 실행되는 동안만 사용할 수 있습니다. + +그렇게 하려면 프로그램 바로 앞, 같은 줄에 환경 변수를 만들어야 합니다: + +
+ +```console +// Create an env var MY_NAME in line for this program call +$ MY_NAME="Wade Wilson" python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python + +// The env var no longer exists afterwards +$ python main.py + +Hello World from Python +``` + +
+ +/// tip | "팁" + +The Twelve-Factor App: Config 에서 좀 더 자세히 알아볼 수 있습니다. + +/// + +## 타입과 검증 + +이 환경변수들은 오직 **텍스트 문자열**로만 처리할 수 있습니다. 텍스트 문자열은 파이썬 외부에 있으며 다른 프로그램 및 나머지 시스템(Linux, Windows, macOS 등 다른 운영 체제)과 호환되어야 합니다. + +즉, 파이썬에서 환경 변수로부터 읽은 **모든 값**은 **`str`**이 되고, 다른 타입으로의 변환이나 검증은 코드에서 수행해야 합니다. + +**애플리케이션 설정**을 처리하기 위한 환경 변수 사용에 대한 자세한 내용은 [고급 사용자 가이드 - 설정 및 환경 변수](./advanced/settings.md){.internal-link target=\_blank} 에서 확인할 수 있습니다. + +## `PATH` 환경 변수 + +**`PATH`**라고 불리는, **특별한** 환경변수가 있습니다. 운영체제(Linux, Windows, macOS 등)에서 실행할 프로그램을 찾기위해 사용됩니다. + +변수 `PATH`의 값은 Linux와 macOS에서는 콜론 `:`, Windows에서는 세미콜론 `;`으로 구분된 디렉토리로 구성된 긴 문자열입니다. + +예를 들어, `PATH` 환경 변수는 다음과 같습니다: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +이는 시스템이 다음 디렉토리에서 프로그램을 찾아야 함을 의미합니다: + +- `/usr/local/bin` +- `/usr/bin` +- `/bin` +- `/usr/sbin` +- `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +이는 시스템이 다음 디렉토리에서 프로그램을 찾아야 함을 의미합니다: + +- `C:\Program Files\Python312\Scripts` +- `C:\Program Files\Python312` +- `C:\Windows\System32` + +//// + +터미널에 **명령어**를 입력하면 운영 체제는 `PATH` 환경 변수에 나열된 **각 디렉토리**에서 프로그램을 **찾습니다.** + +예를 들어 터미널에 `python`을 입력하면 운영 체제는 해당 목록의 **첫 번째 디렉토리**에서 `python`이라는 프로그램을 찾습니다. + +찾으면 **사용합니다**. 그렇지 않으면 **다른 디렉토리**에서 계속 찾습니다. + +### 파이썬 설치와 `PATH` 업데이트 + +파이썬을 설치할 때, 아마 `PATH` 환경 변수를 업데이트 할 것이냐고 물어봤을 겁니다. + +//// tab | Linux, macOS + +파이썬을 설치하고 그것이 `/opt/custompython/bin` 디렉토리에 있다고 가정해 보겠습니다. + +`PATH` 환경 변수를 업데이트하도록 "예"라고 하면 설치 관리자가 `/opt/custompython/bin`을 `PATH` 환경 변수에 추가합니다. + +다음과 같이 보일 수 있습니다: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +이렇게 하면 터미널에 `python`을 입력할 때, 시스템이 `/opt/custompython/bin`(마지막 디렉토리)에서 파이썬 프로그램을 찾아 사용합니다. + +//// + +//// tab | Windows + +파이썬을 설치하고 그것이 `C:\opt\custompython\bin` 디렉토리에 있다고 가정해 보겠습니다. + +`PATH` 환경 변수를 업데이트하도록 "예"라고 하면 설치 관리자가 `C:\opt\custompython\bin`을 `PATH` 환경 변수에 추가합니다. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +이렇게 하면 터미널에 `python`을 입력할 때, 시스템이 `C:\opt\custompython\bin`(마지막 디렉토리)에서 파이썬 프로그램을 찾아 사용합니다. + +//// + +그래서, 다음과 같이 입력한다면: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +시스템은 `/opt/custompython/bin`에서 `python` 프로그램을 **찾아** 실행합니다. + +다음과 같이 입력하는 것과 거의 같습니다: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +시스템은 `C:\opt\custompython\bin\python`에서 `python` 프로그램을 **찾아** 실행합니다. + +다음과 같이 입력하는 것과 거의 같습니다: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +이 정보는 [가상 환경](virtual-environments.md){.internal-link target=\_blank} 에 대해 알아볼 때 유용할 것입니다. + +## 결론 + +이 문서를 읽고 **환경 변수**가 무엇이고 파이썬에서 어떻게 사용하는지 기본적으로 이해하셨을 겁니다. + +또한 환경 변수에 대한 위키피디아(한국어)에서 이에 대해 자세히 알아볼 수 있습니다. + +많은 경우에서, 환경 변수가 어떻게 유용하고 적용 가능한지 바로 명확하게 알 수는 없습니다. 하지만 개발할 때 다양한 시나리오에서 계속 나타나므로 이에 대해 아는 것이 좋습니다. + +예를 들어, 다음 섹션인 [가상 환경](virtual-environments.md)에서 이 정보가 필요합니다. From 2809c08a70c5b429a8fe803a5d62802d44d066be Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 7 Nov 2024 21:05:45 +0000 Subject: [PATCH 302/932] =?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 78e98cbc1..3764e2f96 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `/docs/ko/docs/environment-variables.md`. PR [#12526](https://github.com/fastapi/fastapi/pull/12526) by [@Tolerblanc](https://github.com/Tolerblanc). * 🌐 Add Korean translation for `docs/ko/docs/history-design-future.md`. PR [#12646](https://github.com/fastapi/fastapi/pull/12646) by [@saeye](https://github.com/saeye). * 🌐 Add Korean translation for `docs/ko/docs/advanced/advanced-dependencies.md`. PR [#12675](https://github.com/fastapi/fastapi/pull/12675) by [@kim-sangah](https://github.com/kim-sangah). * 🌐 Add Korean translation for `docs/ko/docs/how-to/conditional-openapi.md`. PR [#12731](https://github.com/fastapi/fastapi/pull/12731) by [@sptcnl](https://github.com/sptcnl). From 45d9fabbdd3b0d30f4faa87c9abc95b9cb73d615 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E4=BA=91=E6=98=94=20=28Vincy=20SHI=29?= Date: Sat, 9 Nov 2024 03:23:26 +0800 Subject: [PATCH 303/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/virtual-environments.md`=20(#12790)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/virtual-environments.md | 844 +++++++++++++++++++++++++++ 1 file changed, 844 insertions(+) create mode 100644 docs/zh/docs/virtual-environments.md diff --git a/docs/zh/docs/virtual-environments.md b/docs/zh/docs/virtual-environments.md new file mode 100644 index 000000000..9b3c0340a --- /dev/null +++ b/docs/zh/docs/virtual-environments.md @@ -0,0 +1,844 @@ +# 虚拟环境 + +当你在 Python 工程中工作时,你可能会有必要用到一个**虚拟环境**(或类似的机制)来隔离你为每个工程安装的包。 + +/// info + +如果你已经了解虚拟环境,知道如何创建和使用它们,你可以考虑跳过这一部分。🤓 + +/// + +/// tip + +**虚拟环境**和**环境变量**是不同的。 + +**环境变量**是系统中的一个变量,可以被程序使用。 + +**虚拟环境**是一个包含一些文件的目录。 + +/// + +/// info + +这个页面将教你如何使用**虚拟环境**以及了解它们的工作原理。 + +如果你计划使用一个**可以为你管理一切的工具**(包括安装 Python),试试 uv。 + +/// + +## 创建一个工程 + +首先,为你的工程创建一个目录。 + +我 (指原作者 —— 译者注) 通常会在我的主目录下创建一个名为 `code` 的目录。 + +在这个目录下,我再为每个工程创建一个目录。 + +
+ +```console +// 进入主目录 +$ cd +// 创建一个用于存放所有代码工程的目录 +$ mkdir code +// 进入 code 目录 +$ cd code +// 创建一个用于存放这个工程的目录 +$ mkdir awesome-project +// 进入这个工程的目录 +$ cd awesome-project +``` + +
+ +## 创建一个虚拟环境 + +在开始一个 Python 工程的**第一时间**,**在你的工程内部**创建一个虚拟环境。 + +/// tip + +你只需要 **在每个工程中操作一次**,而不是每次工作时都操作。 + +/// + +//// tab | `venv` + +你可以使用 Python 自带的 `venv` 模块来创建一个虚拟环境。 + +
+ +```console +$ python -m venv .venv +``` + +
+ +/// details | 上述命令的含义 + +* `python`: 使用名为 `python` 的程序 +* `-m`: 以脚本的方式调用一个模块,我们将告诉它接下来使用哪个模块 +* `venv`: 使用名为 `venv` 的模块,这个模块通常随 Python 一起安装 +* `.venv`: 在新目录 `.venv` 中创建虚拟环境 + +/// + +//// + +//// tab | `uv` + +如果你安装了 `uv`,你也可以使用它来创建一个虚拟环境。 + +
+ +```console +$ uv venv +``` + +
+ +/// tip + +默认情况下,`uv` 会在一个名为 `.venv` 的目录中创建一个虚拟环境。 + +但你可以通过传递一个额外的参数来自定义它,指定目录的名称。 + +/// + +//// + +这个命令会在一个名为 `.venv` 的目录中创建一个新的虚拟环境。 + +/// details | `.venv`,或是其他名称 + +你可以在不同的目录下创建虚拟环境,但通常我们会把它命名为 `.venv`。 + +/// + +## 激活虚拟环境 + +激活新的虚拟环境来确保你运行的任何 Python 命令或安装的包都能使用到它。 + +/// tip + +**每次**开始一个 **新的终端会话** 来工作在这个工程时,你都需要执行这个操作。 + +/// + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +或者,如果你在 Windows 上使用 Bash(例如 Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +/// tip + +每次你在这个环境中安装一个 **新的包** 时,都需要 **重新激活** 这个环境。 + +这么做确保了当你使用一个由这个包安装的 **终端(CLI)程序** 时,你使用的是你的虚拟环境中的程序,而不是全局安装、可能版本不同的程序。 + +/// + +## 检查虚拟环境是否激活 + +检查虚拟环境是否激活 (前面的命令是否生效)。 + +/// tip + +这是 **可选的**,但这是一个很好的方法,可以 **检查** 一切是否按预期工作,以及你是否使用了你打算使用的虚拟环境。 + +/// + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +如果它显示了在你工程 (在这个例子中是 `awesome-project`) 的 `.venv/bin/python` 中的 `python` 二进制文件,那么它就生效了。🎉 + +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +如果它显示了在你工程 (在这个例子中是 `awesome-project`) 的 `.venv\Scripts\python` 中的 `python` 二进制文件,那么它就生效了。🎉 + +//// + +## 升级 `pip` + +/// tip + +如果你使用 `uv` 来安装内容,而不是 `pip`,那么你就不需要升级 `pip`。😎 + +/// + +如果你使用 `pip` 来安装包(它是 Python 的默认组件),你应该将它 **升级** 到最新版本。 + +在安装包时出现的许多奇怪的错误都可以通过先升级 `pip` 来解决。 + +/// tip + +通常你只需要在创建虚拟环境后 **执行一次** 这个操作。 + +/// + +确保虚拟环境是激活的 (使用上面的命令),然后运行: + +
+ +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
+ +## 添加 `.gitignore` + +如果你使用 **Git** (这是你应该使用的),添加一个 `.gitignore` 文件来排除你的 `.venv` 中的所有内容。 + +/// tip + +如果你使用 `uv` 来创建虚拟环境,它会自动为你完成这个操作,你可以跳过这一步。😎 + +/// + +/// tip + +通常你只需要在创建虚拟环境后 **执行一次** 这个操作。 + +/// + +
+ +```console +$ echo "*" > .venv/.gitignore +``` + +
+ +/// details | 上述命令的含义 + +* `echo "*"`: 将在终端中 "打印" 文本 `*`(接下来的部分会对这个操作进行一些修改) +* `>`: 使左边的命令打印到终端的任何内容实际上都不会被打印,而是会被写入到右边的文件中 +* `.gitignore`: 被写入文本的文件的名称 + +而 `*` 对于 Git 来说意味着 "所有内容"。所以,它会忽略 `.venv` 目录中的所有内容。 + +该命令会创建一个名为 `.gitignore` 的文件,内容如下: + +```gitignore +* +``` + +/// + +## 安装软件包 + +在激活虚拟环境后,你可以在其中安装软件包。 + +/// tip + +当你需要安装或升级软件包时,执行本操作**一次**; + +如果你需要再升级版本或添加新软件包,你可以**再次执行此操作**。 + +/// + +### 直接安装包 + +如果你急于安装,不想使用文件来声明工程的软件包依赖,您可以直接安装它们。 + +/// tip + +将程序所需的软件包及其版本放在文件中(例如 `requirements.txt` 或 `pyproject.toml`)是个好(并且非常好)的主意。 + +/// + +//// tab | `pip` + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +如果你有 `uv`: + +
+ +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
+ +//// + +### 从 `requirements.txt` 安装 + +如果你有一个 `requirements.txt` 文件,你可以使用它来安装其中的软件包。 + +//// tab | `pip` + +
+ +```console +$ pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +如果你有 `uv`: + +
+ +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +/// details | 关于 `requirements.txt` + +一个包含一些软件包的 `requirements.txt` 文件看起来应该是这样的: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## 运行程序 + +在你激活虚拟环境后,你可以运行你的程序,它将使用虚拟环境中的 Python 和你在其中安装的软件包。 + +
+ +```console +$ python main.py + +Hello World +``` + +
+ +## 配置编辑器 + +你可能会用到编辑器(即 IDE —— 译者注),请确保配置它使用与你创建的相同的虚拟环境(它可能会自动检测到),以便你可以获得自动补全和内联错误提示。 + +例如: + +* VS Code +* PyCharm + +/// tip + +通常你只需要在创建虚拟环境时执行此操作**一次**。 + +/// + +## 退出虚拟环境 + +当你完成工作后,你可以**退出**虚拟环境。 + +
+ +```console +$ deactivate +``` + +
+ +这样,当你运行 `python` 时,它不会尝试从安装了软件包的虚拟环境中运行。(即,它将不再会尝试从虚拟环境中运行,也不会使用其中安装的软件包。—— 译者注) + +## 开始工作 + +现在你已经准备好开始你的工作了。 + + + +/// tip + +你想要理解上面的所有内容吗? + +继续阅读。👇🤓 + +/// + +## 为什么要使用虚拟环境 + +你需要安装 Python 才能使用 FastAPI。 + +之后,你需要**安装** FastAPI 和你想要使用的任何其他**软件包**。 + +要安装软件包,你通常会使用随 Python 一起提供的 `pip` 命令(或类似的替代方案)。 + +然而,如果你直接使用 `pip`,软件包将被安装在你的**全局 Python 环境**中(即 Python 的全局安装)。 + +### 存在的问题 + +那么,在全局 Python 环境中安装软件包有什么问题呢? + +有些时候,你可能会编写许多不同的程序,这些程序依赖于**不同的软件包**;你所做的一些工程也会依赖于**同一软件包的不同版本**。😱 + +例如,你可能会创建一个名为 `philosophers-stone` 的工程,这个程序依赖于另一个名为 **`harry` 的软件包,使用版本 `1`**。因此,你需要安装 `harry`。 + +```mermaid +flowchart LR + stone(philosophers-stone) -->|需要| harry-1[harry v1] +``` + +然而在此之后,你又创建了另一个名为 `prisoner-of-azkaban` 的工程,这个工程也依赖于 `harry`,但是这个工程需要 **`harry` 版本 `3`**。 + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |需要| harry-3[harry v3] +``` + +那么现在的问题是,如果你将软件包安装在全局环境中而不是在本地**虚拟环境**中,你将不得不面临选择安装哪个版本的 `harry` 的问题。 + +如果你想运行 `philosophers-stone`,你需要首先安装 `harry` 版本 `1`,例如: + +
+ +```console +$ pip install "harry==1" +``` + +
+ +然后你将在全局 Python 环境中安装 `harry` 版本 `1`。 + +```mermaid +flowchart LR + subgraph global[全局环境] + harry-1[harry v1] + end + subgraph stone-project[工程 philosophers-stone] + stone(philosophers-stone) -->|需要| harry-1 + end +``` + +但是如果你想运行 `prisoner-of-azkaban`,你需要卸载 `harry` 版本 `1` 并安装 `harry` 版本 `3`(或者说,只要你安装版本 `3` ,版本 `1` 就会自动卸载)。 + +
+ +```console +$ pip install "harry==3" +``` + +
+ +于是,你在你的全局 Python 环境中安装了 `harry` 版本 `3`。 + +如果你再次尝试运行 `philosophers-stone`,有可能它**无法正常工作**,因为它需要 `harry` 版本 `1`。 + +```mermaid +flowchart LR + subgraph global[全局环境] + harry-1[harry v1] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[工程 philosophers-stone] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[工程 prisoner-of-azkaban] + azkaban(prisoner-of-azkaban) --> |需要| harry-3 + end +``` + +/// tip + +Python 包在推出**新版本**时通常会尽量**避免破坏性更改**,但最好还是要小心,要想清楚再安装新版本,而且在运行测试以确保一切能正常工作时再安装。 + +/// + +现在,想象一下,如果有**许多**其他**软件包**,它们都是你的**工程所依赖的**。这是非常难以管理的。你可能会发现,有些工程使用了一些**不兼容的软件包版本**,而不知道为什么某些东西无法正常工作。 + +此外,取决于你的操作系统(例如 Linux、Windows、macOS),它可能已经预先安装了 Python。在这种情况下,它可能已经预先安装了一些软件包,这些软件包的特定版本是**系统所需的**。如果你在全局 Python 环境中安装软件包,你可能会**破坏**一些随操作系统一起安装的程序。 + +## 软件包安装在哪里 + +当你安装 Python 时,它会在你的计算机上创建一些目录,并在这些目录中放一些文件。 + +其中一些目录负责存放你安装的所有软件包。 + +当你运行: + +
+ +```console +// 先别去运行这个命令,这只是一个示例 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
+ +这将会从 PyPI 下载一个压缩文件,其中包含 FastAPI 代码。 + +它还会**下载** FastAPI 依赖的其他软件包的文件。 + +然后它会**解压**所有这些文件,并将它们放在你的计算机上的一个目录中。 + +默认情况下,它会将下载并解压的这些文件放在随 Python 安装的目录中,这就是**全局环境**。 + +## 什么是虚拟环境 + +解决软件包都安装在全局环境中的问题的方法是为你所做的每个工程使用一个**虚拟环境**。 + +虚拟环境是一个**目录**,与全局环境非常相似,你可以在其中专为某个工程安装软件包。 + +这样,每个工程都会有自己的虚拟环境(`.venv` 目录),其中包含自己的软件包。 + +```mermaid +flowchart TB + subgraph stone-project[工程 philosophers-stone] + stone(philosophers-stone) --->|需要| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[工程 prisoner-of-azkaban] + azkaban(prisoner-of-azkaban) --->|需要| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## 激活虚拟环境意味着什么 + +当你激活了一个虚拟环境,例如: + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +或者如果你在 Windows 上使用 Bash(例如 Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +这个命令会创建或修改一些[环境变量](environment-variables.md){.internal-link target=_blank},这些环境变量将在接下来的命令中可用。 + +其中之一是 `PATH` 变量。 + +/// tip + +你可以在 [环境变量](environment-variables.md#path-environment-variable){.internal-link target=_blank} 部分了解更多关于 `PATH` 环境变量的内容。 + +/// + +激活虚拟环境会将其路径 `.venv/bin`(在 Linux 和 macOS 上)或 `.venv\Scripts`(在 Windows 上)添加到 `PATH` 环境变量中。 + +假设在激活环境之前,`PATH` 变量看起来像这样: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +这意味着系统会在以下目录中查找程序: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +这意味着系统会在以下目录中查找程序: + +* `C:\Windows\System32` + +//// + +激活虚拟环境后,`PATH` 变量会变成这样: + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +这意味着系统现在会首先在以下目录中查找程序: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +然后再在其他目录中查找。 + +因此,当你在终端中输入 `python` 时,系统会在以下目录中找到 Python 程序: + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +并使用这个。 + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +这意味着系统现在会首先在以下目录中查找程序: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +然后再在其他目录中查找。 + +因此,当你在终端中输入 `python` 时,系统会在以下目录中找到 Python 程序: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +并使用这个。 + +//// + +一个重要的细节是,虚拟环境路径会被放在 `PATH` 变量的**开头**。系统会在找到任何其他可用的 Python **之前**找到它。这样,当你运行 `python` 时,它会使用**虚拟环境中**的 Python,而不是任何其他 `python`(例如,全局环境中的 `python`)。 + +激活虚拟环境还会改变其他一些东西,但这是它所做的最重要的事情之一。 + +## 检查虚拟环境 + +当你检查虚拟环境是否激活时,例如: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +//// + +这意味着将使用的 `python` 程序是**在虚拟环境中**的那个。 + +在 Linux 和 macOS 中使用 `which`,在 Windows PowerShell 中使用 `Get-Command`。 + +这个命令的工作方式是,它会在 `PATH` 环境变量中查找,按顺序**逐个路径**查找名为 `python` 的程序。一旦找到,它会**显示该程序的路径**。 + +最重要的部分是,当你调用 `python` 时,将执行的就是这个确切的 "`python`"。 + +因此,你可以确认你是否在正确的虚拟环境中。 + +/// tip + +激活一个虚拟环境,获取一个 Python,然后**转到另一个工程**是一件很容易的事情; + +但如果第二个工程**无法工作**,那是因为你使用了来自另一个工程的虚拟环境的、**不正确的 Python**。 + +因此,会检查正在使用的 `python` 是很有用的。🤓 + +/// + +## 为什么要停用虚拟环境 + +例如,你可能正在一个工程 `philosophers-stone` 上工作,**激活了该虚拟环境**,安装了包并使用了该环境, + +然后你想要在**另一个工程** `prisoner-of-azkaban` 上工作, + +你进入那个工程: + +
+ +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
+ +如果你不去停用 `philosophers-stone` 的虚拟环境,当你在终端中运行 `python` 时,它会尝试使用 `philosophers-stone` 中的 Python。 + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// 导入 sirius 报错,它没有安装 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
+ +但是如果你停用虚拟环境并激活 `prisoner-of-askaban` 的新虚拟环境,那么当你运行 `python` 时,它会使用 `prisoner-of-askaban` 中的虚拟环境中的 Python。 + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +// 你不需要在旧目录中操作停用,你可以在任何地方操作停用,甚至在转到另一个工程之后 😎 +$ deactivate + +// 激活 prisoner-of-azkaban/.venv 中的虚拟环境 🚀 +$ source .venv/bin/activate + +// 现在当你运行 python 时,它会在这个虚拟环境中找到安装的 sirius 包 ✨ +$ python main.py + +I solemnly swear 🐺 +``` + +
+ +## 替代方案 + +这是一个简单的指南,可以帮助你入门并教会你如何理解一切**底层**的东西。 + +有许多**替代方案**来管理虚拟环境、包依赖(requirements)、工程。 + +一旦你准备好并想要使用一个工具来**管理整个工程**、包依赖、虚拟环境等,建议你尝试 uv。 + +`uv` 可以做很多事情,它可以: + +* 为你**安装 Python**,包括不同的版本 +* 为你的工程管理**虚拟环境** +* 安装**软件包** +* 为你的工程管理软件包的**依赖和版本** +* 确保你有一个**确切**的软件包和版本集合来安装,包括它们的依赖项,这样你就可以确保在生产中运行你的工程与在开发时在你的计算机上运行的工程完全相同,这被称为**锁定** +* 还有很多其他功能 + +## 结论 + +如果你读过并理解了所有这些,现在**你对虚拟环境的了解比很多开发者都要多**。🤓 + +在未来当你调试看起来复杂的东西时,了解这些细节很可能会有用,你会知道**它是如何在底层工作的**。😎 From 4f430f49ace8153eb605a39919a03cfaba0127f4 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 8 Nov 2024 19:23:51 +0000 Subject: [PATCH 304/932] =?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 3764e2f96..718d1d57b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/virtual-environments.md`. PR [#12790](https://github.com/fastapi/fastapi/pull/12790) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Add Korean translation for `/docs/ko/docs/environment-variables.md`. PR [#12526](https://github.com/fastapi/fastapi/pull/12526) by [@Tolerblanc](https://github.com/Tolerblanc). * 🌐 Add Korean translation for `docs/ko/docs/history-design-future.md`. PR [#12646](https://github.com/fastapi/fastapi/pull/12646) by [@saeye](https://github.com/saeye). * 🌐 Add Korean translation for `docs/ko/docs/advanced/advanced-dependencies.md`. PR [#12675](https://github.com/fastapi/fastapi/pull/12675) by [@kim-sangah](https://github.com/kim-sangah). From 075f41bad98c46d483482f3dfd36b707a5f2895a Mon Sep 17 00:00:00 2001 From: LKY <74170199+kwang1215@users.noreply.github.com> Date: Sat, 9 Nov 2024 04:42:29 +0900 Subject: [PATCH 305/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`ko/docs/advanced/response-headers.md`=20(#12740)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/advanced/response-headers.md | 45 +++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 docs/ko/docs/advanced/response-headers.md diff --git a/docs/ko/docs/advanced/response-headers.md b/docs/ko/docs/advanced/response-headers.md new file mode 100644 index 000000000..54cf655c5 --- /dev/null +++ b/docs/ko/docs/advanced/response-headers.md @@ -0,0 +1,45 @@ +# 응답 헤더 + +## `Response` 매개변수 사용하기 + +여러분은 *경로 작동 함수*에서 `Response` 타입의 매개변수를 선언할 수 있습니다 (쿠키와 같이 사용할 수 있습니다). + +그런 다음, 여러분은 해당 *임시* 응답 객체에서 헤더를 설정할 수 있습니다. + +```Python hl_lines="1 7-8" +{!../../docs_src/response_headers/tutorial002.py!} +``` + +그 후, 일반적으로 사용하듯이 필요한 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다. + +`response_model`을 선언한 경우, 반환한 객체를 필터링하고 변환하는 데 여전히 사용됩니다. + +**FastAPI**는 해당 *임시* 응답에서 헤더(쿠키와 상태 코드도 포함)를 추출하여, 여러분이 반환한 값을 포함하는 최종 응답에 `response_model`로 필터링된 값을 넣습니다. + +또한, 종속성에서 `Response` 매개변수를 선언하고 그 안에서 헤더(및 쿠키)를 설정할 수 있습니다. + +## `Response` 직접 반환하기 + +`Response`를 직접 반환할 때에도 헤더를 추가할 수 있습니다. + +[응답을 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 설명한 대로 응답을 생성하고, 헤더를 추가 매개변수로 전달하세요. + +```Python hl_lines="10-12" +{!../../docs_src/response_headers/tutorial001.py!} +``` + +/// note | "기술적 세부사항" + +`from starlette.responses import Response`나 `from starlette.responses import JSONResponse`를 사용할 수도 있습니다. + +**FastAPI**는 `starlette.responses`를 `fastapi.responses`로 개발자의 편의를 위해 직접 제공하지만, 대부분의 응답은 Starlette에서 직접 제공됩니다. + +그리고 `Response`는 헤더와 쿠키를 설정하는 데 자주 사용될 수 있으므로, **FastAPI**는 `fastapi.Response`로도 이를 제공합니다. + +/// + +## 커스텀 헤더 + +‘X-’ 접두어를 사용하여 커스텀 사설 헤더를 추가할 수 있습니다. + +하지만, 여러분이 브라우저에서 클라이언트가 볼 수 있기를 원하는 커스텀 헤더가 있는 경우, CORS 설정에 이를 추가해야 합니다([CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}에서 자세히 알아보세요). `expose_headers` 매개변수를 사용하여 Starlette의 CORS 설명서에 문서화된 대로 설정할 수 있습니다. From b0fe5ebbf0aa129d9a4bcf60e7f0fc0b2828cf3c Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 8 Nov 2024 19:42:52 +0000 Subject: [PATCH 306/932] =?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 718d1d57b..972c096e3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `ko/docs/advanced/response-headers.md`. PR [#12740](https://github.com/fastapi/fastapi/pull/12740) by [@kwang1215](https://github.com/kwang1215). * 🌐 Add Chinese translation for `docs/zh/docs/virtual-environments.md`. PR [#12790](https://github.com/fastapi/fastapi/pull/12790) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Add Korean translation for `/docs/ko/docs/environment-variables.md`. PR [#12526](https://github.com/fastapi/fastapi/pull/12526) by [@Tolerblanc](https://github.com/Tolerblanc). * 🌐 Add Korean translation for `docs/ko/docs/history-design-future.md`. PR [#12646](https://github.com/fastapi/fastapi/pull/12646) by [@saeye](https://github.com/saeye). From 8cd47a3551a0bafd594b43963eedbedb5b81a370 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 8 Nov 2024 22:05:33 +0000 Subject: [PATCH 307/932] =?UTF-8?q?=E2=AC=86=20Bump=20tiangolo/latest-chan?= =?UTF-8?q?ges=20from=200.3.1=20to=200.3.2=20(#12794)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [tiangolo/latest-changes](https://github.com/tiangolo/latest-changes) from 0.3.1 to 0.3.2. - [Release notes](https://github.com/tiangolo/latest-changes/releases) - [Commits](https://github.com/tiangolo/latest-changes/compare/0.3.1...0.3.2) --- updated-dependencies: - dependency-name: tiangolo/latest-changes dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/latest-changes.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/latest-changes.yml b/.github/workflows/latest-changes.yml index 16da3bc63..b8b5c42ee 100644 --- a/.github/workflows/latest-changes.yml +++ b/.github/workflows/latest-changes.yml @@ -34,7 +34,7 @@ jobs: if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - - uses: tiangolo/latest-changes@0.3.1 + - uses: tiangolo/latest-changes@0.3.2 with: token: ${{ secrets.GITHUB_TOKEN }} latest_changes_file: docs/en/docs/release-notes.md From 858912e6e46a9a4d312ea2695a7d9afe50773be9 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 8 Nov 2024 22:06:00 +0000 Subject: [PATCH 308/932] =?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 [skip ci] --- 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 972c096e3..69f0c9c9e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -53,6 +53,7 @@ hide: ### Internal +* ⬆ Bump tiangolo/latest-changes from 0.3.1 to 0.3.2. PR [#12794](https://github.com/fastapi/fastapi/pull/12794) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pypa/gh-action-pypi-publish from 1.12.0 to 1.12.2. PR [#12788](https://github.com/fastapi/fastapi/pull/12788) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pypa/gh-action-pypi-publish from 1.11.0 to 1.12.0. PR [#12781](https://github.com/fastapi/fastapi/pull/12781) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump cloudflare/wrangler-action from 3.11 to 3.12. PR [#12777](https://github.com/fastapi/fastapi/pull/12777) by [@dependabot[bot]](https://github.com/apps/dependabot). From 855b4f66f51071f47581c2bce6643b3132ae60a1 Mon Sep 17 00:00:00 2001 From: Alissa <96190409+alissadb@users.noreply.github.com> Date: Sat, 9 Nov 2024 11:02:30 +0100 Subject: [PATCH 309/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/de/docs/how-to/configure-swagger-ui.md`=20(#12690)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/how-to/configure-swagger-ui.md | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/docs/de/docs/how-to/configure-swagger-ui.md b/docs/de/docs/how-to/configure-swagger-ui.md index 31b9cd290..1ee72d205 100644 --- a/docs/de/docs/how-to/configure-swagger-ui.md +++ b/docs/de/docs/how-to/configure-swagger-ui.md @@ -18,9 +18,7 @@ Ohne Änderung der Einstellungen ist die Syntaxhervorhebung standardmäßig akti Sie können sie jedoch deaktivieren, indem Sie `syntaxHighlight` auf `False` setzen: -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial001.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *} ... und dann zeigt die Swagger-Oberfläche die Syntaxhervorhebung nicht mehr an: @@ -30,9 +28,7 @@ Sie können sie jedoch deaktivieren, indem Sie `syntaxHighlight` auf `False` set Auf die gleiche Weise könnten Sie das Theme der Syntaxhervorhebung mit dem Schlüssel `syntaxHighlight.theme` festlegen (beachten Sie, dass er einen Punkt in der Mitte hat): -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial002.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *} Obige Konfiguration würde das Theme für die Farbe der Syntaxhervorhebung ändern: @@ -44,17 +40,13 @@ FastAPI enthält einige Defaultkonfigurationsparameter, die für die meisten Anw Es umfasst die folgenden Defaultkonfigurationen: -```Python -{!../../fastapi/openapi/docs.py[ln:7-23]!} -``` +{* ../../fastapi/openapi/docs.py ln[7:23] *} Sie können jede davon überschreiben, indem Sie im Argument `swagger_ui_parameters` einen anderen Wert festlegen. Um beispielsweise `deepLinking` zu deaktivieren, könnten Sie folgende Einstellungen an `swagger_ui_parameters` übergeben: -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial003.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *} ## Andere Parameter der Swagger-Oberfläche From 561803520305f5faf6bdc23eef311561d6ee3a24 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 10:02:55 +0000 Subject: [PATCH 310/932] =?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 [skip ci] --- 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 69f0c9c9e..ad76badbe 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/de/docs/how-to/configure-swagger-ui.md`. PR [#12690](https://github.com/fastapi/fastapi/pull/12690) by [@alissadb](https://github.com/alissadb). * 📝 Update includes in `docs/en/docs/advanced/security/oauth2-scopes.md`. PR [#12572](https://github.com/fastapi/fastapi/pull/12572) by [@krishnamadhavan](https://github.com/krishnamadhavan). * 📝 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). From 1e9ea61cbd6c11d673df4317ef9af20759d650ea Mon Sep 17 00:00:00 2001 From: Quentin Takeda Date: Sat, 9 Nov 2024 11:08:25 +0100 Subject: [PATCH 311/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/fr/docs/tutorial/path-params.md`=20(#12592)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/fr/docs/tutorial/path-params.md | 36 +++++++--------------------- 1 file changed, 9 insertions(+), 27 deletions(-) diff --git a/docs/fr/docs/tutorial/path-params.md b/docs/fr/docs/tutorial/path-params.md index 34012c278..508529fae 100644 --- a/docs/fr/docs/tutorial/path-params.md +++ b/docs/fr/docs/tutorial/path-params.md @@ -4,9 +4,7 @@ Vous pouvez déclarer des "paramètres" ou "variables" de chemin avec la même s formatage de chaîne Python : -```Python hl_lines="6-7" -{!../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} La valeur du paramètre `item_id` sera transmise à la fonction dans l'argument `item_id`. @@ -22,9 +20,7 @@ vous verrez comme réponse : Vous pouvez déclarer le type d'un paramètre de chemin dans la fonction, en utilisant les annotations de type Python : -```Python hl_lines="7" -{!../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} Ici, `item_id` est déclaré comme `int`. @@ -131,9 +127,7 @@ Et vous avez un second chemin : `/users/{user_id}` pour récupérer de la donné Les *fonctions de chemin* étant évaluées dans l'ordre, il faut s'assurer que la fonction correspondant à `/users/me` est déclarée avant celle de `/users/{user_id}` : -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} Sinon, le chemin `/users/{user_id}` correspondrait aussi à `/users/me`, la fonction "croyant" qu'elle a reçu un paramètre `user_id` avec pour valeur `"me"`. @@ -149,9 +143,7 @@ En héritant de `str` la documentation sera capable de savoir que les valeurs do Créez ensuite des attributs de classe avec des valeurs fixes, qui seront les valeurs autorisées pour cette énumération. -```Python hl_lines="1 6-9" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} /// info @@ -169,9 +161,7 @@ Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms Créez ensuite un *paramètre de chemin* avec une annotation de type désignant l'énumération créée précédemment (`ModelName`) : -```Python hl_lines="16" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### Documentation @@ -187,17 +177,13 @@ La valeur du *paramètre de chemin* sera un des "membres" de l'énumération. Vous pouvez comparer ce paramètre avec les membres de votre énumération `ModelName` : -```Python hl_lines="17" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### Récupérer la *valeur de l'énumération* Vous pouvez obtenir la valeur réel d'un membre (une chaîne de caractères ici), avec `model_name.value`, ou en général, `votre_membre_d'enum.value` : -```Python hl_lines="20" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} /// tip | "Astuce" @@ -211,9 +197,7 @@ Vous pouvez retourner des *membres d'énumération* dans vos *fonctions de chemi Ils seront convertis vers leurs valeurs correspondantes (chaînes de caractères ici) avant d'être transmis au client : -```Python hl_lines="18 21 23" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} Le client recevra une réponse JSON comme celle-ci : @@ -252,9 +236,7 @@ Dans ce cas, le nom du paramètre est `file_path`, et la dernière partie, `:pat Vous pouvez donc l'utilisez comme tel : -```Python hl_lines="6" -{!../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} /// tip | "Astuce" From ee260368d005339de963f9f05697dd2ad03e05b6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 10:08:49 +0000 Subject: [PATCH 312/932] =?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 [skip ci] --- 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 ad76badbe..dcf3c66ef 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.md`. PR [#12592](https://github.com/fastapi/fastapi/pull/12592) by [@kantandane](https://github.com/kantandane). * 📝 Update includes for `docs/de/docs/how-to/configure-swagger-ui.md`. PR [#12690](https://github.com/fastapi/fastapi/pull/12690) by [@alissadb](https://github.com/alissadb). * 📝 Update includes in `docs/en/docs/advanced/security/oauth2-scopes.md`. PR [#12572](https://github.com/fastapi/fastapi/pull/12572) by [@krishnamadhavan](https://github.com/krishnamadhavan). * 📝 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). From af280dbde9d12f0bf212c35e181a6a15531ee25c Mon Sep 17 00:00:00 2001 From: Alissa <96190409+alissadb@users.noreply.github.com> Date: Sat, 9 Nov 2024 11:12:35 +0100 Subject: [PATCH 313/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/de/docs/advanced/dataclasses.md`=20(#12658)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/dataclasses.md | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/docs/de/docs/advanced/dataclasses.md b/docs/de/docs/advanced/dataclasses.md index 573f500e8..8e537c639 100644 --- a/docs/de/docs/advanced/dataclasses.md +++ b/docs/de/docs/advanced/dataclasses.md @@ -4,9 +4,7 @@ FastAPI basiert auf **Pydantic** und ich habe Ihnen gezeigt, wie Sie Pydantic-Mo Aber FastAPI unterstützt auf die gleiche Weise auch die Verwendung von `dataclasses`: -```Python hl_lines="1 7-12 19-20" -{!../../docs_src/dataclasses/tutorial001.py!} -``` +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} Das ist dank **Pydantic** ebenfalls möglich, da es `dataclasses` intern unterstützt. @@ -34,9 +32,7 @@ Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Tr Sie können `dataclasses` auch im Parameter `response_model` verwenden: -```Python hl_lines="1 7-13 19" -{!../../docs_src/dataclasses/tutorial002.py!} -``` +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} Die Datenklasse wird automatisch in eine Pydantic-Datenklasse konvertiert. @@ -52,9 +48,7 @@ In einigen Fällen müssen Sie möglicherweise immer noch Pydantics Version von In diesem Fall können Sie einfach die Standard-`dataclasses` durch `pydantic.dataclasses` ersetzen, was einen direkten Ersatz darstellt: -```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } -{!../../docs_src/dataclasses/tutorial003.py!} -``` +{* ../../docs_src/dataclasses/tutorial003.py hl[1,5,8:11,14:17,23:25,28] *} 1. Wir importieren `field` weiterhin von Standard-`dataclasses`. From 546bb50e091e603d5eea33870ed65982e56c230f Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 10:12:55 +0000 Subject: [PATCH 314/932] =?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 [skip ci] --- 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 dcf3c66ef..04b06a359 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/de/docs/advanced/dataclasses.md`. PR [#12658](https://github.com/fastapi/fastapi/pull/12658) by [@alissadb](https://github.com/alissadb). * 📝 Update includes in `docs/fr/docs/tutorial/path-params.md`. PR [#12592](https://github.com/fastapi/fastapi/pull/12592) by [@kantandane](https://github.com/kantandane). * 📝 Update includes for `docs/de/docs/how-to/configure-swagger-ui.md`. PR [#12690](https://github.com/fastapi/fastapi/pull/12690) by [@alissadb](https://github.com/alissadb). * 📝 Update includes in `docs/en/docs/advanced/security/oauth2-scopes.md`. PR [#12572](https://github.com/fastapi/fastapi/pull/12572) by [@krishnamadhavan](https://github.com/krishnamadhavan). From 890a61fb67e24b7262a4dfee106d9bdb715a9ab1 Mon Sep 17 00:00:00 2001 From: Alissa <96190409+alissadb@users.noreply.github.com> Date: Sat, 9 Nov 2024 11:15:47 +0100 Subject: [PATCH 315/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/de/docs/python-types.md`=20(#12660)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/python-types.md | 44 +++++++++--------------------------- 1 file changed, 11 insertions(+), 33 deletions(-) diff --git a/docs/de/docs/python-types.md b/docs/de/docs/python-types.md index a43bf5ffe..a9ab4beab 100644 --- a/docs/de/docs/python-types.md +++ b/docs/de/docs/python-types.md @@ -22,9 +22,7 @@ Wenn Sie ein Python-Experte sind und bereits alles über Typhinweise wissen, üb Fangen wir mit einem einfachen Beispiel an: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} Dieses Programm gibt aus: @@ -38,9 +36,7 @@ Die Funktion macht Folgendes: * Schreibt den ersten Buchstaben eines jeden Wortes groß, mithilfe von `title()`. * Verkettet sie mit einem Leerzeichen in der Mitte. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} ### Bearbeiten Sie es @@ -82,9 +78,7 @@ Das war's. Das sind die „Typhinweise“: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} Das ist nicht das gleiche wie das Deklarieren von Defaultwerten, wie es hier der Fall ist: @@ -112,9 +106,7 @@ Hier können Sie durch die Optionen blättern, bis Sie diejenige finden, bei der Sehen Sie sich diese Funktion an, sie hat bereits Typhinweise: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervollständigung, sondern auch eine Fehlerprüfung: @@ -122,9 +114,7 @@ Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervoll Jetzt, da Sie wissen, dass Sie das reparieren müssen, konvertieren Sie `age` mittels `str(age)` in einen String: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} ## Deklarieren von Typen @@ -143,9 +133,7 @@ Zum Beispiel diese: * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} ### Generische Typen mit Typ-Parametern @@ -320,9 +308,7 @@ Sie können deklarieren, dass ein Wert ein `str`, aber vielleicht auch `None` se In Python 3.6 und darüber (inklusive Python 3.10) können Sie das deklarieren, indem Sie `Optional` vom `typing` Modul importieren und verwenden. -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009.py!} -``` +{* ../../docs_src/python_types/tutorial009.py hl[1,4] *} Wenn Sie `Optional[str]` anstelle von nur `str` verwenden, wird Ihr Editor Ihnen dabei helfen, Fehler zu erkennen, bei denen Sie annehmen könnten, dass ein Wert immer eine String (`str`) ist, obwohl er auch `None` sein könnte. @@ -369,9 +355,7 @@ Es geht nur um Wörter und Namen. Aber diese Worte können beeinflussen, wie Sie Nehmen wir zum Beispiel diese Funktion: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c.py!} -``` +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} Der Parameter `name` ist definiert als `Optional[str]`, aber er ist **nicht optional**, Sie können die Funktion nicht ohne diesen Parameter aufrufen: @@ -387,9 +371,7 @@ say_hi(name=None) # Das funktioniert, None is gültig 🎉 Die gute Nachricht ist, dass Sie sich darüber keine Sorgen mehr machen müssen, wenn Sie Python 3.10 verwenden, da Sie einfach `|` verwenden können, um Vereinigungen von Typen zu definieren: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c_py310.py!} -``` +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} Und dann müssen Sie sich nicht mehr um Namen wie `Optional` und `Union` kümmern. 😎 @@ -451,15 +433,11 @@ Sie können auch eine Klasse als Typ einer Variablen deklarieren. Nehmen wir an, Sie haben eine Klasse `Person`, mit einem Namen: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} Dann können Sie eine Variable vom Typ `Person` deklarieren: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} Und wiederum bekommen Sie die volle Editor-Unterstützung: From ce97de97d9d77d2f6671f8b7527e3db2163e3448 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 10:16:07 +0000 Subject: [PATCH 316/932] =?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 [skip ci] --- 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 04b06a359..58c21a482 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/de/docs/python-types.md`. PR [#12660](https://github.com/fastapi/fastapi/pull/12660) by [@alissadb](https://github.com/alissadb). * 📝 Update includes for `docs/de/docs/advanced/dataclasses.md`. PR [#12658](https://github.com/fastapi/fastapi/pull/12658) by [@alissadb](https://github.com/alissadb). * 📝 Update includes in `docs/fr/docs/tutorial/path-params.md`. PR [#12592](https://github.com/fastapi/fastapi/pull/12592) by [@kantandane](https://github.com/kantandane). * 📝 Update includes for `docs/de/docs/how-to/configure-swagger-ui.md`. PR [#12690](https://github.com/fastapi/fastapi/pull/12690) by [@alissadb](https://github.com/alissadb). From 51fe0e437b05185bb677583d023f17533d9509e7 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Sat, 9 Nov 2024 07:32:53 -0300 Subject: [PATCH 317/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/pt/docs/python-types.md`=20(#12671)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/python-types.md | 42 ++++++++++-------------------------- 1 file changed, 11 insertions(+), 31 deletions(-) diff --git a/docs/pt/docs/python-types.md b/docs/pt/docs/python-types.md index a0938259f..90a361f40 100644 --- a/docs/pt/docs/python-types.md +++ b/docs/pt/docs/python-types.md @@ -22,9 +22,7 @@ Se você é um especialista em Python e já sabe tudo sobre type hints, pule par Vamos começar com um exemplo simples: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} A chamada deste programa gera: @@ -38,9 +36,7 @@ A função faz o seguinte: * Converte a primeira letra de cada uma em maiúsculas com `title()`. * Concatena com um espaço no meio. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} ### Edite-o @@ -82,9 +78,7 @@ para: Esses são os "type hints": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} Isso não é o mesmo que declarar valores padrão como seria com: @@ -112,9 +106,7 @@ Com isso, você pode rolar, vendo as opções, até encontrar o que "soa familia Verifique esta função, ela já possui type hints: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} Como o editor conhece os tipos de variáveis, você não obtém apenas o preenchimento automático, mas também as verificações de erro: @@ -122,9 +114,7 @@ Como o editor conhece os tipos de variáveis, você não obtém apenas o preench Agora você sabe que precisa corrigí-lo, converta `age` em uma string com `str(age)`: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} ## Declarando Tipos @@ -143,9 +133,7 @@ Você pode usar, por exemplo: * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} ### Tipos genéricos com parâmetros de tipo @@ -321,7 +309,7 @@ Você pode declarar que um valor pode ter um tipo, como `str`, mas que ele tamb No Python 3.6 e superior (incluindo o Python 3.10) você pode declará-lo importando e utilizando `Optional` do módulo `typing`. -```Python hl_lines="1 4" +```Python hl_lines="1 4" {!../../docs_src/python_types/tutorial009.py!} ``` @@ -370,9 +358,7 @@ Isso é apenas sobre palavras e nomes. Mas estas palavras podem afetar como os s Por exemplo, vamos pegar esta função: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c.py!} -``` +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} O paâmetro `name` é definido como `Optional[str]`, mas ele **não é opcional**, você não pode chamar a função sem o parâmetro: @@ -388,9 +374,7 @@ say_hi(name=None) # This works, None is valid 🎉 A boa notícia é, quando você estiver no Python 3.10 você não precisará se preocupar mais com isso, pois você poderá simplesmente utilizar o `|` para definir uniões de tipos: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c_py310.py!} -``` +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} E então você não precisará mais se preocupar com nomes como `Optional` e `Union`. 😎 @@ -452,15 +436,11 @@ Você também pode declarar uma classe como o tipo de uma variável. Digamos que você tenha uma classe `Person`, com um nome: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} Então você pode declarar que uma variável é do tipo `Person`: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} E então, novamente, você recebe todo o suporte do editor: From 92a5f68e4db675e552aa127bbb43eeb958023e17 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 10:33:21 +0000 Subject: [PATCH 318/932] =?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 [skip ci] --- 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 58c21a482..29c33a362 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/pt/docs/python-types.md`. PR [#12671](https://github.com/fastapi/fastapi/pull/12671) by [@ceb10n](https://github.com/ceb10n). * 📝 Update includes for `docs/de/docs/python-types.md`. PR [#12660](https://github.com/fastapi/fastapi/pull/12660) by [@alissadb](https://github.com/alissadb). * 📝 Update includes for `docs/de/docs/advanced/dataclasses.md`. PR [#12658](https://github.com/fastapi/fastapi/pull/12658) by [@alissadb](https://github.com/alissadb). * 📝 Update includes in `docs/fr/docs/tutorial/path-params.md`. PR [#12592](https://github.com/fastapi/fastapi/pull/12592) by [@kantandane](https://github.com/kantandane). From 1cfd9a70ac0b63b42e0d6acec31e41422ca7b7f6 Mon Sep 17 00:00:00 2001 From: Baldeep Singh Handa Date: Sat, 9 Nov 2024 10:44:28 +0000 Subject: [PATCH 319/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/advanced/custom-response.md`=20(#12797)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/custom-response.md | 64 ++++++------------------ 1 file changed, 16 insertions(+), 48 deletions(-) diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index 1d6dc3f6d..95152b9fe 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -30,9 +30,7 @@ This is because by default, FastAPI will inspect every item inside and make sure But if you are certain that the content that you are returning is **serializable with JSON**, you can pass it directly to the response class and avoid the extra overhead that FastAPI would have by passing your return content through the `jsonable_encoder` before passing it to the response class. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} /// info @@ -57,9 +55,7 @@ To return a response with HTML directly from **FastAPI**, use `HTMLResponse`. * Import `HTMLResponse`. * Pass `HTMLResponse` as the parameter `response_class` of your *path operation decorator*. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial002.py!} -``` +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} /// info @@ -77,9 +73,7 @@ As seen in [Return a Response directly](response-directly.md){.internal-link tar The same example from above, returning an `HTMLResponse`, could look like: -```Python hl_lines="2 7 19" -{!../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} /// warning @@ -103,9 +97,7 @@ The `response_class` will then be used only to document the OpenAPI *path operat For example, it could be something like: -```Python hl_lines="7 21 23" -{!../../docs_src/custom_response/tutorial004.py!} -``` +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} In this example, the function `generate_html_response()` already generates and returns a `Response` instead of returning the HTML in a `str`. @@ -144,9 +136,7 @@ It accepts the following parameters: FastAPI (actually Starlette) will automatically include a Content-Length header. It will also include a Content-Type header, based on the `media_type` and appending a charset for text types. -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ### `HTMLResponse` @@ -156,9 +146,7 @@ Takes some text or bytes and returns an HTML response, as you read above. Takes some text or bytes and returns a plain text response. -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial005.py!} -``` +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} ### `JSONResponse` @@ -192,9 +180,7 @@ This requires installing `ujson` for example with `pip install ujson`. /// -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001.py!} -``` +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} /// tip @@ -208,18 +194,14 @@ Returns an HTTP redirect. Uses a 307 status code (Temporary Redirect) by default You can return a `RedirectResponse` directly: -```Python hl_lines="2 9" -{!../../docs_src/custom_response/tutorial006.py!} -``` +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} --- Or you can use it in the `response_class` parameter: -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial006b.py!} -``` +{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *} If you do that, then you can return the URL directly from your *path operation* function. @@ -229,17 +211,13 @@ In this case, the `status_code` used will be the default one for the `RedirectRe You can also use the `status_code` parameter combined with the `response_class` parameter: -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial006c.py!} -``` +{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *} ### `StreamingResponse` Takes an async generator or a normal generator/iterator and streams the response body. -```Python hl_lines="2 14" -{!../../docs_src/custom_response/tutorial007.py!} -``` +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} #### Using `StreamingResponse` with file-like objects @@ -249,9 +227,7 @@ That way, you don't have to read it all first in memory, and you can pass that g This includes many libraries to interact with cloud storage, video processing, and others. -```{ .python .annotate hl_lines="2 10-12 14" } -{!../../docs_src/custom_response/tutorial008.py!} -``` +{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *} 1. This is the generator function. It's a "generator function" because it contains `yield` statements inside. 2. By using a `with` block, we make sure that the file-like object is closed after the generator function is done. So, after it finishes sending the response. @@ -280,15 +256,11 @@ Takes a different set of arguments to instantiate than the other response types: File responses will include appropriate `Content-Length`, `Last-Modified` and `ETag` headers. -```Python hl_lines="2 10" -{!../../docs_src/custom_response/tutorial009.py!} -``` +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} You can also use the `response_class` parameter: -```Python hl_lines="2 8 10" -{!../../docs_src/custom_response/tutorial009b.py!} -``` +{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *} In this case, you can return the file path directly from your *path operation* function. @@ -302,9 +274,7 @@ Let's say you want it to return indented and formatted JSON, so you want to use You could create a `CustomORJSONResponse`. The main thing you have to do is create a `Response.render(content)` method that returns the content as `bytes`: -```Python hl_lines="9-14 17" -{!../../docs_src/custom_response/tutorial009c.py!} -``` +{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *} Now instead of returning: @@ -330,9 +300,7 @@ The parameter that defines this is `default_response_class`. In the example below, **FastAPI** will use `ORJSONResponse` by default, in all *path operations*, instead of `JSONResponse`. -```Python hl_lines="2 4" -{!../../docs_src/custom_response/tutorial010.py!} -``` +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} /// tip From 4733cc74864003cd79c883f81ff5717bb6c68fc7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 10:44:54 +0000 Subject: [PATCH 320/932] =?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 [skip ci] --- 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 29c33a362..17a287571 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/advanced/custom-response.md`. PR [#12797](https://github.com/fastapi/fastapi/pull/12797) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes for `docs/pt/docs/python-types.md`. PR [#12671](https://github.com/fastapi/fastapi/pull/12671) by [@ceb10n](https://github.com/ceb10n). * 📝 Update includes for `docs/de/docs/python-types.md`. PR [#12660](https://github.com/fastapi/fastapi/pull/12660) by [@alissadb](https://github.com/alissadb). * 📝 Update includes for `docs/de/docs/advanced/dataclasses.md`. PR [#12658](https://github.com/fastapi/fastapi/pull/12658) by [@alissadb](https://github.com/alissadb). From 5b2bd906d7af3c5ba1c04c20741352b0cbcf7a72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A9lix?= <49922137+bhunao@users.noreply.github.com> Date: Sat, 9 Nov 2024 07:55:35 -0300 Subject: [PATCH 321/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/pt/docs/tutorial/background-tasks.md`=20(#12736)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/background-tasks.md | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/docs/pt/docs/tutorial/background-tasks.md b/docs/pt/docs/tutorial/background-tasks.md index 2b5f82464..6a69ae2af 100644 --- a/docs/pt/docs/tutorial/background-tasks.md +++ b/docs/pt/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ Isso inclui, por exemplo: Primeiro, importe `BackgroundTasks` e defina um parâmetro em sua _função de operação de caminho_ com uma declaração de tipo de `BackgroundTasks`: -```Python hl_lines="1 13" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} O **FastAPI** criará o objeto do tipo `BackgroundTasks` para você e o passará como esse parâmetro. @@ -33,17 +31,13 @@ Nesse caso, a função de tarefa gravará em um arquivo (simulando o envio de um E como a operação de gravação não usa `async` e `await`, definimos a função com `def` normal: -```Python hl_lines="6-9" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## Adicionar a tarefa em segundo plano Dentro de sua _função de operação de caminho_, passe sua função de tarefa para o objeto _tarefas em segundo plano_ com o método `.add_task()`: -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` recebe como argumentos: @@ -57,9 +51,7 @@ Usar `BackgroundTasks` também funciona com o sistema de injeção de dependênc O **FastAPI** sabe o que fazer em cada caso e como reutilizar o mesmo objeto, de forma que todas as tarefas em segundo plano sejam mescladas e executadas em segundo plano posteriormente: -```Python hl_lines="13 15 22 25" -{!../../docs_src/background_tasks/tutorial002.py!} -``` +{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *} Neste exemplo, as mensagens serão gravadas no arquivo `log.txt` _após_ o envio da resposta. From 6d066c0d62d8ac8c0953658f4086571e03a464ff Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 10:56:01 +0000 Subject: [PATCH 322/932] =?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 [skip ci] --- 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 17a287571..a55e8cecd 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/tutorial/background-tasks.md`. PR [#12736](https://github.com/fastapi/fastapi/pull/12736) by [@bhunao](https://github.com/bhunao). * 📝 Update includes for `docs/en/docs/advanced/custom-response.md`. PR [#12797](https://github.com/fastapi/fastapi/pull/12797) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes for `docs/pt/docs/python-types.md`. PR [#12671](https://github.com/fastapi/fastapi/pull/12671) by [@ceb10n](https://github.com/ceb10n). * 📝 Update includes for `docs/de/docs/python-types.md`. PR [#12660](https://github.com/fastapi/fastapi/pull/12660) by [@alissadb](https://github.com/alissadb). From 83d7f114051385edf95a9f343b5e1eab34cb663d Mon Sep 17 00:00:00 2001 From: Tashanam Shahbaz <64039299+Tashanam-Shahbaz@users.noreply.github.com> Date: Sat, 9 Nov 2024 16:08:12 +0500 Subject: [PATCH 323/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/tutorial/body-multiple-params.md`=20(#12593)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/body-multiple-params.md | 220 +----------------- 1 file changed, 6 insertions(+), 214 deletions(-) diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md index eebbb3fe4..9fced9652 100644 --- a/docs/en/docs/tutorial/body-multiple-params.md +++ b/docs/en/docs/tutorial/body-multiple-params.md @@ -8,57 +8,9 @@ First, of course, you can mix `Path`, `Query` and request body parameter declara And you can also declare body parameters as optional, by setting the default to `None`: -//// tab | Python 3.10+ +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17-19" -{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001.py!} -``` - -//// +## Multiple body parameters /// note @@ -81,21 +33,8 @@ In the previous example, the *path operations* would expect a JSON body with the But you can also declare multiple body parameters, e.g. `item` and `user`: -//// tab | Python 3.10+ - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial002.py!} -``` - -//// In this case, **FastAPI** will notice that there is more than one body parameter in the function (there are two parameters that are Pydantic models). @@ -136,57 +75,8 @@ If you declare it as is, because it is a singular value, **FastAPI** will assume But you can instruct **FastAPI** to treat it as another body key using `Body`: -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial003.py!} -``` - -//// In this case, **FastAPI** will expect a body like: @@ -226,57 +116,8 @@ q: str | None = None For example: -//// tab | Python 3.10+ - -```Python hl_lines="28" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="28" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="29" -{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *} -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="26" -{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="28" -{!> ../../docs_src/body_multiple_params/tutorial004.py!} -``` - -//// /// info @@ -298,57 +139,8 @@ item: Item = Body(embed=True) as in: -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} -//// In this case **FastAPI** will expect a body like: From c1110d529e54aae58a38192c70757f003f31e4ba Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 11:08:32 +0000 Subject: [PATCH 324/932] =?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 [skip ci] --- 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 a55e8cecd..04d596fb5 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-multiple-params.md`. PR [#12593](https://github.com/fastapi/fastapi/pull/12593) by [@Tashanam-Shahbaz](https://github.com/Tashanam-Shahbaz). * 📝 Update includes in `docs/pt/docs/tutorial/background-tasks.md`. PR [#12736](https://github.com/fastapi/fastapi/pull/12736) by [@bhunao](https://github.com/bhunao). * 📝 Update includes for `docs/en/docs/advanced/custom-response.md`. PR [#12797](https://github.com/fastapi/fastapi/pull/12797) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes for `docs/pt/docs/python-types.md`. PR [#12671](https://github.com/fastapi/fastapi/pull/12671) by [@ceb10n](https://github.com/ceb10n). From 150f8225b2eb03ed68846e3618b3af4a7a7d64d6 Mon Sep 17 00:00:00 2001 From: Quentin Takeda Date: Sat, 9 Nov 2024 12:10:17 +0100 Subject: [PATCH 325/932] =?UTF-8?q?=F0=9F=93=9D=20=20Update=20includes=20i?= =?UTF-8?q?n=20`docs/fr/docs/tutorial/body-multiple-params.md`=20(#12598)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/fr/docs/tutorial/body-multiple-params.md | 223 +----------------- 1 file changed, 5 insertions(+), 218 deletions(-) diff --git a/docs/fr/docs/tutorial/body-multiple-params.md b/docs/fr/docs/tutorial/body-multiple-params.md index dafd869e3..0541acc74 100644 --- a/docs/fr/docs/tutorial/body-multiple-params.md +++ b/docs/fr/docs/tutorial/body-multiple-params.md @@ -8,57 +8,7 @@ Tout d'abord, sachez que vous pouvez mélanger les déclarations des paramètres Vous pouvez également déclarer des paramètres body comme étant optionnels, en leur assignant une valeur par défaut à `None` : -//// tab | Python 3.10+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="17-19" -{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} /// note @@ -81,21 +31,7 @@ Dans l'exemple précédent, les opérations de routage attendaient un body JSON Mais vous pouvez également déclarer plusieurs paramètres provenant de body, par exemple `item` et `user` simultanément : -//// tab | Python 3.10+ - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} Dans ce cas, **FastAPI** détectera qu'il y a plus d'un paramètre dans le body (chacun correspondant à un modèle Pydantic). @@ -135,57 +71,8 @@ Par exemple, en étendant le modèle précédent, vous pouvez vouloir ajouter un Si vous le déclarez tel quel, comme c'est une valeur [scalaire](https://docs.github.com/fr/graphql/reference/scalars), **FastAPI** supposera qu'il s'agit d'un paramètre de requête (`Query`). Mais vous pouvez indiquer à **FastAPI** de la traiter comme une variable de body en utilisant `Body` : -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial003.py!} -``` -//// +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} Dans ce cas, **FastAPI** s'attendra à un body semblable à : @@ -225,57 +112,7 @@ q: str | None = None Par exemple : -//// tab | Python 3.10+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="28" -{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="25" -{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *} /// info @@ -297,57 +134,7 @@ item: Item = Body(embed=True) Voici un exemple complet : -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Préférez utiliser la version `Annotated` si possible. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} Dans ce cas **FastAPI** attendra un body semblable à : From 38141dbc9f3bf5613471b61525a6fe7c201a4e71 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 11:12:50 +0000 Subject: [PATCH 326/932] =?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 [skip ci] --- 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 04d596fb5..d4f8a9a2c 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-multiple-params.md`. PR [#12598](https://github.com/fastapi/fastapi/pull/12598) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/en/docs/tutorial/body-multiple-params.md`. PR [#12593](https://github.com/fastapi/fastapi/pull/12593) by [@Tashanam-Shahbaz](https://github.com/Tashanam-Shahbaz). * 📝 Update includes in `docs/pt/docs/tutorial/background-tasks.md`. PR [#12736](https://github.com/fastapi/fastapi/pull/12736) by [@bhunao](https://github.com/bhunao). * 📝 Update includes for `docs/en/docs/advanced/custom-response.md`. PR [#12797](https://github.com/fastapi/fastapi/pull/12797) by [@handabaldeep](https://github.com/handabaldeep). From 2d4e9d46c036040e8ff37c10a777155c3c429e2b Mon Sep 17 00:00:00 2001 From: Baldeep Singh Handa Date: Sat, 9 Nov 2024 11:23:09 +0000 Subject: [PATCH 327/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20`doc?= =?UTF-8?q?s/en/docs/advanced/openapi-callbacks.md`=20(#12800)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/openapi-callbacks.md | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md index 82069a950..ca9065a89 100644 --- a/docs/en/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -31,9 +31,7 @@ It will have a *path operation* that will receive an `Invoice` body, and a query This part is pretty normal, most of the code is probably already familiar to you: -```Python hl_lines="9-13 36-53" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *} /// tip @@ -92,9 +90,7 @@ Temporarily adopting this point of view (of the *external developer*) can help y First create a new `APIRouter` that will contain one or more callbacks. -```Python hl_lines="3 25" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *} ### Create the callback *path operation* @@ -105,9 +101,7 @@ It should look just like a normal FastAPI *path operation*: * It should probably have a declaration of the body it should receive, e.g. `body: InvoiceEvent`. * And it could also have a declaration of the response it should return, e.g. `response_model=InvoiceEventReceived`. -```Python hl_lines="16-18 21-22 28-32" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *} There are 2 main differences from a normal *path operation*: @@ -175,9 +169,7 @@ At this point you have the *callback path operation(s)* needed (the one(s) that Now use the parameter `callbacks` in *your API's path operation decorator* to pass the attribute `.routes` (that's actually just a `list` of routes/*path operations*) from that callback router: -```Python hl_lines="35" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *} /// tip From c0f56ce0b285c391116f5fcabf21e116110fef21 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 11:23:32 +0000 Subject: [PATCH 328/932] =?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 [skip ci] --- 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 d4f8a9a2c..2633c1965 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes `docs/en/docs/advanced/openapi-callbacks.md`. PR [#12800](https://github.com/fastapi/fastapi/pull/12800) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes in `docs/fr/docs/tutorial/body-multiple-params.md`. PR [#12598](https://github.com/fastapi/fastapi/pull/12598) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/en/docs/tutorial/body-multiple-params.md`. PR [#12593](https://github.com/fastapi/fastapi/pull/12593) by [@Tashanam-Shahbaz](https://github.com/Tashanam-Shahbaz). * 📝 Update includes in `docs/pt/docs/tutorial/background-tasks.md`. PR [#12736](https://github.com/fastapi/fastapi/pull/12736) by [@bhunao](https://github.com/bhunao). From 7517aa9f8f5fd2b7068c844e83b059bb8783e3b5 Mon Sep 17 00:00:00 2001 From: Baldeep Singh Handa Date: Sat, 9 Nov 2024 11:23:58 +0000 Subject: [PATCH 329/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20`doc?= =?UTF-8?q?s/en/docs/advanced/response-change-status-code.md`=20(#12801)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/response-change-status-code.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/en/docs/advanced/response-change-status-code.md b/docs/en/docs/advanced/response-change-status-code.md index fc041f7de..6d3f9f3e8 100644 --- a/docs/en/docs/advanced/response-change-status-code.md +++ b/docs/en/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ You can declare a parameter of type `Response` in your *path operation function* And then you can set the `status_code` in that *temporal* response object. -```Python hl_lines="1 9 12" -{!../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} And then you can return any object you need, as you normally would (a `dict`, a database model, etc). From b2ec345e67d691f4c40d484750645d765226dd15 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 11:25:26 +0000 Subject: [PATCH 330/932] =?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 [skip ci] --- 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 2633c1965..bfe34cea5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update includes `docs/en/docs/advanced/response-change-status-code.md`. PR [#12801](https://github.com/fastapi/fastapi/pull/12801) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes `docs/en/docs/advanced/openapi-callbacks.md`. PR [#12800](https://github.com/fastapi/fastapi/pull/12800) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes in `docs/fr/docs/tutorial/body-multiple-params.md`. PR [#12598](https://github.com/fastapi/fastapi/pull/12598) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/en/docs/tutorial/body-multiple-params.md`. PR [#12593](https://github.com/fastapi/fastapi/pull/12593) by [@Tashanam-Shahbaz](https://github.com/Tashanam-Shahbaz). From 34ed88394c27fb448bfccc0fc165317139478dbf Mon Sep 17 00:00:00 2001 From: Alex Wendland Date: Sat, 9 Nov 2024 11:27:35 +0000 Subject: [PATCH 331/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/em/docs/tutorial/body-updates.md`=20(#12799)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/em/docs/tutorial/body-updates.md | 96 ++------------------------- 1 file changed, 4 insertions(+), 92 deletions(-) diff --git a/docs/em/docs/tutorial/body-updates.md b/docs/em/docs/tutorial/body-updates.md index 4a4b3b6b8..7e2fbfaf7 100644 --- a/docs/em/docs/tutorial/body-updates.md +++ b/docs/em/docs/tutorial/body-updates.md @@ -6,29 +6,7 @@ 👆 💪 ⚙️ `jsonable_encoder` 🗜 🔢 💽 📊 👈 💪 🏪 🎻 (✅ ⏮️ ☁ 💽). 🖼, 🏭 `datetime` `str`. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="28-33" -{!> ../../docs_src/body_updates/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial001.py hl[30:35] *} `PUT` ⚙️ 📨 💽 👈 🔜 ❎ ♻ 💽. @@ -76,29 +54,7 @@ ⤴️ 👆 💪 ⚙️ 👉 🏗 `dict` ⏮️ 🕴 💽 👈 ⚒ (📨 📨), 🚫 🔢 💲: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="32" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002.py hl[34] *} ### ⚙️ Pydantic `update` 🔢 @@ -106,29 +62,7 @@ 💖 `stored_item_model.copy(update=update_data)`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="33" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002.py hl[35] *} ### 🍕 ℹ 🌃 @@ -145,29 +79,7 @@ * 🖊 💽 👆 💽. * 📨 ℹ 🏷. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="28-35" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002.py hl[30:37] *} /// tip From 6b965b576edc8a968f5e11934364e894319b0ff8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 11:31:19 +0000 Subject: [PATCH 332/932] =?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 [skip ci] --- 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 bfe34cea5..72ebd4684 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/em/docs/tutorial/body-updates.md`. PR [#12799](https://github.com/fastapi/fastapi/pull/12799) by [@AlexWendland](https://github.com/AlexWendland). * 📝 Update includes `docs/en/docs/advanced/response-change-status-code.md`. PR [#12801](https://github.com/fastapi/fastapi/pull/12801) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes `docs/en/docs/advanced/openapi-callbacks.md`. PR [#12800](https://github.com/fastapi/fastapi/pull/12800) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes in `docs/fr/docs/tutorial/body-multiple-params.md`. PR [#12598](https://github.com/fastapi/fastapi/pull/12598) by [@kantandane](https://github.com/kantandane). From c88e82d6ec2227bc934a62cfcd85267b4bd1937e Mon Sep 17 00:00:00 2001 From: Alissa <96190409+alissadb@users.noreply.github.com> Date: Sat, 9 Nov 2024 12:32:51 +0100 Subject: [PATCH 333/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/de/docs/tutorial/body-multiple-params.md`=20(#12699)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/body-multiple-params.md | 224 +----------------- 1 file changed, 5 insertions(+), 219 deletions(-) diff --git a/docs/de/docs/tutorial/body-multiple-params.md b/docs/de/docs/tutorial/body-multiple-params.md index 26ae73ebc..891c98cb2 100644 --- a/docs/de/docs/tutorial/body-multiple-params.md +++ b/docs/de/docs/tutorial/body-multiple-params.md @@ -8,57 +8,7 @@ Zuerst einmal, Sie können `Path`-, `Query`- und Requestbody-Parameter-Deklarati Und Sie können auch Body-Parameter als optional kennzeichnen, indem Sie den Defaultwert auf `None` setzen: -//// tab | Python 3.10+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="17-19" -{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} /// note | "Hinweis" @@ -81,21 +31,7 @@ Im vorherigen Beispiel erwartete die *Pfadoperation* einen JSON-Body mit den Att Aber Sie können auch mehrere Body-Parameter deklarieren, z. B. `item` und `user`: -//// tab | Python 3.10+ - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} In diesem Fall wird **FastAPI** bemerken, dass es mehr als einen Body-Parameter in der Funktion gibt (zwei Parameter, die Pydantic-Modelle sind). @@ -136,57 +72,7 @@ Wenn Sie diesen Parameter einfach so hinzufügen, wird **FastAPI** annehmen, das Aber Sie können **FastAPI** instruieren, ihn als weiteren Body-Schlüssel zu erkennen, indem Sie `Body` verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} In diesem Fall erwartet **FastAPI** einen Body wie: @@ -226,57 +112,7 @@ q: str | None = None Zum Beispiel: -//// tab | Python 3.10+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="28" -{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="25" -{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *} /// info @@ -298,57 +134,7 @@ item: Item = Body(embed=True) so wie in: -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} In diesem Fall erwartet **FastAPI** einen Body wie: From a36454a7e6eacda8460f84fe504144751d9cd569 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 11:34:42 +0000 Subject: [PATCH 334/932] =?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 [skip ci] --- 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 72ebd4684..c0c19da9e 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/de/docs/tutorial/body-multiple-params.md`. PR [#12699](https://github.com/fastapi/fastapi/pull/12699) by [@alissadb](https://github.com/alissadb). * 📝 Update includes in `docs/em/docs/tutorial/body-updates.md`. PR [#12799](https://github.com/fastapi/fastapi/pull/12799) by [@AlexWendland](https://github.com/AlexWendland). * 📝 Update includes `docs/en/docs/advanced/response-change-status-code.md`. PR [#12801](https://github.com/fastapi/fastapi/pull/12801) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes `docs/en/docs/advanced/openapi-callbacks.md`. PR [#12800](https://github.com/fastapi/fastapi/pull/12800) by [@handabaldeep](https://github.com/handabaldeep). From 5e0722276a43596ca072e591096ca64b9cae8551 Mon Sep 17 00:00:00 2001 From: Zhaohan Dong <65422392+zhaohan-dong@users.noreply.github.com> Date: Sat, 9 Nov 2024 11:49:55 +0000 Subject: [PATCH 335/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/zh/docs/tutorial/background-tasks.md`=20(#12798)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/background-tasks.md | 32 ++++++----------------- 1 file changed, 8 insertions(+), 24 deletions(-) diff --git a/docs/zh/docs/tutorial/background-tasks.md b/docs/zh/docs/tutorial/background-tasks.md index fc9312bc5..80622e129 100644 --- a/docs/zh/docs/tutorial/background-tasks.md +++ b/docs/zh/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ 首先导入 `BackgroundTasks` 并在 *路径操作函数* 中使用类型声明 `BackgroundTasks` 定义一个参数: -```Python hl_lines="1 13" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1, 13] *} **FastAPI** 会创建一个 `BackgroundTasks` 类型的对象并作为该参数传入。 @@ -33,17 +31,13 @@ 由于写操作不使用 `async` 和 `await`,我们用普通的 `def` 定义函数: -```Python hl_lines="6-9" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## 添加后台任务 在你的 *路径操作函数* 里,用 `.add_task()` 方法将任务函数传到 *后台任务* 对象中: -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` 接收以下参数: @@ -59,25 +53,19 @@ //// 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!} -``` +{* ../../docs_src/background_tasks/tutorial002_an_py39.py hl[13, 15, 22, 25] *} //// //// tab | Python 3.8+ -```Python hl_lines="14 16 23 26" -{!> ../../docs_src/background_tasks/tutorial002_an.py!} -``` +{* ../../docs_src/background_tasks/tutorial002_an.py hl[14, 16, 23, 26] *} //// @@ -89,9 +77,7 @@ /// -```Python hl_lines="11 13 20 23" -{!> ../../docs_src/background_tasks/tutorial002_py310.py!} -``` +{* ../../docs_src/background_tasks/tutorial002_py310.py hl[11, 13, 20, 23] *} //// @@ -103,9 +89,7 @@ /// -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002.py!} -``` +{* ../../docs_src/background_tasks/tutorial002.py hl[13, 15, 22, 25] *} //// From 835123ee28bba1a6b3bfffc97e47e87f62d376d7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 11:50:20 +0000 Subject: [PATCH 336/932] =?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 [skip ci] --- 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 c0c19da9e..d2fd65995 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/zh/docs/tutorial/background-tasks.md`. PR [#12798](https://github.com/fastapi/fastapi/pull/12798) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes for `docs/de/docs/tutorial/body-multiple-params.md`. PR [#12699](https://github.com/fastapi/fastapi/pull/12699) by [@alissadb](https://github.com/alissadb). * 📝 Update includes in `docs/em/docs/tutorial/body-updates.md`. PR [#12799](https://github.com/fastapi/fastapi/pull/12799) by [@AlexWendland](https://github.com/AlexWendland). * 📝 Update includes `docs/en/docs/advanced/response-change-status-code.md`. PR [#12801](https://github.com/fastapi/fastapi/pull/12801) by [@handabaldeep](https://github.com/handabaldeep). From 22eafff2d87c66a0f6e78dcbf68fdcbddfc56e58 Mon Sep 17 00:00:00 2001 From: Baldeep Singh Handa Date: Sat, 9 Nov 2024 11:54:19 +0000 Subject: [PATCH 337/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/advanced/response-directly.md`=20(#12803)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/response-directly.md | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md index 8246b9674..09947a2ee 100644 --- a/docs/en/docs/advanced/response-directly.md +++ b/docs/en/docs/advanced/response-directly.md @@ -34,9 +34,7 @@ For example, you cannot put a Pydantic model in a `JSONResponse` without first c For those cases, you can use the `jsonable_encoder` to convert your data before passing it to a response: -```Python hl_lines="6-7 21-22" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} /// note | "Technical Details" @@ -56,9 +54,7 @@ Let's say that you want to return an Date: Sat, 9 Nov 2024 11:54:43 +0000 Subject: [PATCH 338/932] =?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 [skip ci] --- 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 d2fd65995..1c43ac02a 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/advanced/response-directly.md`. PR [#12803](https://github.com/fastapi/fastapi/pull/12803) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes in `docs/zh/docs/tutorial/background-tasks.md`. PR [#12798](https://github.com/fastapi/fastapi/pull/12798) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes for `docs/de/docs/tutorial/body-multiple-params.md`. PR [#12699](https://github.com/fastapi/fastapi/pull/12699) by [@alissadb](https://github.com/alissadb). * 📝 Update includes in `docs/em/docs/tutorial/body-updates.md`. PR [#12799](https://github.com/fastapi/fastapi/pull/12799) by [@AlexWendland](https://github.com/AlexWendland). From b5036db18cb910e533728de695b8704dfa8a1f6e Mon Sep 17 00:00:00 2001 From: Zhaohan Dong <65422392+zhaohan-dong@users.noreply.github.com> Date: Sat, 9 Nov 2024 11:58:07 +0000 Subject: [PATCH 339/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/advanced/path-operation-advanced-configuration?= =?UTF-8?q?.md`=20(#12802)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../path-operation-advanced-configuration.md | 40 +++++-------------- 1 file changed, 10 insertions(+), 30 deletions(-) diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md index a61e3f19b..fea1e4db0 100644 --- a/docs/en/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md @@ -12,9 +12,7 @@ You can set the OpenAPI `operationId` to be used in your *path operation* with t You would have to make sure that it is unique for each operation. -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### Using the *path operation function* name as the operationId @@ -22,9 +20,7 @@ If you want to use your APIs' function names as `operationId`s, you can iterate You should do it after adding all your *path operations*. -```Python hl_lines="2 12-21 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2, 12:21, 24] *} /// tip @@ -44,9 +40,7 @@ Even if they are in different modules (Python files). To exclude a *path operation* from the generated OpenAPI schema (and thus, from the automatic documentation systems), use the parameter `include_in_schema` and set it to `False`: -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## Advanced description from docstring @@ -56,9 +50,7 @@ Adding an `\f` (an escaped "form feed" character) causes **FastAPI** to truncate It won't show up in the documentation, but other tools (such as Sphinx) will be able to use the rest. -```Python hl_lines="19-29" -{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} ## Additional Responses @@ -100,9 +92,7 @@ You can extend the OpenAPI schema for a *path operation* using the parameter `op This `openapi_extra` can be helpful, for example, to declare [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions): -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} If you open the automatic API docs, your extension will show up at the bottom of the specific *path operation*. @@ -149,9 +139,7 @@ For example, you could decide to read and validate the request with your own cod You could do that with `openapi_extra`: -```Python hl_lines="19-36 39-40" -{!../../docs_src/path_operation_advanced_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[19:36, 39:40] *} In this example, we didn't declare any Pydantic model. In fact, the request body is not even parsed as JSON, it is read directly as `bytes`, and the function `magic_data_reader()` would be in charge of parsing it in some way. @@ -167,17 +155,13 @@ For example, in this application we don't use FastAPI's integrated functionality //// tab | Pydantic v2 -```Python hl_lines="17-22 24" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22, 24] *} //// //// tab | Pydantic v1 -```Python hl_lines="17-22 24" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[17:22, 24] *} //// @@ -195,17 +179,13 @@ And then in our code, we parse that YAML content directly, and then we are again //// tab | Pydantic v2 -```Python hl_lines="26-33" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} //// //// tab | Pydantic v1 -```Python hl_lines="26-33" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[26:33] *} //// From f91d193d6304ac6598cf76850a6be87a382ed63b Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 11:58:33 +0000 Subject: [PATCH 340/932] =?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 [skip ci] --- 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 1c43ac02a..ebcc8ffc6 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/path-operation-advanced-configuration.md`. PR [#12802](https://github.com/fastapi/fastapi/pull/12802) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes for `docs/en/docs/advanced/response-directly.md`. PR [#12803](https://github.com/fastapi/fastapi/pull/12803) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes in `docs/zh/docs/tutorial/background-tasks.md`. PR [#12798](https://github.com/fastapi/fastapi/pull/12798) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes for `docs/de/docs/tutorial/body-multiple-params.md`. PR [#12699](https://github.com/fastapi/fastapi/pull/12699) by [@alissadb](https://github.com/alissadb). From 854cddf1a8e3ab5e3da70f74286c5485ccff5fb1 Mon Sep 17 00:00:00 2001 From: Zhaohan Dong <65422392+zhaohan-dong@users.noreply.github.com> Date: Sat, 9 Nov 2024 12:06:35 +0000 Subject: [PATCH 341/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/advanced/response-cookies.md`=20(#12804)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/response-cookies.md | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/docs/en/docs/advanced/response-cookies.md b/docs/en/docs/advanced/response-cookies.md index 4467779ba..988394d06 100644 --- a/docs/en/docs/advanced/response-cookies.md +++ b/docs/en/docs/advanced/response-cookies.md @@ -6,9 +6,7 @@ You can declare a parameter of type `Response` in your *path operation function* And then you can set cookies in that *temporal* response object. -```Python hl_lines="1 8-9" -{!../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1, 8:9] *} And then you can return any object you need, as you normally would (a `dict`, a database model, etc). @@ -26,9 +24,7 @@ To do that, you can create a response as described in [Return a Response Directl Then set Cookies in it, and then return it: -```Python hl_lines="10-12" -{!../../docs_src/response_cookies/tutorial001.py!} -``` +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} /// tip From 75cde1fb5cab577249f92c70c7da8b6ee808845b Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 12:06:57 +0000 Subject: [PATCH 342/932] =?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 [skip ci] --- 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 ebcc8ffc6..4d512f712 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/response-cookies.md`. PR [#12804](https://github.com/fastapi/fastapi/pull/12804) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes in `docs/en/docs/advanced/path-operation-advanced-configuration.md`. PR [#12802](https://github.com/fastapi/fastapi/pull/12802) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes for `docs/en/docs/advanced/response-directly.md`. PR [#12803](https://github.com/fastapi/fastapi/pull/12803) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes in `docs/zh/docs/tutorial/background-tasks.md`. PR [#12798](https://github.com/fastapi/fastapi/pull/12798) by [@zhaohan-dong](https://github.com/zhaohan-dong). From f55f93c181491d0d7dff60b556b6d2792a9da611 Mon Sep 17 00:00:00 2001 From: Quentin Takeda Date: Sat, 9 Nov 2024 13:10:11 +0100 Subject: [PATCH 343/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/fr/docs/tutorial/first-steps.md`=20(#12594)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/fr/docs/tutorial/first-steps.md | 32 +++++++--------------------- 1 file changed, 8 insertions(+), 24 deletions(-) diff --git a/docs/fr/docs/tutorial/first-steps.md b/docs/fr/docs/tutorial/first-steps.md index e9511b029..b2fb5181c 100644 --- a/docs/fr/docs/tutorial/first-steps.md +++ b/docs/fr/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Le fichier **FastAPI** le plus simple possible pourrait ressembler à cela : -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Copiez ce code dans un fichier nommé `main.py`. @@ -134,9 +132,7 @@ Vous pourriez aussi l'utiliser pour générer du code automatiquement, pour les ### Étape 1 : import `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` est une classe Python qui fournit toutes les fonctionnalités nécessaires au lancement de votre API. @@ -150,9 +146,7 @@ Vous pouvez donc aussi utiliser toutes les fonctionnalités de Date: Sat, 9 Nov 2024 12:12:02 +0000 Subject: [PATCH 344/932] =?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 [skip ci] --- 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 4d512f712..9ffb524de 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/first-steps.md`. PR [#12594](https://github.com/fastapi/fastapi/pull/12594) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/en/docs/advanced/response-cookies.md`. PR [#12804](https://github.com/fastapi/fastapi/pull/12804) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes in `docs/en/docs/advanced/path-operation-advanced-configuration.md`. PR [#12802](https://github.com/fastapi/fastapi/pull/12802) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes for `docs/en/docs/advanced/response-directly.md`. PR [#12803](https://github.com/fastapi/fastapi/pull/12803) by [@handabaldeep](https://github.com/handabaldeep). From 58975aa3ed1caebf01b309ee62ae9558b30ffa26 Mon Sep 17 00:00:00 2001 From: Zhaohan Dong <65422392+zhaohan-dong@users.noreply.github.com> Date: Sat, 9 Nov 2024 12:14:09 +0000 Subject: [PATCH 345/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/advanced/response-headers.md`=20(#12805)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/response-headers.md | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/docs/en/docs/advanced/response-headers.md b/docs/en/docs/advanced/response-headers.md index 80c100826..fca641d89 100644 --- a/docs/en/docs/advanced/response-headers.md +++ b/docs/en/docs/advanced/response-headers.md @@ -6,9 +6,7 @@ You can declare a parameter of type `Response` in your *path operation function* And then you can set headers in that *temporal* response object. -```Python hl_lines="1 7-8" -{!../../docs_src/response_headers/tutorial002.py!} -``` +{* ../../docs_src/response_headers/tutorial002.py hl[1, 7:8] *} And then you can return any object you need, as you normally would (a `dict`, a database model, etc). @@ -24,9 +22,7 @@ You can also add headers when you return a `Response` directly. Create a response as described in [Return a Response Directly](response-directly.md){.internal-link target=_blank} and pass the headers as an additional parameter: -```Python hl_lines="10-12" -{!../../docs_src/response_headers/tutorial001.py!} -``` +{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *} /// note | "Technical Details" From 35c37be540287f8d4f930f55cce6839773208761 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 12:15:34 +0000 Subject: [PATCH 346/932] =?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 [skip ci] --- 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 9ffb524de..c258e2bdc 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/response-headers.md`. PR [#12805](https://github.com/fastapi/fastapi/pull/12805) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes in `docs/fr/docs/tutorial/first-steps.md`. PR [#12594](https://github.com/fastapi/fastapi/pull/12594) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/en/docs/advanced/response-cookies.md`. PR [#12804](https://github.com/fastapi/fastapi/pull/12804) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes in `docs/en/docs/advanced/path-operation-advanced-configuration.md`. PR [#12802](https://github.com/fastapi/fastapi/pull/12802) by [@zhaohan-dong](https://github.com/zhaohan-dong). From 58eb4e4fc53509550a44f3a30ba584004a85977d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E4=BA=91=E6=98=94=20=28Vincy=20SHI=29?= Date: Sat, 9 Nov 2024 20:17:15 +0800 Subject: [PATCH 347/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/environment-variables.md`=20(#12784)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/environment-variables.md | 298 ++++++++++++++++++++++++++ 1 file changed, 298 insertions(+) create mode 100644 docs/zh/docs/environment-variables.md diff --git a/docs/zh/docs/environment-variables.md b/docs/zh/docs/environment-variables.md new file mode 100644 index 000000000..812278051 --- /dev/null +++ b/docs/zh/docs/environment-variables.md @@ -0,0 +1,298 @@ +# 环境变量 + +/// tip + +如果你已经知道什么是“环境变量”并且知道如何使用它们,你可以放心跳过这一部分。 + +/// + +环境变量(也称为“**env var**”)是一个独立于 Python 代码**之外**的变量,它存在于**操作系统**中,可以被你的 Python 代码(或其他程序)读取。 + +环境变量对于处理应用程序**设置**、作为 Python **安装**的一部分等方面非常有用。 + +## 创建和使用环境变量 + +你在 **shell(终端)**中就可以**创建**和使用环境变量,并不需要用到 Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// 你可以使用以下命令创建一个名为 MY_NAME 的环境变量 +$ export MY_NAME="Wade Wilson" + +// 然后,你可以在其他程序中使用它,例如 +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// 创建一个名为 MY_NAME 的环境变量 +$ $Env:MY_NAME = "Wade Wilson" + +// 在其他程序中使用它,例如 +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## 在 Python 中读取环境变量 + +你也可以在 Python **之外**的终端中创建环境变量(或使用任何其他方法),然后在 Python 中**读取**它们。 + +例如,你可以创建一个名为 `main.py` 的文件,其中包含以下内容: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +第二个参数是
`os.getenv()` 的默认返回值。 + +如果没有提供,默认值为 `None`,这里我们提供 `"World"` 作为默认值。 + +/// + +然后你可以调用这个 Python 程序: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// 这里我们还没有设置环境变量 +$ python main.py + +// 因为我们没有设置环境变量,所以我们得到的是默认值 + +Hello World from Python + +// 但是如果我们事先创建过一个环境变量 +$ export MY_NAME="Wade Wilson" + +// 然后再次调用程序 +$ python main.py + +// 现在就可以读取到环境变量了 + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// 这里我们还没有设置环境变量 +$ python main.py + +// 因为我们没有设置环境变量,所以我们得到的是默认值 + +Hello World from Python + +// 但是如果我们事先创建过一个环境变量 +$ $Env:MY_NAME = "Wade Wilson" + +// 然后再次调用程序 +$ python main.py + +// 现在就可以读取到环境变量了 + +Hello Wade Wilson from Python +``` + +
+ +//// + +由于环境变量可以在代码之外设置、但可以被代码读取,并且不必与其他文件一起存储(提交到 `git`),因此通常用于配置或**设置**。 + +你还可以为**特定的程序调用**创建特定的环境变量,该环境变量仅对该程序可用,且仅在其运行期间有效。 + +要实现这一点,只需在同一行内、程序本身之前创建它: + +
+ +```console +// 在这个程序调用的同一行中创建一个名为 MY_NAME 的环境变量 +$ MY_NAME="Wade Wilson" python main.py + +// 现在就可以读取到环境变量了 + +Hello Wade Wilson from Python + +// 在此之后这个环境变量将不会依然存在 +$ python main.py + +Hello World from Python +``` + +
+ +/// tip + +你可以在 The Twelve-Factor App: 配置中了解更多信息。 + +/// + +## 类型和验证 + +这些环境变量只能处理**文本字符串**,因为它们是处于 Python 范畴之外的,必须与其他程序和操作系统的其余部分兼容(甚至与不同的操作系统兼容,如 Linux、Windows、macOS)。 + +这意味着从环境变量中读取的**任何值**在 Python 中都将是一个 `str`,任何类型转换或验证都必须在代码中完成。 + +你将在[高级用户指南 - 设置和环境变量](./advanced/settings.md)中了解更多关于使用环境变量处理**应用程序设置**的信息。 + +## `PATH` 环境变量 + +有一个**特殊的**环境变量称为 **`PATH`**,操作系统(Linux、macOS、Windows)用它来查找要运行的程序。 + +`PATH` 变量的值是一个长字符串,由 Linux 和 macOS 上的冒号 `:` 分隔的目录组成,而在 Windows 上则是由分号 `;` 分隔的。 + +例如,`PATH` 环境变量可能如下所示: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +这意味着系统应该在以下目录中查找程序: + +- `/usr/local/bin` +- `/usr/bin` +- `/bin` +- `/usr/sbin` +- `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +这意味着系统应该在以下目录中查找程序: + +- `C:\Program Files\Python312\Scripts` +- `C:\Program Files\Python312` +- `C:\Windows\System32` + +//// + +当你在终端中输入一个**命令**时,操作系统会在 `PATH` 环境变量中列出的**每个目录**中**查找**程序。 + +例如,当你在终端中输入 `python` 时,操作系统会在该列表中的**第一个目录**中查找名为 `python` 的程序。 + +如果找到了,那么操作系统将**使用它**;否则,操作系统会继续在**其他目录**中查找。 + +### 安装 Python 和更新 `PATH` + +安装 Python 时,可能会询问你是否要更新 `PATH` 环境变量。 + +//// tab | Linux, macOS + +假设你安装 Python 并最终将其安装在了目录 `/opt/custompython/bin` 中。 + +如果你同意更新 `PATH` 环境变量,那么安装程序将会将 `/opt/custompython/bin` 添加到 `PATH` 环境变量中。 + +它看起来大概会像这样: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +如此一来,当你在终端中输入 `python` 时,系统会在 `/opt/custompython/bin` 中找到 Python 程序(最后一个目录)并使用它。 + +//// + +//// tab | Windows + +假设你安装 Python 并最终将其安装在了目录 `C:\opt\custompython\bin` 中。 + +如果你同意更新 `PATH` 环境变量 (在 Python 安装程序中,这个操作是名为 `Add Python x.xx to PATH` 的复选框 —— 译者注),那么安装程序将会将 `C:\opt\custompython\bin` 添加到 `PATH` 环境变量中。 + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +如此一来,当你在终端中输入 `python` 时,系统会在 `C:\opt\custompython\bin` 中找到 Python 程序(最后一个目录)并使用它。 + +//// + +因此,如果你输入: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +系统会在 `/opt/custompython/bin` 中**找到** `python` 程序并运行它。 + +这和输入以下命令大致等价: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +系统会在 `C:\opt\custompython\bin\python` 中**找到** `python` 程序并运行它。 + +这和输入以下命令大致等价: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +当学习[虚拟环境](virtual-environments.md)时,这些信息将会很有用。 + +## 结论 + +通过这个教程,你应该对**环境变量**是什么以及如何在 Python 中使用它们有了基本的了解。 + +你也可以在环境变量 - 维基百科 (Wikipedia for Environment Variable) 中了解更多关于它们的信息。 + +在许多情况下,环境变量的用途和适用性并不是很明显。但是在开发过程中,它们会在许多不同的场景中出现,因此了解它们是很有必要的。 + +例如,你将在下一节关于[虚拟环境](virtual-environments.md)中需要这些信息。 From b458d0acb5602f8e096a7f7d7fc152d931087a4a Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 12:17:39 +0000 Subject: [PATCH 348/932] =?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 [skip ci] --- 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 c258e2bdc..1de48f196 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -46,6 +46,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/environment-variables.md`. PR [#12784](https://github.com/fastapi/fastapi/pull/12784) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Add Korean translation for `ko/docs/advanced/response-headers.md`. PR [#12740](https://github.com/fastapi/fastapi/pull/12740) by [@kwang1215](https://github.com/kwang1215). * 🌐 Add Chinese translation for `docs/zh/docs/virtual-environments.md`. PR [#12790](https://github.com/fastapi/fastapi/pull/12790) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Add Korean translation for `/docs/ko/docs/environment-variables.md`. PR [#12526](https://github.com/fastapi/fastapi/pull/12526) by [@Tolerblanc](https://github.com/Tolerblanc). From 8b183f18f744855cc477550b74ca89dca1bcece8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E4=BA=91=E6=98=94=20=28Vincy=20SHI=29?= Date: Sat, 9 Nov 2024 20:17:55 +0800 Subject: [PATCH 349/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Traditional=20Chin?= =?UTF-8?q?ese=20translation=20for=20`docs/zh-hant/docs/environment-variab?= =?UTF-8?q?les.md`=20(#12785)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/environment-variables.md | 298 +++++++++++++++++++++ 1 file changed, 298 insertions(+) create mode 100644 docs/zh-hant/docs/environment-variables.md diff --git a/docs/zh-hant/docs/environment-variables.md b/docs/zh-hant/docs/environment-variables.md new file mode 100644 index 000000000..a1598fc01 --- /dev/null +++ b/docs/zh-hant/docs/environment-variables.md @@ -0,0 +1,298 @@ +# 環境變數 + +/// tip + +如果你已經知道什麼是「環境變數」並且知道如何使用它們,你可以放心跳過這一部分。 + +/// + +環境變數(也稱為「**env var**」)是一個獨立於 Python 程式碼**之外**的變數,它存在於**作業系統**中,可以被你的 Python 程式碼(或其他程式)讀取。 + +環境變數對於處理應用程式**設定**(作為 Python **安裝**的一部分等方面)非常有用。 + +## 建立和使用環境變數 + +你在 **shell(終端機)**中就可以**建立**和使用環境變數,並不需要用到 Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// 你可以使用以下指令建立一個名為 MY_NAME 的環境變數 +$ export MY_NAME="Wade Wilson" + +// 然後,你可以在其他程式中使用它,例如 +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// 建立一個名為 MY_NAME 的環境變數 +$ $Env:MY_NAME = "Wade Wilson" + +// 在其他程式中使用它,例如 +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## 在 Python 中讀取環境變數 + +你也可以在 Python **之外**的終端機中建立環境變數(或使用其他方法),然後在 Python 中**讀取**它們。 + +例如,你可以建立一個名為 `main.py` 的檔案,其中包含以下內容: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +第二個參數是 `os.getenv()` 的預設回傳值。 + +如果沒有提供,預設值為 `None`,這裡我們提供 `"World"` 作為預設值。 + +/// + +然後你可以呼叫這個 Python 程式: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// 這裡我們還沒有設定環境變數 +$ python main.py + +// 因為我們沒有設定環境變數,所以我們得到的是預設值 + +Hello World from Python + +// 但是如果我們事先建立過一個環境變數 +$ export MY_NAME="Wade Wilson" + +// 然後再次呼叫程式 +$ python main.py + +// 現在就可以讀取到環境變數了 + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// 這裡我們還沒有設定環境變數 +$ python main.py + +// 因為我們沒有設定環境變數,所以我們得到的是預設值 + +Hello World from Python + +// 但是如果我們事先建立過一個環境變數 +$ $Env:MY_NAME = "Wade Wilson" + +// 然後再次呼叫程式 +$ python main.py + +// 現在就可以讀取到環境變數了 + +Hello Wade Wilson from Python +``` + +
+ +//// + +由於環境變數可以在程式碼之外設定,但可以被程式碼讀取,並且不必與其他檔案一起儲存(提交到 `git`),因此通常用於配置或**設定**。 + +你還可以為**特定的程式呼叫**建立特定的環境變數,該環境變數僅對該程式可用,且僅在其執行期間有效。 + +要實現這一點,只需在同一行內(程式本身之前)建立它: + +
+ +```console +// 在這個程式呼叫的同一行中建立一個名為 MY_NAME 的環境變數 +$ MY_NAME="Wade Wilson" python main.py + +// 現在就可以讀取到環境變數了 + +Hello Wade Wilson from Python + +// 在此之後這個環境變數將不再存在 +$ python main.py + +Hello World from Python +``` + +
+ +/// tip + +你可以在 The Twelve-Factor App: 配置中了解更多資訊。 + +/// + +## 型別和驗證 + +這些環境變數只能處理**文字字串**,因為它們是位於 Python 範疇之外的,必須與其他程式和作業系統的其餘部分相容(甚至與不同的作業系統相容,如 Linux、Windows、macOS)。 + +這意味著從環境變數中讀取的**任何值**在 Python 中都將是一個 `str`,任何型別轉換或驗證都必須在程式碼中完成。 + +你將在[進階使用者指南 - 設定和環境變數](./advanced/settings.md)中了解更多關於使用環境變數處理**應用程式設定**的資訊。 + +## `PATH` 環境變數 + +有一個**特殊的**環境變數稱為 **`PATH`**,作業系統(Linux、macOS、Windows)用它來查找要執行的程式。 + +`PATH` 變數的值是一個長字串,由 Linux 和 macOS 上的冒號 `:` 分隔的目錄組成,而在 Windows 上則是由分號 `;` 分隔的。 + +例如,`PATH` 環境變數可能如下所示: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +這意味著系統應該在以下目錄中查找程式: + +- `/usr/local/bin` +- `/usr/bin` +- `/bin` +- `/usr/sbin` +- `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +這意味著系統應該在以下目錄中查找程式: + +- `C:\Program Files\Python312\Scripts` +- `C:\Program Files\Python312` +- `C:\Windows\System32` + +//// + +當你在終端機中輸入一個**指令**時,作業系統會在 `PATH` 環境變數中列出的**每個目錄**中**查找**程式。 + +例如,當你在終端機中輸入 `python` 時,作業系統會在該列表中的**第一個目錄**中查找名為 `python` 的程式。 + +如果找到了,那麼作業系統將**使用它**;否則,作業系統會繼續在**其他目錄**中查找。 + +### 安裝 Python 並更新 `PATH` + +安裝 Python 時,可能會詢問你是否要更新 `PATH` 環境變數。 + +//// tab | Linux, macOS + +假設你安裝了 Python,並將其安裝在目錄 `/opt/custompython/bin` 中。 + +如果你選擇更新 `PATH` 環境變數,那麼安裝程式會將 `/opt/custompython/bin` 加入到 `PATH` 環境變數中。 + +它看起來大致會是這樣: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +如此一來,當你在終端機輸入 `python` 時,系統會在 `/opt/custompython/bin` 中找到 Python 程式(最後一個目錄)並使用它。 + +//// + +//// tab | Windows + +假設你安裝了 Python,並將其安裝在目錄 `C:\opt\custompython\bin` 中。 + +如果你選擇更新 `PATH` 環境變數(在 Python 安裝程式中,這個選項是名為 `Add Python x.xx to PATH` 的勾選框——譯者註),那麼安裝程式會將 `C:\opt\custompython\bin` 加入到 `PATH` 環境變數中。 + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +如此一來,當你在終端機輸入 `python` 時,系統會在 `C:\opt\custompython\bin` 中找到 Python 程式(最後一個目錄)並使用它。 + +//// + +因此,如果你輸入: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +系統會在 `/opt/custompython/bin` 中**找到** `python` 程式並執行它。 + +這大致等同於輸入以下指令: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +系統會在 `C:\opt\custompython\bin\python` 中**找到** `python` 程式並執行它。 + +這大致等同於輸入以下指令: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +當學習[虛擬環境](virtual-environments.md)時,這些資訊將會很有用。 + +## 結論 + +透過這個教學,你應該對**環境變數**是什麼以及如何在 Python 中使用它們有了基本的了解。 + +你也可以在環境變數 - 維基百科 (Wikipedia for Environment Variable) 中了解更多關於它們的資訊。 + +在許多情況下,環境變數的用途和適用性可能不會立刻顯現。但是在開發過程中,它們會在許多不同的場景中出現,因此瞭解它們是非常必要的。 + +例如,你在接下來的[虛擬環境](virtual-environments.md)章節中將需要這些資訊。 From 2abde61372004bae6964ea7d70e7e99535560324 Mon Sep 17 00:00:00 2001 From: Chol_rang Date: Sat, 9 Nov 2024 21:18:47 +0900 Subject: [PATCH 350/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/advanced/testing-websockets.md`=20(#12?= =?UTF-8?q?739)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/advanced/testing-websockets.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 docs/ko/docs/advanced/testing-websockets.md diff --git a/docs/ko/docs/advanced/testing-websockets.md b/docs/ko/docs/advanced/testing-websockets.md new file mode 100644 index 000000000..f1580c3c3 --- /dev/null +++ b/docs/ko/docs/advanced/testing-websockets.md @@ -0,0 +1,15 @@ +# WebSocket 테스트하기 + +`TestClient`를 사용하여 WebSocket을 테스트할 수 있습니다. + +이를 위해 `with` 문에서 `TestClient`를 사용하여 WebSocket에 연결합니다: + +```Python hl_lines="27-31" +{!../../docs_src/app_testing/tutorial002.py!} +``` + +/// note | 참고 + +자세한 내용은 Starlette의 WebSocket 테스트에 관한 설명서를 참고하시길 바랍니다. + +/// From 589f3c0e592cd522adab65759377476e39be3e66 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 12:21:07 +0000 Subject: [PATCH 351/932] =?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 [skip ci] --- 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 1de48f196..6fcb9b050 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -46,6 +46,7 @@ hide: ### Translations +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/environment-variables.md`. PR [#12785](https://github.com/fastapi/fastapi/pull/12785) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Add Chinese translation for `docs/zh/docs/environment-variables.md`. PR [#12784](https://github.com/fastapi/fastapi/pull/12784) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Add Korean translation for `ko/docs/advanced/response-headers.md`. PR [#12740](https://github.com/fastapi/fastapi/pull/12740) by [@kwang1215](https://github.com/kwang1215). * 🌐 Add Chinese translation for `docs/zh/docs/virtual-environments.md`. PR [#12790](https://github.com/fastapi/fastapi/pull/12790) by [@Vincy1230](https://github.com/Vincy1230). From 334d8326d00d7bbd7bfa3b1b50d1ecef2befbe69 Mon Sep 17 00:00:00 2001 From: Zhaohan Dong <65422392+zhaohan-dong@users.noreply.github.com> Date: Sat, 9 Nov 2024 12:21:25 +0000 Subject: [PATCH 352/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/advanced/sub-applications.md`=20(#12806)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/sub-applications.md | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/docs/en/docs/advanced/sub-applications.md b/docs/en/docs/advanced/sub-applications.md index befa9908a..48e329fc1 100644 --- a/docs/en/docs/advanced/sub-applications.md +++ b/docs/en/docs/advanced/sub-applications.md @@ -10,9 +10,7 @@ If you need to have two independent FastAPI applications, with their own indepen First, create the main, top-level, **FastAPI** application, and its *path operations*: -```Python hl_lines="3 6-8" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[3, 6:8] *} ### Sub-application @@ -20,9 +18,7 @@ Then, create your sub-application, and its *path operations*. This sub-application is just another standard FastAPI application, but this is the one that will be "mounted": -```Python hl_lines="11 14-16" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11, 14:16] *} ### Mount the sub-application @@ -30,9 +26,7 @@ In your top-level application, `app`, mount the sub-application, `subapi`. In this case, it will be mounted at the path `/subapi`: -```Python hl_lines="11 19" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11, 19] *} ### Check the automatic API docs From e364f941be902c40e438acfee9c6ac6edad054f4 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 12:23:03 +0000 Subject: [PATCH 353/932] =?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 [skip ci] --- 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 6fcb9b050..611c49121 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -46,6 +46,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/advanced/testing-websockets.md`. PR [#12739](https://github.com/fastapi/fastapi/pull/12739) by [@Limsunoh](https://github.com/Limsunoh). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/environment-variables.md`. PR [#12785](https://github.com/fastapi/fastapi/pull/12785) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Add Chinese translation for `docs/zh/docs/environment-variables.md`. PR [#12784](https://github.com/fastapi/fastapi/pull/12784) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Add Korean translation for `ko/docs/advanced/response-headers.md`. PR [#12740](https://github.com/fastapi/fastapi/pull/12740) by [@kwang1215](https://github.com/kwang1215). From f0a8f00b41490cd7c54029036a6f2fbd49f78751 Mon Sep 17 00:00:00 2001 From: Alex Wendland Date: Sat, 9 Nov 2024 12:24:09 +0000 Subject: [PATCH 354/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/tutorial/middleware.md`=20(#12807)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/middleware.md | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index 7c4954c7b..16d853018 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -31,9 +31,7 @@ The middleware function receives: * Then it returns the `response` generated by the corresponding *path operation*. * You can then further modify the `response` before returning it. -```Python hl_lines="8-9 11 14" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} /// tip @@ -59,11 +57,10 @@ And also after the `response` is generated, before returning it. For example, you could add a custom header `X-Process-Time` containing the time in seconds that it took to process the request and generate a response: -```Python hl_lines="10 12-13" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} /// tip +```Python hl_lines="10 12-13" Here we use `time.perf_counter()` instead of `time.time()` because it can be more precise for these use cases. 🤓 From 3c914aa610c5734072b43a0fa44b1943114f9603 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 12:25:28 +0000 Subject: [PATCH 355/932] =?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 [skip ci] --- 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 611c49121..908f1acdd 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/sub-applications.md`. PR [#12806](https://github.com/fastapi/fastapi/pull/12806) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes in `docs/en/docs/advanced/response-headers.md`. PR [#12805](https://github.com/fastapi/fastapi/pull/12805) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes in `docs/fr/docs/tutorial/first-steps.md`. PR [#12594](https://github.com/fastapi/fastapi/pull/12594) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/en/docs/advanced/response-cookies.md`. PR [#12804](https://github.com/fastapi/fastapi/pull/12804) by [@zhaohan-dong](https://github.com/zhaohan-dong). From 3f2b4339aaff79983423643cae003c1378b0f54a Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 12:27:28 +0000 Subject: [PATCH 356/932] =?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 [skip ci] --- 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 908f1acdd..f972b1cdd 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/middleware.md`. PR [#12807](https://github.com/fastapi/fastapi/pull/12807) by [@AlexWendland](https://github.com/AlexWendland). * 📝 Update includes in `docs/en/docs/advanced/sub-applications.md`. PR [#12806](https://github.com/fastapi/fastapi/pull/12806) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes in `docs/en/docs/advanced/response-headers.md`. PR [#12805](https://github.com/fastapi/fastapi/pull/12805) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes in `docs/fr/docs/tutorial/first-steps.md`. PR [#12594](https://github.com/fastapi/fastapi/pull/12594) by [@kantandane](https://github.com/kantandane). From 5d62d85095cc44d879f7e82c07b13563c09597e7 Mon Sep 17 00:00:00 2001 From: Baldeep Singh Handa Date: Sat, 9 Nov 2024 12:32:45 +0000 Subject: [PATCH 357/932] =?UTF-8?q?=F0=9F=93=9D=20Updates=20include=20for?= =?UTF-8?q?=20`docs/en/docs/tutorial/cookie-params.md`=20(#12808)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/cookie-params.md | 104 +------------------------ 1 file changed, 2 insertions(+), 102 deletions(-) diff --git a/docs/en/docs/tutorial/cookie-params.md b/docs/en/docs/tutorial/cookie-params.md index 8804f854f..aeeefe3f5 100644 --- a/docs/en/docs/tutorial/cookie-params.md +++ b/docs/en/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ You can define Cookie parameters the same way you define `Query` and `Path` para First import `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 - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## Declare `Cookie` parameters @@ -64,57 +14,7 @@ Then declare the cookie parameters using the same structure as with `Path` and ` You can define the default value as well as all the extra validation or annotation parameters: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} /// note | "Technical Details" From 64204dc2b170ae583d70c25daf028018ac4497a3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 12:35:47 +0000 Subject: [PATCH 358/932] =?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 [skip ci] --- 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 f972b1cdd..762dd3c80 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Updates include for `docs/en/docs/tutorial/cookie-params.md`. PR [#12808](https://github.com/fastapi/fastapi/pull/12808) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes in `docs/en/docs/tutorial/middleware.md`. PR [#12807](https://github.com/fastapi/fastapi/pull/12807) by [@AlexWendland](https://github.com/AlexWendland). * 📝 Update includes in `docs/en/docs/advanced/sub-applications.md`. PR [#12806](https://github.com/fastapi/fastapi/pull/12806) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes in `docs/en/docs/advanced/response-headers.md`. PR [#12805](https://github.com/fastapi/fastapi/pull/12805) by [@zhaohan-dong](https://github.com/zhaohan-dong). From ffcb635c2a21c353b156e00a3f37f9cc6cc2d827 Mon Sep 17 00:00:00 2001 From: VISHNU V S <84698110+vishnuvskvkl@users.noreply.github.com> Date: Sat, 9 Nov 2024 18:55:07 +0530 Subject: [PATCH 359/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/advanced/websockets.md`=20(#12606)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/websockets.md | 80 ++--------------------------- 1 file changed, 5 insertions(+), 75 deletions(-) diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index 8947f32e7..95a394749 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -38,17 +38,13 @@ In production you would have one of the options above. But it's the simplest way to focus on the server-side of WebSockets and have a working example: -```Python hl_lines="2 6-38 41-43" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} ## Create a `websocket` In your **FastAPI** application, create a `websocket`: -```Python hl_lines="1 46-47" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} /// note | "Technical Details" @@ -62,9 +58,7 @@ You could also use `from starlette.websockets import WebSocket`. In your WebSocket route you can `await` for messages and send messages. -```Python hl_lines="48-52" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} You can receive and send binary, text, and JSON data. @@ -115,57 +109,7 @@ In WebSocket endpoints you can import from `fastapi` and use: They work the same way as for other FastAPI endpoints/*path operations*: -//// tab | Python 3.10+ - -```Python hl_lines="68-69 82" -{!> ../../docs_src/websockets/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="68-69 82" -{!> ../../docs_src/websockets/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="69-70 83" -{!> ../../docs_src/websockets/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="66-67 79" -{!> ../../docs_src/websockets/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="68-69 81" -{!> ../../docs_src/websockets/tutorial002.py!} -``` - -//// +{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *} /// info @@ -210,21 +154,7 @@ With that you can connect the WebSocket and then send and receive messages: When a WebSocket connection is closed, the `await websocket.receive_text()` will raise a `WebSocketDisconnect` exception, which you can then catch and handle like in this example. -//// tab | Python 3.9+ - -```Python hl_lines="79-81" -{!> ../../docs_src/websockets/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="81-83" -{!> ../../docs_src/websockets/tutorial003.py!} -``` - -//// +{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *} To try it out: From f2b100900a4ea675802e3c351bd75e96a8b70960 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 13:25:30 +0000 Subject: [PATCH 360/932] =?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 [skip ci] --- 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 762dd3c80..37c35a135 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/websockets.md`. PR [#12606](https://github.com/fastapi/fastapi/pull/12606) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Updates include for `docs/en/docs/tutorial/cookie-params.md`. PR [#12808](https://github.com/fastapi/fastapi/pull/12808) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes in `docs/en/docs/tutorial/middleware.md`. PR [#12807](https://github.com/fastapi/fastapi/pull/12807) by [@AlexWendland](https://github.com/AlexWendland). * 📝 Update includes in `docs/en/docs/advanced/sub-applications.md`. PR [#12806](https://github.com/fastapi/fastapi/pull/12806) by [@zhaohan-dong](https://github.com/zhaohan-dong). From abd6ad21873d336a58adae69bd900d7153776da1 Mon Sep 17 00:00:00 2001 From: Quentin Takeda Date: Sat, 9 Nov 2024 15:13:47 +0100 Subject: [PATCH 361/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/tutorial/response-model.md`=20(#12621)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/response-model.md | 264 ++---------------------- 1 file changed, 16 insertions(+), 248 deletions(-) diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index 36ccfc4ce..e7837086f 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -4,29 +4,7 @@ You can declare the type used for the response by annotating the *path operation You can use **type annotations** the same way you would for input data in function **parameters**, you can use Pydantic models, lists, dictionaries, scalar values like integers, booleans, etc. -//// tab | Python 3.10+ - -```Python hl_lines="16 21" -{!> ../../docs_src/response_model/tutorial001_01_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *} FastAPI will use this return type to: @@ -59,29 +37,7 @@ You can use the `response_model` parameter in any of the *path operations*: * `@app.delete()` * etc. -//// tab | Python 3.10+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *} /// note @@ -113,21 +69,7 @@ You can also use `response_model=None` to disable creating a response model for Here we are declaring a `UserIn` model, it will contain a plaintext password: -//// tab | Python 3.10+ - -```Python hl_lines="7 9" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *} /// info @@ -149,21 +91,7 @@ $ pip install "pydantic[email]" And we are using this model to declare our input and the same model to declare our output: -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *} Now, whenever a browser is creating a user with a password, the API will return the same password in the response. @@ -181,57 +109,15 @@ Never store the plain password of a user or send it in a response like this, unl We can instead create an input model with the plaintext password and an output model without it: -//// tab | Python 3.10+ - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *} Here, even though our *path operation function* is returning the same input user that contains the password: -//// tab | Python 3.10+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *} ...we declared the `response_model` to be our model `UserOut`, that doesn't include the password: -//// tab | Python 3.10+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *} So, **FastAPI** will take care of filtering out all the data that is not declared in the output model (using Pydantic). @@ -255,21 +141,7 @@ But in most of the cases where we need to do something like this, we want the mo And in those cases, we can use classes and inheritance to take advantage of function **type annotations** to get better support in the editor and tools, and still get the FastAPI **data filtering**. -//// tab | Python 3.10+ - -```Python hl_lines="7-10 13-14 18" -{!> ../../docs_src/response_model/tutorial003_01_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-13 15-16 20" -{!> ../../docs_src/response_model/tutorial003_01.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *} With this, we get tooling support, from editors and mypy as this code is correct in terms of types, but we also get the data filtering from FastAPI. @@ -311,9 +183,7 @@ There might be cases where you return something that is not a valid Pydantic fie The most common case would be [returning a Response directly as explained later in the advanced docs](../advanced/response-directly.md){.internal-link target=_blank}. -```Python hl_lines="8 10-11" -{!> ../../docs_src/response_model/tutorial003_02.py!} -``` +{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *} This simple case is handled automatically by FastAPI because the return type annotation is the class (or a subclass of) `Response`. @@ -323,9 +193,7 @@ And tools will also be happy because both `RedirectResponse` and `JSONResponse` You can also use a subclass of `Response` in the type annotation: -```Python hl_lines="8-9" -{!> ../../docs_src/response_model/tutorial003_03.py!} -``` +{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *} This will also work because `RedirectResponse` is a subclass of `Response`, and FastAPI will automatically handle this simple case. @@ -335,21 +203,7 @@ But when you return some other arbitrary object that is not a valid Pydantic typ The same would happen if you had something like a union between different types where one or more of them are not valid Pydantic types, for example this would fail 💥: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/response_model/tutorial003_04_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/response_model/tutorial003_04.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *} ...this fails because the type annotation is not a Pydantic type and is not just a single `Response` class or subclass, it's a union (any of the two) between a `Response` and a `dict`. @@ -361,21 +215,7 @@ But you might want to still keep the return type annotation in the function to g In this case, you can disable the response model generation by setting `response_model=None`: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/response_model/tutorial003_05_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/response_model/tutorial003_05.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *} This will make FastAPI skip the response model generation and that way you can have any return type annotations you need without it affecting your FastAPI application. 🤓 @@ -383,29 +223,7 @@ This will make FastAPI skip the response model generation and that way you can h Your response model could have default values, like: -//// tab | Python 3.10+ - -```Python hl_lines="9 11-12" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *} * `description: Union[str, None] = None` (or `str | None = None` in Python 3.10) has a default of `None`. * `tax: float = 10.5` has a default of `10.5`. @@ -419,29 +237,7 @@ For example, if you have models with many optional attributes in a NoSQL databas You can set the *path operation decorator* parameter `response_model_exclude_unset=True`: -//// tab | Python 3.10+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *} and those default values won't be included in the response, only the values actually set. @@ -538,21 +334,7 @@ This also applies to `response_model_by_alias` that works similarly. /// -//// tab | Python 3.10+ - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial005.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *} /// tip @@ -566,21 +348,7 @@ It is equivalent to `set(["name", "description"])`. If you forget to use a `set` and use a `list` or `tuple` instead, FastAPI will still convert it to a `set` and it will work correctly: -//// tab | Python 3.10+ - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial006.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *} ## Recap From 23cb1f8334c1665ed33f47c758567805bf338ffc Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 14:14:59 +0000 Subject: [PATCH 362/932] =?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 [skip ci] --- 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 37c35a135..f7723b0b2 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-model.md`. PR [#12621](https://github.com/fastapi/fastapi/pull/12621) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/en/docs/advanced/websockets.md`. PR [#12606](https://github.com/fastapi/fastapi/pull/12606) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Updates include for `docs/en/docs/tutorial/cookie-params.md`. PR [#12808](https://github.com/fastapi/fastapi/pull/12808) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes in `docs/en/docs/tutorial/middleware.md`. PR [#12807](https://github.com/fastapi/fastapi/pull/12807) by [@AlexWendland](https://github.com/AlexWendland). From 6f671b8b5a6b8550f254957a99f28090dc073363 Mon Sep 17 00:00:00 2001 From: Alex Wendland Date: Sat, 9 Nov 2024 14:19:27 +0000 Subject: [PATCH 363/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/tutorial/path-params.md`=20(#12811)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/path-params.md | 40 +++++++--------------------- 1 file changed, 10 insertions(+), 30 deletions(-) diff --git a/docs/en/docs/tutorial/path-params.md b/docs/en/docs/tutorial/path-params.md index fd9e74585..7e83d3ae5 100644 --- a/docs/en/docs/tutorial/path-params.md +++ b/docs/en/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ You can declare path "parameters" or "variables" with the same syntax used by Python format strings: -```Python hl_lines="6-7" -{!../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} The value of the path parameter `item_id` will be passed to your function as the argument `item_id`. @@ -18,9 +16,7 @@ So, if you run this example and go to Date: Sat, 9 Nov 2024 14:19:51 +0000 Subject: [PATCH 364/932] =?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 [skip ci] --- 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 f7723b0b2..60a83dff0 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/path-params.md`. PR [#12811](https://github.com/fastapi/fastapi/pull/12811) by [@AlexWendland](https://github.com/AlexWendland). * 📝 Update includes in `docs/en/docs/tutorial/response-model.md`. PR [#12621](https://github.com/fastapi/fastapi/pull/12621) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/en/docs/advanced/websockets.md`. PR [#12606](https://github.com/fastapi/fastapi/pull/12606) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Updates include for `docs/en/docs/tutorial/cookie-params.md`. PR [#12808](https://github.com/fastapi/fastapi/pull/12808) by [@handabaldeep](https://github.com/handabaldeep). From f6ba3a3c468e8db02c7e4219d16867f366b08430 Mon Sep 17 00:00:00 2001 From: Baldeep Singh Handa Date: Sat, 9 Nov 2024 14:47:24 +0000 Subject: [PATCH 365/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/tutorial/query-param-models.md`=20(#12817)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/query-param-models.md | 132 +------------------- 1 file changed, 2 insertions(+), 130 deletions(-) diff --git a/docs/en/docs/tutorial/query-param-models.md b/docs/en/docs/tutorial/query-param-models.md index f7ce345b2..84d82931a 100644 --- a/docs/en/docs/tutorial/query-param-models.md +++ b/docs/en/docs/tutorial/query-param-models.md @@ -14,71 +14,7 @@ This is supported since FastAPI version `0.115.0`. 🤓 Declare the **query parameters** that you need in a **Pydantic model**, and then declare the parameter as `Query`: -//// tab | Python 3.10+ - -```Python hl_lines="9-13 17" -{!> ../../docs_src/query_param_models/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-12 16" -{!> ../../docs_src/query_param_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10-14 18" -{!> ../../docs_src/query_param_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9-13 17" -{!> ../../docs_src/query_param_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8-12 16" -{!> ../../docs_src/query_param_models/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9-13 17" -{!> ../../docs_src/query_param_models/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} **FastAPI** will **extract** the data for **each field** from the **query parameters** in the request and give you the Pydantic model you defined. @@ -96,71 +32,7 @@ In some special use cases (probably not very common), you might want to **restri You can use Pydantic's model configuration to `forbid` any `extra` fields: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_param_models/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_param_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_param_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_param_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_param_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_param_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} If a client tries to send some **extra** data in the **query parameters**, they will receive an **error** response. From 9628d38d241c42c98503c885c751860d9f04d8dd Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 14:47:48 +0000 Subject: [PATCH 366/932] =?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 [skip ci] --- 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 60a83dff0..656f9abb6 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/tutorial/query-param-models.md`. PR [#12817](https://github.com/fastapi/fastapi/pull/12817) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes in `docs/en/docs/tutorial/path-params.md`. PR [#12811](https://github.com/fastapi/fastapi/pull/12811) by [@AlexWendland](https://github.com/AlexWendland). * 📝 Update includes in `docs/en/docs/tutorial/response-model.md`. PR [#12621](https://github.com/fastapi/fastapi/pull/12621) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/en/docs/advanced/websockets.md`. PR [#12606](https://github.com/fastapi/fastapi/pull/12606) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). From 170826c911719876cd2935f3690933e5521f286f Mon Sep 17 00:00:00 2001 From: Zhaohan Dong <65422392+zhaohan-dong@users.noreply.github.com> Date: Sat, 9 Nov 2024 14:49:21 +0000 Subject: [PATCH 367/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/tutorial/request-files.md`=20(#12818)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/request-files.md | 260 +------------------------ 1 file changed, 7 insertions(+), 253 deletions(-) diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md index f3f1eb103..2b433555b 100644 --- a/docs/en/docs/tutorial/request-files.md +++ b/docs/en/docs/tutorial/request-files.md @@ -20,69 +20,13 @@ This is because uploaded files are sent as "form data". Import `File` and `UploadFile` from `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} ## Define `File` Parameters Create file parameters the same way you would for `Body` or `Form`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} /// info @@ -110,35 +54,7 @@ But there are several cases in which you might benefit from using `UploadFile`. Define a file parameter with a type of `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="13" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} Using `UploadFile` has several advantages over `bytes`: @@ -221,91 +137,13 @@ This is not a limitation of **FastAPI**, it's part of the HTTP protocol. You can make a file optional by using standard type annotations and setting a default value of `None`: -//// tab | Python 3.10+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 18" -{!> ../../docs_src/request_files/tutorial001_02_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7 15" -{!> ../../docs_src/request_files/tutorial001_02_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} ## `UploadFile` with Additional Metadata You can also use `File()` with `UploadFile`, for example, to set additional metadata: -//// tab | Python 3.9+ - -```Python hl_lines="9 15" -{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 14" -{!> ../../docs_src/request_files/tutorial001_03_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7 13" -{!> ../../docs_src/request_files/tutorial001_03.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} ## Multiple File Uploads @@ -315,49 +153,7 @@ They would be associated to the same "form field" sent using "form data". To use that, declare a list of `bytes` or `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11 16" -{!> ../../docs_src/request_files/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/request_files/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} You will receive, as declared, a `list` of `bytes` or `UploadFile`s. @@ -373,49 +169,7 @@ You could also use `from starlette.responses import HTMLResponse`. And the same way as before, you can use `File()` to set additional parameters, even for `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="11 18-20" -{!> ../../docs_src/request_files/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12 19-21" -{!> ../../docs_src/request_files/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9 16" -{!> ../../docs_src/request_files/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11 18" -{!> ../../docs_src/request_files/tutorial003.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} ## Recap From e474d042d39a73126840d823b115d9c7ca355a71 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 14:50:19 +0000 Subject: [PATCH 368/932] =?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 [skip ci] --- 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 656f9abb6..24db5b3e5 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/request-files.md`. PR [#12818](https://github.com/fastapi/fastapi/pull/12818) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes for `docs/en/docs/tutorial/query-param-models.md`. PR [#12817](https://github.com/fastapi/fastapi/pull/12817) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes in `docs/en/docs/tutorial/path-params.md`. PR [#12811](https://github.com/fastapi/fastapi/pull/12811) by [@AlexWendland](https://github.com/AlexWendland). * 📝 Update includes in `docs/en/docs/tutorial/response-model.md`. PR [#12621](https://github.com/fastapi/fastapi/pull/12621) by [@kantandane](https://github.com/kantandane). From f6819ba5d2d90a898f05cc5c3a7a4d5653b2555f Mon Sep 17 00:00:00 2001 From: Alex Wendland Date: Sat, 9 Nov 2024 14:54:23 +0000 Subject: [PATCH 369/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/tutorial/path-operation-configuration.md`=20(#?= =?UTF-8?q?12809)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tutorial/path-operation-configuration.md | 128 +----------------- 1 file changed, 7 insertions(+), 121 deletions(-) diff --git a/docs/en/docs/tutorial/path-operation-configuration.md b/docs/en/docs/tutorial/path-operation-configuration.md index 4ca6ebf13..c78d20ea6 100644 --- a/docs/en/docs/tutorial/path-operation-configuration.md +++ b/docs/en/docs/tutorial/path-operation-configuration.md @@ -16,29 +16,7 @@ You can pass directly the `int` code, like `404`. But if you don't remember what each number code is for, you can use the shortcut constants in `status`: -//// tab | Python 3.10+ - -```Python hl_lines="1 15" -{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *} That status code will be used in the response and will be added to the OpenAPI schema. @@ -54,29 +32,7 @@ You could also use `from starlette import status`. You can add tags to your *path operation*, pass the parameter `tags` with a `list` of `str` (commonly just one `str`): -//// tab | Python 3.10+ - -```Python hl_lines="15 20 25" -{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *} They will be added to the OpenAPI schema and used by the automatic documentation interfaces: @@ -90,37 +46,13 @@ In these cases, it could make sense to store the tags in an `Enum`. **FastAPI** supports that the same way as with plain strings: -```Python hl_lines="1 8-10 13 18" -{!../../docs_src/path_operation_configuration/tutorial002b.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *} ## Summary and description You can add a `summary` and `description`: -//// tab | Python 3.10+ - -```Python hl_lines="18-19" -{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[18:19] *} ## Description from docstring @@ -128,29 +60,7 @@ As descriptions tend to be long and cover multiple lines, you can declare the *p You can write Markdown in the docstring, it will be interpreted and displayed correctly (taking into account docstring indentation). -//// tab | Python 3.10+ - -```Python hl_lines="17-25" -{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *} It will be used in the interactive docs: @@ -160,29 +70,7 @@ It will be used in the interactive docs: You can specify the response description with the parameter `response_description`: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[19] *} /// info @@ -204,9 +92,7 @@ So, if you don't provide one, **FastAPI** will automatically generate one of "Su If you need to mark a *path operation* as deprecated, but without removing it, pass the parameter `deprecated`: -```Python hl_lines="16" -{!../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} It will be clearly marked as deprecated in the interactive docs: From 4dcdb20151b761fef1645bc7b49cfda14e2dae2d Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 14:54:50 +0000 Subject: [PATCH 370/932] =?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 [skip ci] --- 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 24db5b3e5..0a36a500c 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/path-operation-configuration.md`. PR [#12809](https://github.com/fastapi/fastapi/pull/12809) by [@AlexWendland](https://github.com/AlexWendland). * 📝 Update includes in `docs/en/docs/tutorial/request-files.md`. PR [#12818](https://github.com/fastapi/fastapi/pull/12818) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes for `docs/en/docs/tutorial/query-param-models.md`. PR [#12817](https://github.com/fastapi/fastapi/pull/12817) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes in `docs/en/docs/tutorial/path-params.md`. PR [#12811](https://github.com/fastapi/fastapi/pull/12811) by [@AlexWendland](https://github.com/AlexWendland). From 069e9bdea863a39123aca1ba02d15a391be7e0a1 Mon Sep 17 00:00:00 2001 From: Zhaohan Dong <65422392+zhaohan-dong@users.noreply.github.com> Date: Sat, 9 Nov 2024 15:10:11 +0000 Subject: [PATCH 371/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/tutorial/body-nested-models.md`=20(#12812)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/body-nested-models.md | 220 +------------------- 1 file changed, 11 insertions(+), 209 deletions(-) diff --git a/docs/en/docs/tutorial/body-nested-models.md b/docs/en/docs/tutorial/body-nested-models.md index 38f3eb136..b473062de 100644 --- a/docs/en/docs/tutorial/body-nested-models.md +++ b/docs/en/docs/tutorial/body-nested-models.md @@ -6,21 +6,7 @@ With **FastAPI**, you can define, validate, document, and use arbitrarily deeply You can define an attribute to be a subtype. For example, a Python `list`: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} This will make `tags` be a list, although it doesn't declare the type of the elements of the list. @@ -34,9 +20,7 @@ In Python 3.9 and above you can use the standard `list` to declare these type an But in Python versions before 3.9 (3.6 and above), you first need to import `List` from standard Python's `typing` module: -```Python hl_lines="1" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### Declare a `list` with a type parameter @@ -65,29 +49,7 @@ Use that same standard syntax for model attributes with internal types. So, in our example, we can make `tags` be specifically a "list of strings": -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} ## Set types @@ -97,29 +59,7 @@ And Python has a special data type for sets of unique items, the `set`. Then we can declare `tags` as a set of strings: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 14" -{!> ../../docs_src/body_nested_models/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} With this, even if you receive a request with duplicate data, it will be converted to a set of unique items. @@ -141,57 +81,13 @@ All that, arbitrarily nested. For example, we can define an `Image` model: -//// tab | Python 3.10+ - -```Python hl_lines="7-9" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} ### Use the submodel as a type And then we can use it as the type of an attribute: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} This would mean that **FastAPI** would expect a body similar to: @@ -224,29 +120,7 @@ To see all the options you have, checkout ../../docs_src/body_nested_models/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} The string will be checked to be a valid URL, and documented in JSON Schema / OpenAPI as such. @@ -254,29 +128,7 @@ The string will be checked to be a valid URL, and documented in JSON Schema / Op You can also use Pydantic models as subtypes of `list`, `set`, etc.: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} This will expect (convert, validate, document, etc.) a JSON body like: @@ -314,29 +166,7 @@ Notice how the `images` key now has a list of image objects. You can define arbitrarily deeply nested models: -//// tab | Python 3.10+ - -```Python hl_lines="7 12 18 21 25" -{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} /// info @@ -360,21 +190,7 @@ images: list[Image] as in: -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/body_nested_models/tutorial008.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} ## Editor support everywhere @@ -404,21 +220,7 @@ That's what we are going to see here. In this case, you would accept any `dict` as long as it has `int` keys with `float` values: -//// tab | Python 3.9+ - -```Python hl_lines="7" -{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/body_nested_models/tutorial009.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} /// tip From 76b13045fec86ea6b155a6a78983e39ca1e9b3ab Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 15:10:34 +0000 Subject: [PATCH 372/932] =?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 [skip ci] --- 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 0a36a500c..6ecd07b05 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-nested-models.md`. PR [#12812](https://github.com/fastapi/fastapi/pull/12812) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes in `docs/en/docs/tutorial/path-operation-configuration.md`. PR [#12809](https://github.com/fastapi/fastapi/pull/12809) by [@AlexWendland](https://github.com/AlexWendland). * 📝 Update includes in `docs/en/docs/tutorial/request-files.md`. PR [#12818](https://github.com/fastapi/fastapi/pull/12818) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes for `docs/en/docs/tutorial/query-param-models.md`. PR [#12817](https://github.com/fastapi/fastapi/pull/12817) by [@handabaldeep](https://github.com/handabaldeep). From 747534334a5cfa31dfad2f7c3eaf62929f857bf4 Mon Sep 17 00:00:00 2001 From: Baldeep Singh Handa Date: Sat, 9 Nov 2024 15:21:30 +0000 Subject: [PATCH 373/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/tutorial/dependencies/sub-dependencies.md`=20(?= =?UTF-8?q?#12810)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tutorial/dependencies/sub-dependencies.md | 156 +----------------- 1 file changed, 3 insertions(+), 153 deletions(-) diff --git a/docs/en/docs/tutorial/dependencies/sub-dependencies.md b/docs/en/docs/tutorial/dependencies/sub-dependencies.md index 2b098d159..1f8ba420a 100644 --- a/docs/en/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/sub-dependencies.md @@ -10,57 +10,7 @@ They can be as **deep** as you need them to be. You could create a first dependency ("dependable") like: -//// tab | Python 3.10+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-10" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *} It declares an optional query parameter `q` as a `str`, and then it just returns it. @@ -70,57 +20,7 @@ This is quite simple (not very useful), but will help us focus on how the sub-de Then you can create another dependency function (a "dependable") that at the same time declares a dependency of its own (so it is a "dependant" too): -//// tab | Python 3.10+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *} Let's focus on the parameters declared: @@ -133,57 +33,7 @@ Let's focus on the parameters declared: Then we can use the dependency with: -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *} /// info From 48c66e30db387a62981291371b3af60641cd40b6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 15:21:54 +0000 Subject: [PATCH 374/932] =?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 [skip ci] --- 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 6ecd07b05..b28226b74 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/tutorial/dependencies/sub-dependencies.md`. PR [#12810](https://github.com/fastapi/fastapi/pull/12810) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes in `docs/en/docs/tutorial/body-nested-models.md`. PR [#12812](https://github.com/fastapi/fastapi/pull/12812) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes in `docs/en/docs/tutorial/path-operation-configuration.md`. PR [#12809](https://github.com/fastapi/fastapi/pull/12809) by [@AlexWendland](https://github.com/AlexWendland). * 📝 Update includes in `docs/en/docs/tutorial/request-files.md`. PR [#12818](https://github.com/fastapi/fastapi/pull/12818) by [@zhaohan-dong](https://github.com/zhaohan-dong). From 85e0a95bde0267d6c958f298a341f63cc47a1880 Mon Sep 17 00:00:00 2001 From: VISHNU V S <84698110+vishnuvskvkl@users.noreply.github.com> Date: Sat, 9 Nov 2024 20:56:44 +0530 Subject: [PATCH 375/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/tutorial/cors.md`=20(#12637)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/cors.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/en/docs/tutorial/cors.md b/docs/en/docs/tutorial/cors.md index 8dfc9bad9..a5d9b763a 100644 --- a/docs/en/docs/tutorial/cors.md +++ b/docs/en/docs/tutorial/cors.md @@ -46,9 +46,8 @@ You can also specify whether your backend allows: * Specific HTTP methods (`POST`, `PUT`) or all of them with the wildcard `"*"`. * Specific HTTP headers or all of them with the wildcard `"*"`. -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} + The default parameters used by the `CORSMiddleware` implementation are restrictive by default, so you'll need to explicitly enable particular origins, methods, or headers, in order for browsers to be permitted to use them in a Cross-Domain context. From 825419ecc48e3d68767f93f2c462cf5b7a2719ae Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 15:27:18 +0000 Subject: [PATCH 376/932] =?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 [skip ci] --- 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 b28226b74..ddc5cc3c7 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/tutorial/cors.md`. PR [#12637](https://github.com/fastapi/fastapi/pull/12637) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes for `docs/en/docs/tutorial/dependencies/sub-dependencies.md`. PR [#12810](https://github.com/fastapi/fastapi/pull/12810) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes in `docs/en/docs/tutorial/body-nested-models.md`. PR [#12812](https://github.com/fastapi/fastapi/pull/12812) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes in `docs/en/docs/tutorial/path-operation-configuration.md`. PR [#12809](https://github.com/fastapi/fastapi/pull/12809) by [@AlexWendland](https://github.com/AlexWendland). From 480ba19e9f2cf055a722cdd86c427c1b6e9b5816 Mon Sep 17 00:00:00 2001 From: VISHNU V S <84698110+vishnuvskvkl@users.noreply.github.com> Date: Sat, 9 Nov 2024 20:58:48 +0530 Subject: [PATCH 377/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/tutorial/extra-models.md`=20(#12638)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/extra-models.md | 76 ++------------------------- 1 file changed, 5 insertions(+), 71 deletions(-) diff --git a/docs/en/docs/tutorial/extra-models.md b/docs/en/docs/tutorial/extra-models.md index 4e6f69f31..5fac3f69e 100644 --- a/docs/en/docs/tutorial/extra-models.md +++ b/docs/en/docs/tutorial/extra-models.md @@ -20,21 +20,8 @@ If you don't know, you will learn what a "password hash" is in the [security cha Here's a general idea of how the models could look like with their password fields and the places where they are used: -//// tab | Python 3.10+ +{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *} -```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../docs_src/extra_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../docs_src/extra_models/tutorial001.py!} -``` - -//// /// info @@ -176,21 +163,7 @@ All the data conversion, validation, documentation, etc. will still work as norm That way, we can declare just the differences between the models (with plaintext `password`, with `hashed_password` and without password): -//// tab | Python 3.10+ - -```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../docs_src/extra_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../docs_src/extra_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *} ## `Union` or `anyOf` @@ -206,21 +179,8 @@ When defining a ../../docs_src/extra_models/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *} -//// tab | Python 3.8+ - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003.py!} -``` - -//// ### `Union` in Python 3.10 @@ -242,21 +202,8 @@ The same way, you can declare responses of lists of objects. For that, use the standard Python `typing.List` (or just `list` in Python 3.9 and above): -//// tab | Python 3.9+ - -```Python hl_lines="18" -{!> ../../docs_src/extra_models/tutorial004_py39.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *} -//// tab | Python 3.8+ - -```Python hl_lines="1 20" -{!> ../../docs_src/extra_models/tutorial004.py!} -``` - -//// ## Response with arbitrary `dict` @@ -266,21 +213,8 @@ This is useful if you don't know the valid field/attribute names (that would be In this case, you can use `typing.Dict` (or just `dict` in Python 3.9 and above): -//// tab | Python 3.9+ - -```Python hl_lines="6" -{!> ../../docs_src/extra_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 8" -{!> ../../docs_src/extra_models/tutorial005.py!} -``` +{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *} -//// ## Recap From 0c449748ffabae7ab8a8dd106b731322aad1e098 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 15:29:42 +0000 Subject: [PATCH 378/932] =?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 [skip ci] --- 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 ddc5cc3c7..a6f9c4d55 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/tutorial/extra-models.md`. PR [#12638](https://github.com/fastapi/fastapi/pull/12638) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes for `docs/en/docs/tutorial/cors.md`. PR [#12637](https://github.com/fastapi/fastapi/pull/12637) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes for `docs/en/docs/tutorial/dependencies/sub-dependencies.md`. PR [#12810](https://github.com/fastapi/fastapi/pull/12810) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes in `docs/en/docs/tutorial/body-nested-models.md`. PR [#12812](https://github.com/fastapi/fastapi/pull/12812) by [@zhaohan-dong](https://github.com/zhaohan-dong). From 35506c1f59d306602d6abb33cd7183f2b40ca374 Mon Sep 17 00:00:00 2001 From: VISHNU V S <84698110+vishnuvskvkl@users.noreply.github.com> Date: Sat, 9 Nov 2024 20:59:53 +0530 Subject: [PATCH 379/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/tutorial/cookie-param-models.md`=20(#12639)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/cookie-param-models.md | 82 +------------------- 1 file changed, 2 insertions(+), 80 deletions(-) diff --git a/docs/en/docs/tutorial/cookie-param-models.md b/docs/en/docs/tutorial/cookie-param-models.md index 62cafbb23..55a812852 100644 --- a/docs/en/docs/tutorial/cookie-param-models.md +++ b/docs/en/docs/tutorial/cookie-param-models.md @@ -20,57 +20,7 @@ This same technique applies to `Query`, `Cookie`, and `Header`. 😎 Declare the **cookie** parameters that you need in a **Pydantic model**, and then declare the parameter as `Cookie`: -//// tab | Python 3.10+ - -```Python hl_lines="9-12 16" -{!> ../../docs_src/cookie_param_models/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-12 16" -{!> ../../docs_src/cookie_param_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10-13 17" -{!> ../../docs_src/cookie_param_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7-10 14" -{!> ../../docs_src/cookie_param_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9-12 16" -{!> ../../docs_src/cookie_param_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} **FastAPI** will **extract** the data for **each field** from the **cookies** received in the request and give you the Pydantic model you defined. @@ -100,35 +50,7 @@ Your API now has the power to control its own ../../docs_src/cookie_param_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/cookie_param_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/cookie_param_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *} If a client tries to send some **extra cookies**, they will receive an **error** response. From 182cc4439e5a97ff0c1be3ff1be90f78398e40ed Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 15:30:31 +0000 Subject: [PATCH 380/932] =?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 [skip ci] --- 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 a6f9c4d55..bfc7669a5 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/cookie-param-models.md`. PR [#12639](https://github.com/fastapi/fastapi/pull/12639) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes for `docs/en/docs/tutorial/extra-models.md`. PR [#12638](https://github.com/fastapi/fastapi/pull/12638) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes for `docs/en/docs/tutorial/cors.md`. PR [#12637](https://github.com/fastapi/fastapi/pull/12637) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes for `docs/en/docs/tutorial/dependencies/sub-dependencies.md`. PR [#12810](https://github.com/fastapi/fastapi/pull/12810) by [@handabaldeep](https://github.com/handabaldeep). From 438343c3767f87cc04e7a4e9dfc3963ea6ecdc83 Mon Sep 17 00:00:00 2001 From: VISHNU V S <84698110+vishnuvskvkl@users.noreply.github.com> Date: Sat, 9 Nov 2024 21:02:39 +0530 Subject: [PATCH 381/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/tutorial/header-params.md`=20(#12640)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/header-params.md | 222 +------------------------ 1 file changed, 4 insertions(+), 218 deletions(-) diff --git a/docs/en/docs/tutorial/header-params.md b/docs/en/docs/tutorial/header-params.md index 293de897f..e34f301a9 100644 --- a/docs/en/docs/tutorial/header-params.md +++ b/docs/en/docs/tutorial/header-params.md @@ -6,57 +6,7 @@ You can define Header parameters the same way you define `Query`, `Path` and `Co First import `Header`: -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[3] *} ## Declare `Header` parameters @@ -64,57 +14,7 @@ Then declare the header parameters using the same structure as with `Path`, `Que You can define the default value as well as all the extra validation or annotation parameters: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *} /// note | "Technical Details" @@ -146,57 +46,7 @@ So, you can use `user_agent` as you normally would in Python code, instead of ne If for some reason you need to disable automatic conversion of underscores to hyphens, set the parameter `convert_underscores` of `Header` to `False`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/header_params/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/header_params/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/header_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial002_an_py310.py hl[10] *} /// warning @@ -214,71 +64,7 @@ You will receive all the values from the duplicate header as a Python `list`. For example, to declare a header of `X-Token` that can appear more than once, you can write: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial003_an_py310.py hl[9] *} If you communicate with that *path operation* sending two HTTP headers like: From 911d24bede6e98c1d4207cb7679e89f6a6e30b4f Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 15:33:00 +0000 Subject: [PATCH 382/932] =?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 [skip ci] --- 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 bfc7669a5..fcbe0f28c 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/tutorial/header-params.md`. PR [#12640](https://github.com/fastapi/fastapi/pull/12640) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes in `docs/en/docs/tutorial/cookie-param-models.md`. PR [#12639](https://github.com/fastapi/fastapi/pull/12639) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes for `docs/en/docs/tutorial/extra-models.md`. PR [#12638](https://github.com/fastapi/fastapi/pull/12638) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes for `docs/en/docs/tutorial/cors.md`. PR [#12637](https://github.com/fastapi/fastapi/pull/12637) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). From 5cf323d93c7563683d1518702dbfe58ee4a76219 Mon Sep 17 00:00:00 2001 From: Quentin Takeda Date: Sat, 9 Nov 2024 16:38:03 +0100 Subject: [PATCH 383/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/fr/docs/advanced/response-directly.md`=20(#12632)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/fr/docs/advanced/response-directly.md | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/docs/fr/docs/advanced/response-directly.md b/docs/fr/docs/advanced/response-directly.md index 80876bc18..338aee017 100644 --- a/docs/fr/docs/advanced/response-directly.md +++ b/docs/fr/docs/advanced/response-directly.md @@ -34,9 +34,7 @@ Par exemple, vous ne pouvez pas mettre un modèle Pydantic dans une `JSONRespons Pour ces cas, vous pouvez spécifier un appel à `jsonable_encoder` pour convertir vos données avant de les passer à une réponse : -```Python hl_lines="6-7 21-22" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} /// note | "Détails techniques" @@ -56,9 +54,7 @@ Disons que vous voulez retourner une réponse Date: Sat, 9 Nov 2024 15:39:04 +0000 Subject: [PATCH 384/932] =?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 [skip ci] --- 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 fcbe0f28c..8ddb0f4dc 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/advanced/response-directly.md`. PR [#12632](https://github.com/fastapi/fastapi/pull/12632) by [@kantandane](https://github.com/kantandane). * 📝 Update includes for `docs/en/docs/tutorial/header-params.md`. PR [#12640](https://github.com/fastapi/fastapi/pull/12640) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes in `docs/en/docs/tutorial/cookie-param-models.md`. PR [#12639](https://github.com/fastapi/fastapi/pull/12639) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes for `docs/en/docs/tutorial/extra-models.md`. PR [#12638](https://github.com/fastapi/fastapi/pull/12638) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). From 2cfd018446ec0e1f97f03a35b9b5227829263248 Mon Sep 17 00:00:00 2001 From: Quentin Takeda Date: Sat, 9 Nov 2024 16:43:03 +0100 Subject: [PATCH 385/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/fr/docs/advanced/path-operation-advanced-configuration?= =?UTF-8?q?.md`=20(#12633)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../path-operation-advanced-configuration.md | 32 +++++-------------- 1 file changed, 8 insertions(+), 24 deletions(-) diff --git a/docs/fr/docs/advanced/path-operation-advanced-configuration.md b/docs/fr/docs/advanced/path-operation-advanced-configuration.md index 94b20b0f3..b00f46727 100644 --- a/docs/fr/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/fr/docs/advanced/path-operation-advanced-configuration.md @@ -12,9 +12,7 @@ Dans OpenAPI, les chemins sont des ressources, tels que /users/ ou /items/, expo Vous devez vous assurer qu'il est unique pour chaque opération. -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### Utilisation du nom *path operation function* comme operationId @@ -22,9 +20,7 @@ Si vous souhaitez utiliser les noms de fonction de vos API comme `operationId`, Vous devriez le faire après avoir ajouté toutes vos *paramètres de chemin*. -```Python hl_lines="2 12-21 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *} /// tip | "Astuce" @@ -44,9 +40,7 @@ Même s'ils se trouvent dans des modules différents (fichiers Python). Pour exclure un *chemin* du schéma OpenAPI généré (et donc des systèmes de documentation automatiques), utilisez le paramètre `include_in_schema` et assignez-lui la valeur `False` : -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## Description avancée de docstring @@ -56,9 +50,7 @@ L'ajout d'un `\f` (un caractère d'échappement "form feed") va permettre à **F Il n'apparaîtra pas dans la documentation, mais d'autres outils (tel que Sphinx) pourront utiliser le reste. -```Python hl_lines="19-29" -{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} ## Réponses supplémentaires @@ -98,9 +90,7 @@ Vous pouvez étendre le schéma OpenAPI pour une *opération de chemin* en utili Cet `openapi_extra` peut être utile, par exemple, pour déclarer [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) : -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} Si vous ouvrez la documentation automatique de l'API, votre extension apparaîtra au bas du *chemin* spécifique. @@ -147,9 +137,7 @@ Par exemple, vous pouvez décider de lire et de valider la requête avec votre p Vous pouvez le faire avec `openapi_extra` : -```Python hl_lines="20-37 39-40" -{!../../docs_src/path_operation_advanced_configuration/tutorial006.py !} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[20:37,39:40] *} Dans cet exemple, nous n'avons déclaré aucun modèle Pydantic. En fait, le corps de la requête n'est même pas parsé en tant que JSON, il est lu directement en tant que `bytes`, et la fonction `magic_data_reader()` serait chargé de l'analyser d'une manière ou d'une autre. @@ -163,9 +151,7 @@ Et vous pouvez le faire même si le type de données dans la requête n'est pas Dans cet exemple, nous n'utilisons pas les fonctionnalités de FastAPI pour extraire le schéma JSON des modèles Pydantic ni la validation automatique pour JSON. En fait, nous déclarons le type de contenu de la requête en tant que YAML, et non JSON : -```Python hl_lines="17-22 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *} Néanmoins, bien que nous n'utilisions pas la fonctionnalité par défaut, nous utilisons toujours un modèle Pydantic pour générer manuellement le schéma JSON pour les données que nous souhaitons recevoir en YAML. @@ -173,9 +159,7 @@ Ensuite, nous utilisons directement la requête et extrayons son contenu en tant Et nous analysons directement ce contenu YAML, puis nous utilisons à nouveau le même modèle Pydantic pour valider le contenu YAML : -```Python hl_lines="26-33" -{!../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} /// tip | "Astuce" From 712c57393c01fe56983762780f62a1f4901070dd Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 15:43:28 +0000 Subject: [PATCH 386/932] =?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 [skip ci] --- 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 8ddb0f4dc..e80a53532 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/advanced/path-operation-advanced-configuration.md`. PR [#12633](https://github.com/fastapi/fastapi/pull/12633) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/fr/docs/advanced/response-directly.md`. PR [#12632](https://github.com/fastapi/fastapi/pull/12632) by [@kantandane](https://github.com/kantandane). * 📝 Update includes for `docs/en/docs/tutorial/header-params.md`. PR [#12640](https://github.com/fastapi/fastapi/pull/12640) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes in `docs/en/docs/tutorial/cookie-param-models.md`. PR [#12639](https://github.com/fastapi/fastapi/pull/12639) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). From 9a8a1adad3b5c7222ee947ecfd32fe8230faebc6 Mon Sep 17 00:00:00 2001 From: Fred Date: Sat, 9 Nov 2024 16:48:46 +0100 Subject: [PATCH 387/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/fr/docs/advanced/additional-responses.md`=20(#12634)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/fr/docs/advanced/additional-responses.md | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/docs/fr/docs/advanced/additional-responses.md b/docs/fr/docs/advanced/additional-responses.md index 52a0a0792..12f944b12 100644 --- a/docs/fr/docs/advanced/additional-responses.md +++ b/docs/fr/docs/advanced/additional-responses.md @@ -26,9 +26,7 @@ Chacun de ces `dict` de réponse peut avoir une clé `model`, contenant un modè Par exemple, pour déclarer une autre réponse avec un code HTTP `404` et un modèle Pydantic `Message`, vous pouvez écrire : -```Python hl_lines="18 22" -{!../../docs_src/additional_responses/tutorial001.py!} -``` +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} /// note | "Remarque" @@ -177,9 +175,7 @@ Vous pouvez utiliser ce même paramètre `responses` pour ajouter différents ty Par exemple, vous pouvez ajouter un type de média supplémentaire `image/png`, en déclarant que votre *opération de chemin* peut renvoyer un objet JSON (avec le type de média `application/json`) ou une image PNG : -```Python hl_lines="19-24 28" -{!../../docs_src/additional_responses/tutorial002.py!} -``` +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} /// note | "Remarque" @@ -207,9 +203,7 @@ Par exemple, vous pouvez déclarer une réponse avec un code HTTP `404` qui util Et une réponse avec un code HTTP `200` qui utilise votre `response_model`, mais inclut un `example` personnalisé : -```Python hl_lines="20-31" -{!../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} Tout sera combiné et inclus dans votre OpenAPI, et affiché dans la documentation de l'API : @@ -243,9 +237,7 @@ Vous pouvez utiliser cette technique pour réutiliser certaines réponses préd Par exemple: -```Python hl_lines="13-17 26" -{!../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## Plus d'informations sur les réponses OpenAPI From 636171ce312d7021b5f29378417db196cc5b0224 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 15:49:07 +0000 Subject: [PATCH 388/932] =?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 [skip ci] --- 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 e80a53532..73d60c229 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/advanced/additional-responses.md`. PR [#12634](https://github.com/fastapi/fastapi/pull/12634) by [@fegmorte](https://github.com/fegmorte). * 📝 Update includes in `docs/fr/docs/advanced/path-operation-advanced-configuration.md`. PR [#12633](https://github.com/fastapi/fastapi/pull/12633) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/fr/docs/advanced/response-directly.md`. PR [#12632](https://github.com/fastapi/fastapi/pull/12632) by [@kantandane](https://github.com/kantandane). * 📝 Update includes for `docs/en/docs/tutorial/header-params.md`. PR [#12640](https://github.com/fastapi/fastapi/pull/12640) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). From 5c080d81ae95d3f7dd0775b1f1789b9249d1bbec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 9 Nov 2024 17:00:17 +0100 Subject: [PATCH 389/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/tutorial/schema-extra-example.md`=20(#12822)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/schema-extra-example.md | 200 +----------------- docs/en/docs/tutorial/schema-extra-example.md | 200 +----------------- docs/ko/docs/tutorial/schema-extra-example.md | 200 +----------------- ..._py310_pv1.py => tutorial001_pv1_py310.py} | 0 ...0_pv1.py => test_tutorial001_pv1_py310.py} | 2 +- 5 files changed, 25 insertions(+), 577 deletions(-) rename docs_src/schema_extra_example/{tutorial001_py310_pv1.py => tutorial001_pv1_py310.py} (100%) rename tests/test_tutorial/test_schema_extra_example/{test_tutorial001_py310_pv1.py => test_tutorial001_pv1_py310.py} (98%) diff --git a/docs/de/docs/tutorial/schema-extra-example.md b/docs/de/docs/tutorial/schema-extra-example.md index 0da1a4ea4..ae3b98709 100644 --- a/docs/de/docs/tutorial/schema-extra-example.md +++ b/docs/de/docs/tutorial/schema-extra-example.md @@ -8,35 +8,15 @@ Hier sind mehrere Möglichkeiten, das zu tun. Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, welche dem generierten JSON-Schema hinzugefügt werden. -//// tab | Python 3.10+ Pydantic v2 - -```Python hl_lines="13-24" -{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.10+ Pydantic v1 - -```Python hl_lines="13-23" -{!> ../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} -``` - -//// - -//// tab | Python 3.8+ Pydantic v2 +//// tab | Pydantic v2 -```Python hl_lines="15-26" -{!> ../../docs_src/schema_extra_example/tutorial001.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *} //// -//// tab | Python 3.8+ Pydantic v1 +//// tab | Pydantic v1 -```Python hl_lines="15-25" -{!> ../../docs_src/schema_extra_example/tutorial001_pv1.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial001_pv1_py310.py hl[13:23] *} //// @@ -80,21 +60,7 @@ Mehr erfahren Sie am Ende dieser Seite. Wenn Sie `Field()` mit Pydantic-Modellen verwenden, können Sie ebenfalls zusätzliche `examples` deklarieren: -//// tab | Python 3.10+ - -```Python hl_lines="2 8-11" -{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10-13" -{!> ../../docs_src/schema_extra_example/tutorial002.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *} ## `examples` im JSON-Schema – OpenAPI @@ -114,57 +80,7 @@ können Sie auch eine Gruppe von `examples` mit zusätzlichen Informationen dekl Hier übergeben wir `examples`, welches ein einzelnes Beispiel für die in `Body()` erwarteten Daten enthält: -//// tab | Python 3.10+ - -```Python hl_lines="22-29" -{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="22-29" -{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23-30" -{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="18-25" -{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="20-27" -{!> ../../docs_src/schema_extra_example/tutorial003.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *} ### Beispiel in der Dokumentations-Benutzeroberfläche @@ -176,57 +92,7 @@ Mit jeder der oben genannten Methoden würde es in `/docs` so aussehen: Sie können natürlich auch mehrere `examples` übergeben: -//// tab | Python 3.10+ - -```Python hl_lines="23-38" -{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23-38" -{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24-39" -{!> ../../docs_src/schema_extra_example/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="19-34" -{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="21-36" -{!> ../../docs_src/schema_extra_example/tutorial004.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *} Wenn Sie das tun, werden die Beispiele Teil des internen **JSON-Schemas** für diese Body-Daten. @@ -267,57 +133,7 @@ Jedes spezifische Beispiel-`dict` in den `examples` kann Folgendes enthalten: Sie können es so verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="23-49" -{!> ../../docs_src/schema_extra_example/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23-49" -{!> ../../docs_src/schema_extra_example/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24-50" -{!> ../../docs_src/schema_extra_example/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="19-45" -{!> ../../docs_src/schema_extra_example/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | "Tipp" - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="21-47" -{!> ../../docs_src/schema_extra_example/tutorial005.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *} ### OpenAPI-Beispiele in der Dokumentations-Benutzeroberfläche diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md index 5896b54d9..32a1f5ca2 100644 --- a/docs/en/docs/tutorial/schema-extra-example.md +++ b/docs/en/docs/tutorial/schema-extra-example.md @@ -8,35 +8,15 @@ Here are several ways to do it. You can declare `examples` for a Pydantic model that will be added to the generated JSON Schema. -//// tab | Python 3.10+ Pydantic v2 - -```Python hl_lines="13-24" -{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.10+ Pydantic v1 - -```Python hl_lines="13-23" -{!> ../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} -``` - -//// - -//// tab | Python 3.8+ Pydantic v2 +//// tab | Pydantic v2 -```Python hl_lines="15-26" -{!> ../../docs_src/schema_extra_example/tutorial001.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *} //// -//// tab | Python 3.8+ Pydantic v1 +//// tab | Pydantic v1 -```Python hl_lines="15-25" -{!> ../../docs_src/schema_extra_example/tutorial001_pv1.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial001_pv1_py310.py hl[13:23] *} //// @@ -80,21 +60,7 @@ You can read more at the end of this page. When using `Field()` with Pydantic models, you can also declare additional `examples`: -//// tab | Python 3.10+ - -```Python hl_lines="2 8-11" -{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10-13" -{!> ../../docs_src/schema_extra_example/tutorial002.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *} ## `examples` in JSON Schema - OpenAPI @@ -114,57 +80,7 @@ you can also declare a group of `examples` with additional information that will Here we pass `examples` containing one example of the data expected in `Body()`: -//// tab | Python 3.10+ - -```Python hl_lines="22-29" -{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="22-29" -{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23-30" -{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="18-25" -{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="20-27" -{!> ../../docs_src/schema_extra_example/tutorial003.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *} ### Example in the docs UI @@ -176,57 +92,7 @@ With any of the methods above it would look like this in the `/docs`: You can of course also pass multiple `examples`: -//// tab | Python 3.10+ - -```Python hl_lines="23-38" -{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23-38" -{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24-39" -{!> ../../docs_src/schema_extra_example/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="19-34" -{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="21-36" -{!> ../../docs_src/schema_extra_example/tutorial004.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *} When you do this, the examples will be part of the internal **JSON Schema** for that body data. @@ -267,57 +133,7 @@ Each specific example `dict` in the `examples` can contain: You can use it like this: -//// tab | Python 3.10+ - -```Python hl_lines="23-49" -{!> ../../docs_src/schema_extra_example/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23-49" -{!> ../../docs_src/schema_extra_example/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24-50" -{!> ../../docs_src/schema_extra_example/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="19-45" -{!> ../../docs_src/schema_extra_example/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="21-47" -{!> ../../docs_src/schema_extra_example/tutorial005.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *} ### OpenAPI Examples in the Docs UI diff --git a/docs/ko/docs/tutorial/schema-extra-example.md b/docs/ko/docs/tutorial/schema-extra-example.md index 71052b334..b713c8975 100644 --- a/docs/ko/docs/tutorial/schema-extra-example.md +++ b/docs/ko/docs/tutorial/schema-extra-example.md @@ -8,35 +8,15 @@ 생성된 JSON 스키마에 추가될 Pydantic 모델을 위한 `examples`을 선언할 수 있습니다. -//// tab | Python 3.10+ Pydantic v2 - -```Python hl_lines="13-24" -{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.10+ Pydantic v1 - -```Python hl_lines="13-23" -{!> ../../docs_src/schema_extra_example/tutorial001_py310_pv1.py!} -``` - -//// - -//// tab | Python 3.8+ Pydantic v2 +//// tab | Pydantic v2 -```Python hl_lines="15-26" -{!> ../../docs_src/schema_extra_example/tutorial001.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *} //// -//// tab | Python 3.8+ Pydantic v1 +//// tab | Pydantic v1 -```Python hl_lines="15-25" -{!> ../../docs_src/schema_extra_example/tutorial001_pv1.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial001_pv1_py310.py hl[13:23] *} //// @@ -80,21 +60,7 @@ JSON 스키마를 확장하고 여러분의 별도의 자체 데이터를 추가 Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 선언할 수 있습니다: -//// tab | Python 3.10+ - -```Python hl_lines="2 8-11" -{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10-13" -{!> ../../docs_src/schema_extra_example/tutorial002.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *} ## JSON Schema에서의 `examples` - OpenAPI @@ -114,57 +80,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 여기, `Body()`에 예상되는 예제 데이터 하나를 포함한 `examples`를 넘겼습니다: -//// tab | Python 3.10+ - -```Python hl_lines="22-29" -{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="22-29" -{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23-30" -{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="18-25" -{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="20-27" -{!> ../../docs_src/schema_extra_example/tutorial003.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *} ### 문서 UI 예시 @@ -176,57 +92,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 물론 여러 `examples`를 넘길 수 있습니다: -//// tab | Python 3.10+ - -```Python hl_lines="23-38" -{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23-38" -{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24-39" -{!> ../../docs_src/schema_extra_example/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="19-34" -{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="21-36" -{!> ../../docs_src/schema_extra_example/tutorial004.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *} 이와 같이 하면 이 예제는 그 본문 데이터를 위한 내부 **JSON 스키마**의 일부가 될 것입니다. @@ -267,57 +133,7 @@ Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 이를 다음과 같이 사용할 수 있습니다: -//// tab | Python 3.10+ - -```Python hl_lines="23-49" -{!> ../../docs_src/schema_extra_example/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23-49" -{!> ../../docs_src/schema_extra_example/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24-50" -{!> ../../docs_src/schema_extra_example/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="19-45" -{!> ../../docs_src/schema_extra_example/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | "팁" - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="21-47" -{!> ../../docs_src/schema_extra_example/tutorial005.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *} ### 문서 UI에서의 OpenAPI 예시 diff --git a/docs_src/schema_extra_example/tutorial001_py310_pv1.py b/docs_src/schema_extra_example/tutorial001_pv1_py310.py similarity index 100% rename from docs_src/schema_extra_example/tutorial001_py310_pv1.py rename to docs_src/schema_extra_example/tutorial001_pv1_py310.py diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310_pv1.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1_py310.py similarity index 98% rename from tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310_pv1.py rename to tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1_py310.py index e036d6b68..b2a4d15b1 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310_pv1.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1_py310.py @@ -6,7 +6,7 @@ from ...utils import needs_py310, needs_pydanticv1 @pytest.fixture(name="client") def get_client(): - from docs_src.schema_extra_example.tutorial001_py310_pv1 import app + from docs_src.schema_extra_example.tutorial001_pv1_py310 import app client = TestClient(app) return client From aac7bbb51e04383e85933a3b37dcd3ed0113923c Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 16:00:40 +0000 Subject: [PATCH 390/932] =?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 [skip ci] --- 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 73d60c229..75fda217f 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/tutorial/schema-extra-example.md`. PR [#12822](https://github.com/fastapi/fastapi/pull/12822) by [@tiangolo](https://github.com/tiangolo). * 📝 Update includes in `docs/fr/docs/advanced/additional-responses.md`. PR [#12634](https://github.com/fastapi/fastapi/pull/12634) by [@fegmorte](https://github.com/fegmorte). * 📝 Update includes in `docs/fr/docs/advanced/path-operation-advanced-configuration.md`. PR [#12633](https://github.com/fastapi/fastapi/pull/12633) by [@kantandane](https://github.com/kantandane). * 📝 Update includes in `docs/fr/docs/advanced/response-directly.md`. PR [#12632](https://github.com/fastapi/fastapi/pull/12632) by [@kantandane](https://github.com/kantandane). From 5eec59fa4d68d25bd08263b5549198a24cf599f1 Mon Sep 17 00:00:00 2001 From: paintdog Date: Sat, 9 Nov 2024 17:15:51 +0100 Subject: [PATCH 391/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/de/docs/tutorial/middleware.md`=20(#12729)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/tutorial/middleware.md | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/docs/de/docs/tutorial/middleware.md b/docs/de/docs/tutorial/middleware.md index 410dc0247..6bdececbc 100644 --- a/docs/de/docs/tutorial/middleware.md +++ b/docs/de/docs/tutorial/middleware.md @@ -31,9 +31,7 @@ Die Middleware-Funktion erhält: * Dann gibt es die von der entsprechenden *Pfadoperation* generierte `response` zurück. * Sie können die `response` dann weiter modifizieren, bevor Sie sie zurückgeben. -```Python hl_lines="8-9 11 14" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} /// tip | "Tipp" @@ -59,9 +57,7 @@ Und auch nachdem die `response` generiert wurde, bevor sie zurückgegeben wird. Sie könnten beispielsweise einen benutzerdefinierten Header `X-Process-Time` hinzufügen, der die Zeit in Sekunden enthält, die benötigt wurde, um den Request zu verarbeiten und eine Response zu generieren: -```Python hl_lines="10 12-13" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} ## Andere Middlewares From 5a7bd20316a948c6fc77492895b059592934d53c Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 16:16:22 +0000 Subject: [PATCH 392/932] =?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 [skip ci] --- 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 75fda217f..8a22dc440 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/middleware.md`. PR [#12729](https://github.com/fastapi/fastapi/pull/12729) by [@paintdog](https://github.com/paintdog). * 📝 Update includes for `docs/en/docs/tutorial/schema-extra-example.md`. PR [#12822](https://github.com/fastapi/fastapi/pull/12822) by [@tiangolo](https://github.com/tiangolo). * 📝 Update includes in `docs/fr/docs/advanced/additional-responses.md`. PR [#12634](https://github.com/fastapi/fastapi/pull/12634) by [@fegmorte](https://github.com/fegmorte). * 📝 Update includes in `docs/fr/docs/advanced/path-operation-advanced-configuration.md`. PR [#12633](https://github.com/fastapi/fastapi/pull/12633) by [@kantandane](https://github.com/kantandane). From a86d2bbf4f02d379f9ab0683b3402ddbb2d56fbd Mon Sep 17 00:00:00 2001 From: Hamid Rasti <43915620+hamidrasti@users.noreply.github.com> Date: Sat, 9 Nov 2024 19:47:10 +0330 Subject: [PATCH 393/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/advanced/wsgi.md`=20(#12758)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/wsgi.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/en/docs/advanced/wsgi.md b/docs/en/docs/advanced/wsgi.md index 3974d491c..296eb1364 100644 --- a/docs/en/docs/advanced/wsgi.md +++ b/docs/en/docs/advanced/wsgi.md @@ -12,9 +12,7 @@ Then wrap the WSGI (e.g. Flask) app with the middleware. And then mount that under a path. -```Python hl_lines="2-3 23" -{!../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,3] *} ## Check it From 8a560758f886e6c24737163ce5c38d5c3ce3c625 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 16:18:19 +0000 Subject: [PATCH 394/932] =?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 [skip ci] --- 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 8a22dc440..fe975e6a2 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/advanced/wsgi.md`. PR [#12758](https://github.com/fastapi/fastapi/pull/12758) by [@hamidrasti](https://github.com/hamidrasti). * 📝 Update includes in `docs/de/docs/tutorial/middleware.md`. PR [#12729](https://github.com/fastapi/fastapi/pull/12729) by [@paintdog](https://github.com/paintdog). * 📝 Update includes for `docs/en/docs/tutorial/schema-extra-example.md`. PR [#12822](https://github.com/fastapi/fastapi/pull/12822) by [@tiangolo](https://github.com/tiangolo). * 📝 Update includes in `docs/fr/docs/advanced/additional-responses.md`. PR [#12634](https://github.com/fastapi/fastapi/pull/12634) by [@fegmorte](https://github.com/fegmorte). From 2d45b54f10e69dd63939ec2f979f1eb9e87d4e4c Mon Sep 17 00:00:00 2001 From: Hamid Rasti <43915620+hamidrasti@users.noreply.github.com> Date: Sat, 9 Nov 2024 19:48:55 +0330 Subject: [PATCH 395/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/advanced/using-request-directly.md`=20(#12760)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/using-request-directly.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/en/docs/advanced/using-request-directly.md b/docs/en/docs/advanced/using-request-directly.md index 917d77a95..3e35734bc 100644 --- a/docs/en/docs/advanced/using-request-directly.md +++ b/docs/en/docs/advanced/using-request-directly.md @@ -29,9 +29,7 @@ Let's imagine you want to get the client's IP address/host inside of your *path For that you need to access the request directly. -```Python hl_lines="1 7-8" -{!../../docs_src/using_request_directly/tutorial001.py!} -``` +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} By declaring a *path operation function* parameter with the type being the `Request` **FastAPI** will know to pass the `Request` in that parameter. From 18ca10cee4230547b3a46b0f7db32d71bece5cc4 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 16:19:17 +0000 Subject: [PATCH 396/932] =?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 [skip ci] --- 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 fe975e6a2..85129304d 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/advanced/using-request-directly.md`. PR [#12760](https://github.com/fastapi/fastapi/pull/12760) by [@hamidrasti](https://github.com/hamidrasti). * 📝 Update includes for `docs/advanced/wsgi.md`. PR [#12758](https://github.com/fastapi/fastapi/pull/12758) by [@hamidrasti](https://github.com/hamidrasti). * 📝 Update includes in `docs/de/docs/tutorial/middleware.md`. PR [#12729](https://github.com/fastapi/fastapi/pull/12729) by [@paintdog](https://github.com/paintdog). * 📝 Update includes for `docs/en/docs/tutorial/schema-extra-example.md`. PR [#12822](https://github.com/fastapi/fastapi/pull/12822) by [@tiangolo](https://github.com/tiangolo). From 52e8ea4c97ca35744e0c1511856182a6aa609ec7 Mon Sep 17 00:00:00 2001 From: Hamid Rasti <43915620+hamidrasti@users.noreply.github.com> Date: Sat, 9 Nov 2024 19:49:46 +0330 Subject: [PATCH 397/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/advanced/testing-websockets.md`=20(#12761)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/testing-websockets.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/en/docs/advanced/testing-websockets.md b/docs/en/docs/advanced/testing-websockets.md index ab08c90fe..60dfdc343 100644 --- a/docs/en/docs/advanced/testing-websockets.md +++ b/docs/en/docs/advanced/testing-websockets.md @@ -4,9 +4,7 @@ You can use the same `TestClient` to test WebSockets. For this, you use the `TestClient` in a `with` statement, connecting to the WebSocket: -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} /// note From 5e21dddb9367259d073c10af588cdb476b739f1b Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 16:21:37 +0000 Subject: [PATCH 398/932] =?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 [skip ci] --- 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 85129304d..6ca16a982 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/advanced/testing-websockets.md`. PR [#12761](https://github.com/fastapi/fastapi/pull/12761) by [@hamidrasti](https://github.com/hamidrasti). * 📝 Update includes for `docs/en/docs/advanced/using-request-directly.md`. PR [#12760](https://github.com/fastapi/fastapi/pull/12760) by [@hamidrasti](https://github.com/hamidrasti). * 📝 Update includes for `docs/advanced/wsgi.md`. PR [#12758](https://github.com/fastapi/fastapi/pull/12758) by [@hamidrasti](https://github.com/hamidrasti). * 📝 Update includes in `docs/de/docs/tutorial/middleware.md`. PR [#12729](https://github.com/fastapi/fastapi/pull/12729) by [@paintdog](https://github.com/paintdog). From ac9f4517f00709a8b7182d3b4e5401f37f15b638 Mon Sep 17 00:00:00 2001 From: Zhaohan Dong <65422392+zhaohan-dong@users.noreply.github.com> Date: Sat, 9 Nov 2024 16:25:01 +0000 Subject: [PATCH 399/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/tutorial/path-params-numeric-validations.md`?= =?UTF-8?q?=20(#12825)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../path-params-numeric-validations.md | 234 +----------------- 1 file changed, 9 insertions(+), 225 deletions(-) diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md index 9ddf49ea9..dc13a513c 100644 --- a/docs/en/docs/tutorial/path-params-numeric-validations.md +++ b/docs/en/docs/tutorial/path-params-numeric-validations.md @@ -6,57 +6,7 @@ In the same way that you can declare more validations and metadata for query par First, import `Path` from `fastapi`, and import `Annotated`: -//// tab | Python 3.10+ - -```Python hl_lines="1 3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} -``` - -//// - -//// 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 - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```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 @@ You can declare all the same parameters as for `Query`. For example, to declare a `title` metadata value for the path parameter `item_id` you can type: -//// 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 - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *} /// note @@ -162,29 +62,13 @@ Prefer to use the `Annotated` version if possible. /// -```Python hl_lines="7" -{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} //// But keep in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`. -//// 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 *} ## Order the parameters as you need, tricks @@ -209,29 +93,13 @@ Pass `*`, as the first parameter of the function. Python won't do anything with that `*`, but it will know that all the following parameters should be called as keyword arguments (key-value pairs), also known as kwargs. Even if they don't have a default value. -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ### Better with `Annotated` Keep in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`. -//// 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] *} ## Number validations: greater than or equal @@ -239,35 +107,7 @@ With `Query` and `Path` (and others you'll see later) you can declare number con Here, with `ge=1`, `item_id` will need to be an integer number "`g`reater than or `e`qual" to `1`. -//// 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] *} ## Number validations: greater than and less than or equal @@ -276,35 +116,7 @@ The same applies for: * `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 - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *} ## Number validations: floats, greater than and less than @@ -316,35 +128,7 @@ So, `0.5` would be a valid value. But `0.0` or `0` would not. And the same for 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 - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *} ## Recap From e5d00910d63674ded70aebab8f366cfa8f4a5fd6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 16:28:06 +0000 Subject: [PATCH 400/932] =?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 [skip ci] --- 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 6ca16a982..37ad0fc5c 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/path-params-numeric-validations.md`. PR [#12825](https://github.com/fastapi/fastapi/pull/12825) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes for `docs/en/docs/advanced/testing-websockets.md`. PR [#12761](https://github.com/fastapi/fastapi/pull/12761) by [@hamidrasti](https://github.com/hamidrasti). * 📝 Update includes for `docs/en/docs/advanced/using-request-directly.md`. PR [#12760](https://github.com/fastapi/fastapi/pull/12760) by [@hamidrasti](https://github.com/hamidrasti). * 📝 Update includes for `docs/advanced/wsgi.md`. PR [#12758](https://github.com/fastapi/fastapi/pull/12758) by [@hamidrasti](https://github.com/hamidrasti). From e812f872766bc576136936ebae7422d230ddb89c Mon Sep 17 00:00:00 2001 From: Zhaohan Dong <65422392+zhaohan-dong@users.noreply.github.com> Date: Sat, 9 Nov 2024 16:29:26 +0000 Subject: [PATCH 401/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/zh/docs/advanced/additional-responses.md`=20(#12828)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/advanced/additional-responses.md | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/docs/zh/docs/advanced/additional-responses.md b/docs/zh/docs/advanced/additional-responses.md index f051b12a4..362ef9460 100644 --- a/docs/zh/docs/advanced/additional-responses.md +++ b/docs/zh/docs/advanced/additional-responses.md @@ -16,9 +16,7 @@ **FastAPI**将采用该模型,生成其`JSON Schema`并将其包含在`OpenAPI`中的正确位置。 例如,要声明另一个具有状态码 `404` 和`Pydantic`模型 `Message` 的响应,可以写: -```Python hl_lines="18 22" -{!../../docs_src/additional_responses/tutorial001.py!} -``` +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} /// note @@ -163,9 +161,7 @@ 例如,您可以添加一个额外的媒体类型` image/png` ,声明您的路径操作可以返回JSON对象(媒体类型 `application/json` )或PNG图像: -```Python hl_lines="19-24 28" -{!../../docs_src/additional_responses/tutorial002.py!} -``` +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} /// note @@ -191,9 +187,7 @@ 以及一个状态码为 `200` 的响应,它使用您的 `response_model` ,但包含自定义的 `example` : -```Python hl_lines="20-31" -{!../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} 所有这些都将被合并并包含在您的OpenAPI中,并在API文档中显示: @@ -219,9 +213,7 @@ new_dict = {**old_dict, "new key": "new value"} ``` 您可以使用该技术在路径操作中重用一些预定义的响应,并将它们与其他自定义响应相结合。 **例如:** -```Python hl_lines="13-17 26" -{!../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## 有关OpenAPI响应的更多信息 要了解您可以在响应中包含哪些内容,您可以查看OpenAPI规范中的以下部分: From d08c4cffabc11b5232bfc125acc251448d8a408c Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 16:34:56 +0000 Subject: [PATCH 402/932] =?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 [skip ci] --- 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 37ad0fc5c..fa66930fc 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/zh/docs/advanced/additional-responses.md`. PR [#12828](https://github.com/fastapi/fastapi/pull/12828) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes in `docs/en/docs/tutorial/path-params-numeric-validations.md`. PR [#12825](https://github.com/fastapi/fastapi/pull/12825) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes for `docs/en/docs/advanced/testing-websockets.md`. PR [#12761](https://github.com/fastapi/fastapi/pull/12761) by [@hamidrasti](https://github.com/hamidrasti). * 📝 Update includes for `docs/en/docs/advanced/using-request-directly.md`. PR [#12760](https://github.com/fastapi/fastapi/pull/12760) by [@hamidrasti](https://github.com/hamidrasti). From 7fb9c5922d6a01a8c38f92101515cb7baa0cdcf4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 9 Nov 2024 17:39:20 +0100 Subject: [PATCH 403/932] =?UTF-8?q?=F0=9F=93=9D=20Fix=20admonition=20doubl?= =?UTF-8?q?e=20quotes=20with=20new=20syntax=20(#12835)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/de/docs/advanced/additional-responses.md | 6 +- .../docs/advanced/additional-status-codes.md | 8 +- .../de/docs/advanced/advanced-dependencies.md | 10 +-- docs/de/docs/advanced/async-tests.md | 8 +- docs/de/docs/advanced/behind-a-proxy.md | 14 ++-- docs/de/docs/advanced/custom-response.md | 16 ++-- docs/de/docs/advanced/events.md | 6 +- docs/de/docs/advanced/generate-clients.md | 2 +- docs/de/docs/advanced/index.md | 2 +- docs/de/docs/advanced/middleware.md | 2 +- docs/de/docs/advanced/openapi-callbacks.md | 10 +-- .../path-operation-advanced-configuration.md | 12 +-- docs/de/docs/advanced/response-cookies.md | 4 +- docs/de/docs/advanced/response-directly.md | 4 +- docs/de/docs/advanced/response-headers.md | 2 +- docs/de/docs/advanced/security/index.md | 2 +- .../docs/advanced/security/oauth2-scopes.md | 60 +++++++-------- docs/de/docs/advanced/settings.md | 28 +++---- docs/de/docs/advanced/templates.md | 6 +- docs/de/docs/advanced/testing-dependencies.md | 8 +- docs/de/docs/advanced/testing-websockets.md | 2 +- .../docs/advanced/using-request-directly.md | 4 +- docs/de/docs/advanced/websockets.md | 10 +-- docs/de/docs/alternatives.md | 40 +++++----- docs/de/docs/async.md | 2 +- docs/de/docs/contributing.md | 18 ++--- docs/de/docs/deployment/concepts.md | 8 +- docs/de/docs/deployment/docker.md | 16 ++-- docs/de/docs/deployment/https.md | 6 +- docs/de/docs/deployment/manually.md | 4 +- docs/de/docs/deployment/versions.md | 4 +- docs/de/docs/help-fastapi.md | 2 +- docs/de/docs/how-to/custom-docs-ui-assets.md | 4 +- .../docs/how-to/custom-request-and-route.md | 8 +- docs/de/docs/how-to/graphql.md | 4 +- docs/de/docs/how-to/index.md | 2 +- docs/de/docs/python-types.md | 10 +-- docs/de/docs/tutorial/background-tasks.md | 4 +- docs/de/docs/tutorial/bigger-applications.md | 20 ++--- docs/de/docs/tutorial/body-fields.md | 16 ++-- docs/de/docs/tutorial/body-multiple-params.md | 4 +- docs/de/docs/tutorial/body-nested-models.md | 2 +- docs/de/docs/tutorial/body-updates.md | 6 +- docs/de/docs/tutorial/body.md | 4 +- docs/de/docs/tutorial/cookie-params.md | 10 +-- .../dependencies/classes-as-dependencies.md | 42 +++++------ ...pendencies-in-path-operation-decorators.md | 10 +-- .../dependencies/dependencies-with-yield.md | 26 +++---- .../dependencies/global-dependencies.md | 2 +- docs/de/docs/tutorial/dependencies/index.md | 18 ++--- .../tutorial/dependencies/sub-dependencies.md | 16 ++-- docs/de/docs/tutorial/encoder.md | 2 +- docs/de/docs/tutorial/extra-models.md | 6 +- docs/de/docs/tutorial/first-steps.md | 10 +-- docs/de/docs/tutorial/handling-errors.md | 8 +- docs/de/docs/tutorial/header-params.md | 22 +++--- docs/de/docs/tutorial/index.md | 2 +- docs/de/docs/tutorial/metadata.md | 4 +- docs/de/docs/tutorial/middleware.md | 6 +- .../tutorial/path-operation-configuration.md | 4 +- .../path-params-numeric-validations.md | 24 +++--- docs/de/docs/tutorial/path-params.md | 6 +- .../tutorial/query-params-str-validations.md | 68 ++++++++--------- docs/de/docs/tutorial/query-params.md | 2 +- docs/de/docs/tutorial/request-files.md | 32 ++++---- .../docs/tutorial/request-forms-and-files.md | 6 +- docs/de/docs/tutorial/request-forms.md | 10 +-- docs/de/docs/tutorial/response-model.md | 12 +-- docs/de/docs/tutorial/response-status-code.md | 10 +-- docs/de/docs/tutorial/schema-extra-example.md | 6 +- docs/de/docs/tutorial/security/first-steps.md | 14 ++-- .../tutorial/security/get-current-user.md | 24 +++--- docs/de/docs/tutorial/security/index.md | 4 +- docs/de/docs/tutorial/security/oauth2-jwt.md | 26 +++---- .../docs/tutorial/security/simple-oauth2.md | 28 +++---- docs/de/docs/tutorial/static-files.md | 2 +- docs/de/docs/tutorial/testing.md | 10 +-- .../docs/advanced/additional-status-codes.md | 2 +- docs/em/docs/advanced/behind-a-proxy.md | 2 +- docs/em/docs/advanced/custom-response.md | 2 +- docs/em/docs/advanced/middleware.md | 2 +- .../path-operation-advanced-configuration.md | 2 +- docs/em/docs/advanced/response-cookies.md | 2 +- docs/em/docs/advanced/response-directly.md | 2 +- docs/em/docs/advanced/response-headers.md | 2 +- .../docs/advanced/security/oauth2-scopes.md | 2 +- docs/em/docs/advanced/templates.md | 2 +- .../docs/advanced/using-request-directly.md | 2 +- docs/em/docs/advanced/websockets.md | 2 +- docs/em/docs/alternatives.md | 38 +++++----- .../docs/how-to/custom-request-and-route.md | 2 +- docs/em/docs/tutorial/bigger-applications.md | 4 +- docs/em/docs/tutorial/body-fields.md | 2 +- docs/em/docs/tutorial/cookie-params.md | 2 +- docs/em/docs/tutorial/cors.md | 2 +- .../dependencies/dependencies-with-yield.md | 4 +- docs/em/docs/tutorial/first-steps.md | 4 +- docs/em/docs/tutorial/handling-errors.md | 4 +- docs/em/docs/tutorial/header-params.md | 2 +- docs/em/docs/tutorial/middleware.md | 4 +- .../tutorial/path-operation-configuration.md | 2 +- .../path-params-numeric-validations.md | 2 +- docs/em/docs/tutorial/request-files.md | 8 +- docs/em/docs/tutorial/request-forms.md | 2 +- docs/em/docs/tutorial/response-status-code.md | 2 +- docs/em/docs/tutorial/security/first-steps.md | 4 +- docs/em/docs/tutorial/sql-databases.md | 6 +- docs/em/docs/tutorial/static-files.md | 2 +- docs/em/docs/tutorial/testing.md | 2 +- .../docs/advanced/additional-status-codes.md | 2 +- docs/en/docs/advanced/behind-a-proxy.md | 2 +- docs/en/docs/advanced/custom-response.md | 2 +- docs/en/docs/advanced/middleware.md | 2 +- .../path-operation-advanced-configuration.md | 2 +- docs/en/docs/advanced/response-cookies.md | 2 +- docs/en/docs/advanced/response-directly.md | 2 +- docs/en/docs/advanced/response-headers.md | 2 +- .../docs/advanced/security/oauth2-scopes.md | 2 +- docs/en/docs/advanced/templates.md | 2 +- .../docs/advanced/using-request-directly.md | 2 +- docs/en/docs/advanced/websockets.md | 2 +- docs/en/docs/alternatives.md | 38 +++++----- docs/en/docs/contributing.md | 2 +- .../docs/how-to/custom-request-and-route.md | 2 +- docs/en/docs/management-tasks.md | 4 +- docs/en/docs/tutorial/bigger-applications.md | 4 +- docs/en/docs/tutorial/body-fields.md | 2 +- docs/en/docs/tutorial/cookie-params.md | 2 +- docs/en/docs/tutorial/cors.md | 2 +- .../dependencies/dependencies-with-yield.md | 4 +- docs/en/docs/tutorial/first-steps.md | 4 +- docs/en/docs/tutorial/handling-errors.md | 4 +- docs/en/docs/tutorial/header-params.md | 2 +- docs/en/docs/tutorial/middleware.md | 4 +- .../tutorial/path-operation-configuration.md | 2 +- .../path-params-numeric-validations.md | 2 +- docs/en/docs/tutorial/request-files.md | 8 +- docs/en/docs/tutorial/request-forms.md | 2 +- docs/en/docs/tutorial/response-status-code.md | 2 +- docs/en/docs/tutorial/security/first-steps.md | 4 +- docs/en/docs/tutorial/static-files.md | 2 +- docs/en/docs/tutorial/testing.md | 2 +- .../path-operation-advanced-configuration.md | 2 +- docs/es/docs/tutorial/cookie-params.md | 2 +- docs/es/docs/tutorial/index.md | 2 +- docs/fa/docs/tutorial/middleware.md | 4 +- docs/fr/docs/advanced/additional-responses.md | 6 +- .../docs/advanced/additional-status-codes.md | 4 +- docs/fr/docs/advanced/index.md | 2 +- .../path-operation-advanced-configuration.md | 12 +-- docs/fr/docs/advanced/response-directly.md | 4 +- docs/fr/docs/alternatives.md | 38 +++++----- docs/fr/docs/async.md | 2 +- docs/fr/docs/deployment/docker.md | 2 +- docs/fr/docs/deployment/manually.md | 2 +- docs/fr/docs/deployment/versions.md | 4 +- docs/fr/docs/python-types.md | 2 +- docs/fr/docs/tutorial/body.md | 2 +- docs/fr/docs/tutorial/first-steps.md | 6 +- .../path-params-numeric-validations.md | 2 +- docs/fr/docs/tutorial/path-params.md | 12 +-- .../tutorial/query-params-str-validations.md | 4 +- docs/fr/docs/tutorial/query-params.md | 4 +- docs/id/docs/tutorial/index.md | 2 +- .../docs/advanced/additional-status-codes.md | 4 +- docs/ja/docs/advanced/custom-response.md | 22 +++--- docs/ja/docs/advanced/index.md | 2 +- .../path-operation-advanced-configuration.md | 6 +- docs/ja/docs/advanced/response-directly.md | 4 +- docs/ja/docs/advanced/websockets.md | 8 +- docs/ja/docs/alternatives.md | 50 ++++++------- docs/ja/docs/async.md | 4 +- docs/ja/docs/contributing.md | 12 +-- docs/ja/docs/deployment/manually.md | 2 +- docs/ja/docs/deployment/versions.md | 4 +- docs/ja/docs/features.md | 2 +- docs/ja/docs/python-types.md | 8 +- docs/ja/docs/tutorial/body-fields.md | 6 +- docs/ja/docs/tutorial/body-multiple-params.md | 6 +- docs/ja/docs/tutorial/body-nested-models.md | 6 +- docs/ja/docs/tutorial/body-updates.md | 6 +- docs/ja/docs/tutorial/body.md | 6 +- docs/ja/docs/tutorial/cookie-params.md | 4 +- docs/ja/docs/tutorial/cors.md | 2 +- docs/ja/docs/tutorial/debugging.md | 2 +- .../dependencies/classes-as-dependencies.md | 2 +- ...pendencies-in-path-operation-decorators.md | 2 +- .../dependencies/dependencies-with-yield.md | 20 ++--- docs/ja/docs/tutorial/dependencies/index.md | 6 +- .../tutorial/dependencies/sub-dependencies.md | 4 +- docs/ja/docs/tutorial/encoder.md | 2 +- docs/ja/docs/tutorial/extra-models.md | 4 +- docs/ja/docs/tutorial/first-steps.md | 12 +-- docs/ja/docs/tutorial/handling-errors.md | 8 +- docs/ja/docs/tutorial/header-params.md | 6 +- docs/ja/docs/tutorial/index.md | 2 +- docs/ja/docs/tutorial/metadata.md | 4 +- docs/ja/docs/tutorial/middleware.md | 6 +- .../tutorial/path-operation-configuration.md | 8 +- .../path-params-numeric-validations.md | 6 +- docs/ja/docs/tutorial/path-params.md | 16 ++-- .../tutorial/query-params-str-validations.md | 14 ++-- docs/ja/docs/tutorial/query-params.md | 4 +- .../docs/tutorial/request-forms-and-files.md | 4 +- docs/ja/docs/tutorial/request-forms.md | 10 +-- docs/ja/docs/tutorial/response-model.md | 16 ++-- docs/ja/docs/tutorial/response-status-code.md | 12 +-- docs/ja/docs/tutorial/schema-extra-example.md | 2 +- docs/ja/docs/tutorial/security/first-steps.md | 14 ++-- .../tutorial/security/get-current-user.md | 4 +- docs/ja/docs/tutorial/security/index.md | 4 +- docs/ja/docs/tutorial/security/oauth2-jwt.md | 12 +-- docs/ja/docs/tutorial/static-files.md | 2 +- docs/ja/docs/tutorial/testing.md | 8 +- docs/ko/docs/advanced/events.md | 8 +- docs/ko/docs/advanced/index.md | 2 +- docs/ko/docs/advanced/response-cookies.md | 2 +- docs/ko/docs/advanced/response-directly.md | 2 +- docs/ko/docs/advanced/response-headers.md | 2 +- docs/ko/docs/async.md | 4 +- docs/ko/docs/deployment/docker.md | 20 ++--- docs/ko/docs/deployment/server-workers.md | 2 +- docs/ko/docs/deployment/versions.md | 4 +- docs/ko/docs/environment-variables.md | 6 +- docs/ko/docs/features.md | 2 +- docs/ko/docs/python-types.md | 8 +- docs/ko/docs/tutorial/body-fields.md | 16 ++-- docs/ko/docs/tutorial/body-multiple-params.md | 6 +- docs/ko/docs/tutorial/body-nested-models.md | 6 +- docs/ko/docs/tutorial/body.md | 6 +- docs/ko/docs/tutorial/cookie-params.md | 12 +-- docs/ko/docs/tutorial/cors.md | 2 +- docs/ko/docs/tutorial/debugging.md | 2 +- .../dependencies/classes-as-dependencies.md | 2 +- ...pendencies-in-path-operation-decorators.md | 12 +-- .../dependencies/global-dependencies.md | 2 +- docs/ko/docs/tutorial/dependencies/index.md | 22 +++--- docs/ko/docs/tutorial/encoder.md | 2 +- docs/ko/docs/tutorial/first-steps.md | 12 +-- docs/ko/docs/tutorial/header-params.md | 6 +- docs/ko/docs/tutorial/index.md | 2 +- docs/ko/docs/tutorial/middleware.md | 6 +- .../tutorial/path-operation-configuration.md | 8 +- .../path-params-numeric-validations.md | 6 +- docs/ko/docs/tutorial/path-params.md | 16 ++-- .../tutorial/query-params-str-validations.md | 14 ++-- docs/ko/docs/tutorial/query-params.md | 6 +- docs/ko/docs/tutorial/request-files.md | 16 ++-- .../docs/tutorial/request-forms-and-files.md | 4 +- docs/ko/docs/tutorial/response-model.md | 16 ++-- docs/ko/docs/tutorial/response-status-code.md | 12 +-- docs/ko/docs/tutorial/schema-extra-example.md | 12 +-- .../tutorial/security/get-current-user.md | 4 +- docs/ko/docs/tutorial/static-files.md | 2 +- docs/pl/docs/help-fastapi.md | 2 +- docs/pl/docs/tutorial/first-steps.md | 4 +- docs/pt/docs/advanced/additional-responses.md | 10 +-- .../docs/advanced/additional-status-codes.md | 8 +- .../pt/docs/advanced/advanced-dependencies.md | 10 +-- docs/pt/docs/advanced/async-tests.md | 8 +- docs/pt/docs/advanced/behind-a-proxy.md | 14 ++-- docs/pt/docs/advanced/events.md | 10 +-- docs/pt/docs/advanced/index.md | 2 +- docs/pt/docs/advanced/openapi-webhooks.md | 4 +- docs/pt/docs/advanced/response-cookies.md | 2 +- docs/pt/docs/advanced/response-headers.md | 2 +- .../docs/advanced/security/http-basic-auth.md | 6 +- docs/pt/docs/advanced/security/index.md | 2 +- .../docs/advanced/security/oauth2-scopes.md | 6 +- docs/pt/docs/advanced/templates.md | 4 +- docs/pt/docs/advanced/testing-dependencies.md | 8 +- docs/pt/docs/advanced/testing-websockets.md | 2 +- .../docs/advanced/using-request-directly.md | 4 +- docs/pt/docs/alternatives.md | 40 +++++----- docs/pt/docs/deployment/concepts.md | 8 +- docs/pt/docs/deployment/docker.md | 2 +- docs/pt/docs/deployment/https.md | 2 +- docs/pt/docs/deployment/manually.md | 6 +- docs/pt/docs/deployment/server-workers.md | 2 +- docs/pt/docs/deployment/versions.md | 4 +- docs/pt/docs/environment-variables.md | 6 +- docs/pt/docs/help-fastapi.md | 2 +- docs/pt/docs/how-to/graphql.md | 4 +- docs/pt/docs/tutorial/bigger-applications.md | 26 +++---- docs/pt/docs/tutorial/body-fields.md | 6 +- docs/pt/docs/tutorial/body-multiple-params.md | 6 +- docs/pt/docs/tutorial/body-nested-models.md | 6 +- docs/pt/docs/tutorial/body.md | 6 +- docs/pt/docs/tutorial/cors.md | 2 +- docs/pt/docs/tutorial/debugging.md | 2 +- .../dependencies/classes-as-dependencies.md | 42 +++++------ ...pendencies-in-path-operation-decorators.md | 12 +-- .../dependencies/dependencies-with-yield.md | 32 ++++---- .../dependencies/global-dependencies.md | 2 +- docs/pt/docs/tutorial/dependencies/index.md | 22 +++--- .../tutorial/dependencies/sub-dependencies.md | 18 ++--- docs/pt/docs/tutorial/encoder.md | 2 +- docs/pt/docs/tutorial/first-steps.md | 12 +-- docs/pt/docs/tutorial/handling-errors.md | 8 +- docs/pt/docs/tutorial/header-params.md | 4 +- docs/pt/docs/tutorial/index.md | 2 +- docs/pt/docs/tutorial/middleware.md | 6 +- .../tutorial/path-operation-configuration.md | 6 +- .../path-params-numeric-validations.md | 6 +- docs/pt/docs/tutorial/path-params.md | 16 ++-- .../tutorial/query-params-str-validations.md | 14 ++-- docs/pt/docs/tutorial/query-params.md | 4 +- docs/pt/docs/tutorial/request-files.md | 6 +- docs/pt/docs/tutorial/request-form-models.md | 8 +- .../docs/tutorial/request-forms-and-files.md | 4 +- docs/pt/docs/tutorial/request-forms.md | 10 +-- docs/pt/docs/tutorial/response-status-code.md | 12 +-- docs/pt/docs/tutorial/schema-extra-example.md | 6 +- docs/pt/docs/tutorial/security/first-steps.md | 14 ++-- docs/pt/docs/tutorial/security/index.md | 4 +- docs/pt/docs/tutorial/static-files.md | 2 +- docs/pt/docs/tutorial/testing.md | 14 ++-- docs/pt/docs/virtual-environments.md | 38 +++++----- docs/ru/docs/alternatives.md | 50 ++++++------- docs/ru/docs/contributing.md | 12 +-- docs/ru/docs/deployment/concepts.md | 8 +- docs/ru/docs/deployment/docker.md | 20 ++--- docs/ru/docs/deployment/https.md | 6 +- docs/ru/docs/deployment/manually.md | 4 +- docs/ru/docs/deployment/versions.md | 4 +- docs/ru/docs/features.md | 2 +- docs/ru/docs/help-fastapi.md | 4 +- docs/ru/docs/tutorial/body-fields.md | 8 +- docs/ru/docs/tutorial/body-multiple-params.md | 22 +++--- docs/ru/docs/tutorial/body-nested-models.md | 6 +- docs/ru/docs/tutorial/body-updates.md | 6 +- docs/ru/docs/tutorial/body.md | 6 +- docs/ru/docs/tutorial/cookie-params.md | 4 +- docs/ru/docs/tutorial/cors.md | 2 +- docs/ru/docs/tutorial/debugging.md | 2 +- .../dependencies/classes-as-dependencies.md | 42 +++++------ .../dependencies/dependencies-with-yield.md | 26 +++---- .../dependencies/global-dependencies.md | 2 +- docs/ru/docs/tutorial/dependencies/index.md | 22 +++--- .../tutorial/dependencies/sub-dependencies.md | 18 ++--- docs/ru/docs/tutorial/encoder.md | 2 +- docs/ru/docs/tutorial/extra-models.md | 6 +- docs/ru/docs/tutorial/first-steps.md | 12 +-- docs/ru/docs/tutorial/handling-errors.md | 8 +- docs/ru/docs/tutorial/header-params.md | 24 +++--- docs/ru/docs/tutorial/index.md | 2 +- docs/ru/docs/tutorial/metadata.md | 6 +- .../tutorial/path-operation-configuration.md | 8 +- .../path-params-numeric-validations.md | 28 +++---- docs/ru/docs/tutorial/path-params.md | 16 ++-- .../tutorial/query-params-str-validations.md | 74 +++++++++---------- docs/ru/docs/tutorial/query-params.md | 4 +- docs/ru/docs/tutorial/request-files.md | 36 ++++----- .../docs/tutorial/request-forms-and-files.md | 8 +- docs/ru/docs/tutorial/request-forms.md | 14 ++-- docs/ru/docs/tutorial/response-model.md | 18 ++--- docs/ru/docs/tutorial/response-status-code.md | 12 +-- docs/ru/docs/tutorial/security/first-steps.md | 20 ++--- docs/ru/docs/tutorial/security/index.md | 4 +- docs/ru/docs/tutorial/static-files.md | 2 +- docs/ru/docs/tutorial/testing.md | 14 ++-- docs/tr/docs/advanced/index.md | 2 +- docs/tr/docs/advanced/security/index.md | 2 +- docs/tr/docs/advanced/testing-websockets.md | 2 +- docs/tr/docs/alternatives.md | 50 ++++++------- docs/tr/docs/async.md | 2 +- docs/tr/docs/how-to/index.md | 2 +- docs/tr/docs/python-types.md | 4 +- docs/tr/docs/tutorial/cookie-params.md | 12 +-- docs/tr/docs/tutorial/first-steps.md | 12 +-- docs/tr/docs/tutorial/path-params.md | 16 ++-- docs/tr/docs/tutorial/query-params.md | 4 +- docs/tr/docs/tutorial/request-forms.md | 10 +-- docs/tr/docs/tutorial/static-files.md | 2 +- docs/uk/docs/alternatives.md | 50 ++++++------- docs/uk/docs/tutorial/body-fields.md | 2 +- docs/uk/docs/tutorial/cookie-params.md | 2 +- docs/uk/docs/tutorial/encoder.md | 2 +- docs/uk/docs/tutorial/first-steps.md | 10 +-- docs/vi/docs/tutorial/first-steps.md | 2 +- .../docs/advanced/additional-status-codes.md | 4 +- .../zh/docs/advanced/advanced-dependencies.md | 2 +- docs/zh/docs/advanced/behind-a-proxy.md | 14 ++-- docs/zh/docs/advanced/custom-response.md | 20 ++--- docs/zh/docs/advanced/dataclasses.md | 2 +- docs/zh/docs/advanced/events.md | 8 +- docs/zh/docs/advanced/middleware.md | 2 +- docs/zh/docs/advanced/openapi-callbacks.md | 10 +-- docs/zh/docs/advanced/response-cookies.md | 2 +- docs/zh/docs/advanced/response-directly.md | 4 +- docs/zh/docs/advanced/response-headers.md | 2 +- docs/zh/docs/advanced/security/index.md | 2 +- .../docs/advanced/security/oauth2-scopes.md | 14 ++-- docs/zh/docs/advanced/templates.md | 6 +- docs/zh/docs/advanced/testing-dependencies.md | 4 +- docs/zh/docs/advanced/testing-websockets.md | 2 +- .../docs/advanced/using-request-directly.md | 4 +- docs/zh/docs/advanced/websockets.md | 2 +- docs/zh/docs/contributing.md | 2 +- docs/zh/docs/fastapi-cli.md | 2 +- docs/zh/docs/help-fastapi.md | 2 +- docs/zh/docs/tutorial/bigger-applications.md | 4 +- docs/zh/docs/tutorial/body-fields.md | 6 +- docs/zh/docs/tutorial/body-updates.md | 6 +- docs/zh/docs/tutorial/body.md | 6 +- docs/zh/docs/tutorial/cookie-params.md | 4 +- docs/zh/docs/tutorial/cors.md | 2 +- ...pendencies-in-path-operation-decorators.md | 4 +- .../dependencies/dependencies-with-yield.md | 4 +- docs/zh/docs/tutorial/dependencies/index.md | 6 +- .../tutorial/dependencies/sub-dependencies.md | 4 +- docs/zh/docs/tutorial/extra-models.md | 6 +- docs/zh/docs/tutorial/first-steps.md | 4 +- docs/zh/docs/tutorial/handling-errors.md | 8 +- docs/zh/docs/tutorial/header-params.md | 6 +- docs/zh/docs/tutorial/metadata.md | 4 +- docs/zh/docs/tutorial/middleware.md | 4 +- .../tutorial/path-operation-configuration.md | 8 +- .../path-params-numeric-validations.md | 2 +- docs/zh/docs/tutorial/path-params.md | 16 ++-- docs/zh/docs/tutorial/query-params.md | 6 +- docs/zh/docs/tutorial/request-files.md | 16 ++-- .../docs/tutorial/request-forms-and-files.md | 4 +- docs/zh/docs/tutorial/request-forms.md | 10 +-- docs/zh/docs/tutorial/response-model.md | 2 +- docs/zh/docs/tutorial/response-status-code.md | 12 +-- docs/zh/docs/tutorial/security/first-steps.md | 14 ++-- .../tutorial/security/get-current-user.md | 4 +- docs/zh/docs/tutorial/security/oauth2-jwt.md | 12 +-- .../docs/tutorial/security/simple-oauth2.md | 16 ++-- docs/zh/docs/tutorial/sql-databases.md | 6 +- docs/zh/docs/tutorial/static-files.md | 2 +- docs/zh/docs/tutorial/testing.md | 14 ++-- 433 files changed, 1799 insertions(+), 1799 deletions(-) diff --git a/docs/de/docs/advanced/additional-responses.md b/docs/de/docs/advanced/additional-responses.md index a87c56491..29a7b064a 100644 --- a/docs/de/docs/advanced/additional-responses.md +++ b/docs/de/docs/advanced/additional-responses.md @@ -1,6 +1,6 @@ # Zusätzliche Responses in OpenAPI -/// warning | "Achtung" +/// warning | Achtung Dies ist ein eher fortgeschrittenes Thema. @@ -30,7 +30,7 @@ Um beispielsweise eine weitere Response mit dem Statuscode `404` und einem Pydan {!../../docs_src/additional_responses/tutorial001.py!} ``` -/// note | "Hinweis" +/// note | Hinweis Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen. @@ -181,7 +181,7 @@ Sie können beispielsweise einen zusätzlichen Medientyp `image/png` hinzufügen {!../../docs_src/additional_responses/tutorial002.py!} ``` -/// note | "Hinweis" +/// note | Hinweis Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben müssen. diff --git a/docs/de/docs/advanced/additional-status-codes.md b/docs/de/docs/advanced/additional-status-codes.md index fc8d09e4c..50702e7e6 100644 --- a/docs/de/docs/advanced/additional-status-codes.md +++ b/docs/de/docs/advanced/additional-status-codes.md @@ -40,7 +40,7 @@ Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -54,7 +54,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -66,7 +66,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// -/// warning | "Achtung" +/// warning | Achtung Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben. @@ -76,7 +76,7 @@ Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte /// -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.responses import JSONResponse` verwenden. diff --git a/docs/de/docs/advanced/advanced-dependencies.md b/docs/de/docs/advanced/advanced-dependencies.md index 54351714e..80cbf1fd3 100644 --- a/docs/de/docs/advanced/advanced-dependencies.md +++ b/docs/de/docs/advanced/advanced-dependencies.md @@ -36,7 +36,7 @@ Dazu deklarieren wir eine Methode `__call__`: //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -72,7 +72,7 @@ Und jetzt können wir `__init__` verwenden, um die Parameter der Instanz zu dekl //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -108,7 +108,7 @@ Wir könnten eine Instanz dieser Klasse erstellen mit: //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -152,7 +152,7 @@ checker(q="somequery") //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -164,7 +164,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// -/// tip | "Tipp" +/// tip | Tipp Das alles mag gekünstelt wirken. Und es ist möglicherweise noch nicht ganz klar, welchen Nutzen das hat. diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md index 6c1981e25..c118e588f 100644 --- a/docs/de/docs/advanced/async-tests.md +++ b/docs/de/docs/advanced/async-tests.md @@ -62,7 +62,7 @@ Der Marker `@pytest.mark.anyio` teilt pytest mit, dass diese Testfunktion asynch {* ../../docs_src/async_tests/test_main.py hl[7] *} -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wie zuvor, wenn Sie den `TestClient` verwenden. @@ -80,13 +80,13 @@ response = client.get('/') ... welches wir verwendet haben, um unsere Requests mit dem `TestClient` zu machen. -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass wir async/await mit dem neuen `AsyncClient` verwenden – der Request ist asynchron. /// -/// warning | "Achtung" +/// warning | Achtung Falls Ihre Anwendung auf Lifespan-Events angewiesen ist, der `AsyncClient` löst diese Events nicht aus. Um sicherzustellen, dass sie ausgelöst werden, verwenden Sie `LifespanManager` von florimondmanca/asgi-lifespan. @@ -96,7 +96,7 @@ Falls Ihre Anwendung auf Lifespan-Events angewiesen ist, der `AsyncClient` löst Da die Testfunktion jetzt asynchron ist, können Sie in Ihren Tests neben dem Senden von Requests an Ihre FastAPI-Anwendung jetzt auch andere `async`hrone Funktionen aufrufen (und `await`en), genau so, wie Sie diese an anderer Stelle in Ihrem Code aufrufen würden. -/// tip | "Tipp" +/// tip | Tipp Wenn Sie einen `RuntimeError: Task attached to a different loop` erhalten, wenn Sie asynchrone Funktionsaufrufe in Ihre Tests integrieren (z. B. bei Verwendung von MongoDBs MotorClient), dann denken Sie daran, Objekte zu instanziieren, die einen Event Loop nur innerhalb asynchroner Funktionen benötigen, z. B. einen `@app.on_event("startup")`-Callback. diff --git a/docs/de/docs/advanced/behind-a-proxy.md b/docs/de/docs/advanced/behind-a-proxy.md index 74b25308a..9da18a626 100644 --- a/docs/de/docs/advanced/behind-a-proxy.md +++ b/docs/de/docs/advanced/behind-a-proxy.md @@ -43,7 +43,7 @@ browser --> proxy proxy --> server ``` -/// tip | "Tipp" +/// tip | Tipp Die IP `0.0.0.0` wird üblicherweise verwendet, um anzudeuten, dass das Programm alle auf diesem Computer/Server verfügbaren IPs abhört. @@ -84,7 +84,7 @@ $ uvicorn main:app --root-path /api/v1 Falls Sie Hypercorn verwenden, das hat auch die Option `--root-path`. -/// note | "Technische Details" +/// note | Technische Details Die ASGI-Spezifikation definiert einen `root_path` für diesen Anwendungsfall. @@ -178,7 +178,7 @@ Dann erstellen Sie eine Datei `traefik.toml` mit: Dadurch wird Traefik angewiesen, Port 9999 abzuhören und eine andere Datei `routes.toml` zu verwenden. -/// tip | "Tipp" +/// tip | Tipp Wir verwenden Port 9999 anstelle des Standard-HTTP-Ports 80, damit Sie ihn nicht mit Administratorrechten (`sudo`) ausführen müssen. @@ -248,7 +248,7 @@ Wenn Sie nun zur URL mit dem Port für Uvicorn gehen: -/// tip | "Tipp" +/// tip | Tipp Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server. diff --git a/docs/de/docs/advanced/custom-response.md b/docs/de/docs/advanced/custom-response.md index 357d2c562..7738bfca4 100644 --- a/docs/de/docs/advanced/custom-response.md +++ b/docs/de/docs/advanced/custom-response.md @@ -12,7 +12,7 @@ Der Inhalt, den Sie von Ihrer *Pfadoperation-Funktion* zurückgeben, wird in die Und wenn diese `Response` einen JSON-Medientyp (`application/json`) hat, wie es bei `JSONResponse` und `UJSONResponse` der Fall ist, werden die von Ihnen zurückgegebenen Daten automatisch mit jedem Pydantic `response_model` konvertiert (und gefiltert), das Sie im *Pfadoperation-Dekorator* deklariert haben. -/// note | "Hinweis" +/// note | Hinweis Wenn Sie eine Response-Klasse ohne Medientyp verwenden, erwartet FastAPI, dass Ihre Response keinen Inhalt hat, und dokumentiert daher das Format der Response nicht in deren generierter OpenAPI-Dokumentation. @@ -44,7 +44,7 @@ Und er wird als solcher in OpenAPI dokumentiert. /// -/// tip | "Tipp" +/// tip | Tipp Die `ORJSONResponse` ist derzeit nur in FastAPI verfügbar, nicht in Starlette. @@ -81,7 +81,7 @@ Das gleiche Beispiel von oben, das eine `HTMLResponse` zurückgibt, könnte so a {!../../docs_src/custom_response/tutorial003.py!} ``` -/// warning | "Achtung" +/// warning | Achtung Eine `Response`, die direkt von Ihrer *Pfadoperation-Funktion* zurückgegeben wird, wird in OpenAPI nicht dokumentiert (zum Beispiel wird der `Content-Type` nicht dokumentiert) und ist in der automatischen interaktiven Dokumentation nicht sichtbar. @@ -121,7 +121,7 @@ Hier sind einige der verfügbaren Responses. Bedenken Sie, dass Sie `Response` verwenden können, um alles andere zurückzugeben, oder sogar eine benutzerdefinierte Unterklasse zu erstellen. -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.responses import HTMLResponse` verwenden. @@ -174,7 +174,7 @@ Eine schnelle alternative JSON-Response mit `ujson`. -/// warning | "Achtung" +/// warning | Achtung `ujson` ist bei der Behandlung einiger Sonderfälle weniger sorgfältig als Pythons eingebaute Implementierung. @@ -184,7 +184,7 @@ Eine alternative JSON-Response mit -/// tip | "Tipp" +/// tip | Tipp Beachten Sie die automatische Vervollständigung für `name` und `price`, welche in der FastAPI-Anwendung im `Item`-Modell definiert wurden. diff --git a/docs/de/docs/advanced/index.md b/docs/de/docs/advanced/index.md index 953ad317d..d93cd5fe8 100644 --- a/docs/de/docs/advanced/index.md +++ b/docs/de/docs/advanced/index.md @@ -6,7 +6,7 @@ Das Haupt-[Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link t In den nächsten Abschnitten sehen Sie weitere Optionen, Konfigurationen und zusätzliche Funktionen. -/// tip | "Tipp" +/// tip | Tipp Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. diff --git a/docs/de/docs/advanced/middleware.md b/docs/de/docs/advanced/middleware.md index b4001efda..d2130c9b7 100644 --- a/docs/de/docs/advanced/middleware.md +++ b/docs/de/docs/advanced/middleware.md @@ -43,7 +43,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** enthält mehrere Middlewares für gängige Anwendungsfälle. Wir werden als Nächstes sehen, wie man sie verwendet. -/// note | "Technische Details" +/// note | Technische Details Für die nächsten Beispiele könnten Sie auch `from starlette.middleware.something import SomethingMiddleware` verwenden. diff --git a/docs/de/docs/advanced/openapi-callbacks.md b/docs/de/docs/advanced/openapi-callbacks.md index f407d5450..4ee2874a3 100644 --- a/docs/de/docs/advanced/openapi-callbacks.md +++ b/docs/de/docs/advanced/openapi-callbacks.md @@ -35,7 +35,7 @@ Dieser Teil ist ziemlich normal, der größte Teil des Codes ist Ihnen wahrschei {!../../docs_src/openapi_callbacks/tutorial001.py!} ``` -/// tip | "Tipp" +/// tip | Tipp Der Query-Parameter `callback_url` verwendet einen Pydantic-Url-Typ. @@ -64,7 +64,7 @@ Diese Dokumentation wird in der Swagger-Oberfläche unter `/docs` in Ihrer API a In diesem Beispiel wird nicht der Callback selbst implementiert (das könnte nur eine Codezeile sein), sondern nur der Dokumentationsteil. -/// tip | "Tipp" +/// tip | Tipp Der eigentliche Callback ist nur ein HTTP-Request. @@ -80,7 +80,7 @@ Sie wissen jedoch bereits, wie Sie mit **FastAPI** ganz einfach eine automatisch Daher werden wir dasselbe Wissen nutzen, um zu dokumentieren, wie die *externe API* aussehen sollte ... indem wir die *Pfadoperation(en)* erstellen, welche die externe API implementieren soll (die, welche Ihre API aufruft). -/// tip | "Tipp" +/// tip | Tipp Wenn Sie den Code zum Dokumentieren eines Callbacks schreiben, kann es hilfreich sein, sich vorzustellen, dass Sie dieser *externe Entwickler* sind. Und dass Sie derzeit die *externe API* implementieren, nicht *Ihre API*. @@ -163,7 +163,7 @@ und sie würde eine Response von dieser *externen API* mit einem JSON-Body wie d } ``` -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass die verwendete Callback-URL die URL enthält, die als Query-Parameter in `callback_url` (`https://www.external.org/events`) empfangen wurde, und auch die Rechnungs-`id` aus dem JSON-Body (`2expen51ve`). @@ -179,7 +179,7 @@ Verwenden Sie nun den Parameter `callbacks` im *Pfadoperation-Dekorator Ihrer AP {!../../docs_src/openapi_callbacks/tutorial001.py!} ``` -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass Sie nicht den Router selbst (`invoices_callback_router`) an `callback=` übergeben, sondern das Attribut `.routes`, wie in `invoices_callback_router.routes`. diff --git a/docs/de/docs/advanced/path-operation-advanced-configuration.md b/docs/de/docs/advanced/path-operation-advanced-configuration.md index 2d8b88be5..53d395724 100644 --- a/docs/de/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/de/docs/advanced/path-operation-advanced-configuration.md @@ -2,7 +2,7 @@ ## OpenAPI operationId -/// warning | "Achtung" +/// warning | Achtung Wenn Sie kein „Experte“ für OpenAPI sind, brauchen Sie dies wahrscheinlich nicht. @@ -26,13 +26,13 @@ Sie sollten dies tun, nachdem Sie alle Ihre *Pfadoperationen* hinzugefügt haben {!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -/// tip | "Tipp" +/// tip | Tipp Wenn Sie `app.openapi()` manuell aufrufen, sollten Sie vorher die `operationId`s aktualisiert haben. /// -/// warning | "Achtung" +/// warning | Achtung Wenn Sie dies tun, müssen Sie sicherstellen, dass jede Ihrer *Pfadoperation-Funktionen* einen eindeutigen Namen hat. @@ -74,7 +74,7 @@ Es gibt hier in der Dokumentation ein ganzes Kapitel darüber, Sie können es un Wenn Sie in Ihrer Anwendung eine *Pfadoperation* deklarieren, generiert **FastAPI** automatisch die relevanten Metadaten dieser *Pfadoperation*, die in das OpenAPI-Schema aufgenommen werden sollen. -/// note | "Technische Details" +/// note | Technische Details In der OpenAPI-Spezifikation wird das Operationsobjekt genannt. @@ -86,7 +86,7 @@ Es enthält `tags`, `parameters`, `requestBody`, `responses`, usw. Dieses *Pfadoperation*-spezifische OpenAPI-Schema wird normalerweise automatisch von **FastAPI** generiert, Sie können es aber auch erweitern. -/// tip | "Tipp" +/// tip | Tipp Dies ist ein Low-Level Erweiterungspunkt. @@ -215,7 +215,7 @@ In Pydantic Version 1 war die Methode zum Parsen und Validieren eines Objekts `I /// -/// tip | "Tipp" +/// tip | Tipp Hier verwenden wir dasselbe Pydantic-Modell wieder. diff --git a/docs/de/docs/advanced/response-cookies.md b/docs/de/docs/advanced/response-cookies.md index ba100870d..6f9d66e07 100644 --- a/docs/de/docs/advanced/response-cookies.md +++ b/docs/de/docs/advanced/response-cookies.md @@ -30,7 +30,7 @@ Setzen Sie dann Cookies darin und geben Sie sie dann zurück: {!../../docs_src/response_cookies/tutorial001.py!} ``` -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass, wenn Sie eine Response direkt zurückgeben, anstatt den `Response`-Parameter zu verwenden, FastAPI diese direkt zurückgibt. @@ -42,7 +42,7 @@ Und auch, dass Sie keine Daten senden, die durch ein `response_model` hätten ge ### Mehr Informationen -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. diff --git a/docs/de/docs/advanced/response-directly.md b/docs/de/docs/advanced/response-directly.md index 70c045f57..fab2e3965 100644 --- a/docs/de/docs/advanced/response-directly.md +++ b/docs/de/docs/advanced/response-directly.md @@ -14,7 +14,7 @@ Das kann beispielsweise nützlich sein, um benutzerdefinierte Header oder Cookie Tatsächlich können Sie jede `Response` oder jede Unterklasse davon zurückgeben. -/// tip | "Tipp" +/// tip | Tipp `JSONResponse` selbst ist eine Unterklasse von `Response`. @@ -38,7 +38,7 @@ In diesen Fällen können Sie den `jsonable_encoder` verwenden, um Ihre Daten zu {!../../docs_src/response_directly/tutorial001.py!} ``` -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.responses import JSONResponse` verwenden. diff --git a/docs/de/docs/advanced/response-headers.md b/docs/de/docs/advanced/response-headers.md index 31c2c9c98..ca1a28fa4 100644 --- a/docs/de/docs/advanced/response-headers.md +++ b/docs/de/docs/advanced/response-headers.md @@ -28,7 +28,7 @@ Erstellen Sie eine Response wie in [Eine Response direkt zurückgeben](response- {!../../docs_src/response_headers/tutorial001.py!} ``` -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. diff --git a/docs/de/docs/advanced/security/index.md b/docs/de/docs/advanced/security/index.md index 380e48bbf..25eeb25b5 100644 --- a/docs/de/docs/advanced/security/index.md +++ b/docs/de/docs/advanced/security/index.md @@ -4,7 +4,7 @@ Neben den in [Tutorial – Benutzerhandbuch: Sicherheit](../../tutorial/security/index.md){.internal-link target=_blank} behandelten Funktionen gibt es noch einige zusätzliche Funktionen zur Handhabung der Sicherheit. -/// tip | "Tipp" +/// tip | Tipp Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. diff --git a/docs/de/docs/advanced/security/oauth2-scopes.md b/docs/de/docs/advanced/security/oauth2-scopes.md index c0af2560a..85175a895 100644 --- a/docs/de/docs/advanced/security/oauth2-scopes.md +++ b/docs/de/docs/advanced/security/oauth2-scopes.md @@ -10,7 +10,7 @@ Jedes Mal, wenn Sie sich mit Facebook, Google, GitHub, Microsoft oder Twitter an In diesem Abschnitt erfahren Sie, wie Sie Authentifizierung und Autorisierung mit demselben OAuth2, mit Scopes in Ihrer **FastAPI**-Anwendung verwalten. -/// warning | "Achtung" +/// warning | Achtung Dies ist ein mehr oder weniger fortgeschrittener Abschnitt. Wenn Sie gerade erst anfangen, können Sie ihn überspringen. @@ -88,7 +88,7 @@ Sehen wir uns zunächst kurz die Teile an, die sich gegenüber den Beispielen im //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -102,7 +102,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.9+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -116,7 +116,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -162,7 +162,7 @@ Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und des //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -176,7 +176,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.9+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -190,7 +190,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -218,7 +218,7 @@ Wir verwenden immer noch dasselbe `OAuth2PasswordRequestForm`. Es enthält eine Und wir geben die Scopes als Teil des JWT-Tokens zurück. -/// danger | "Gefahr" +/// danger | Gefahr Der Einfachheit halber fügen wir hier die empfangenen Scopes direkt zum Token hinzu. @@ -252,7 +252,7 @@ Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwe //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -266,7 +266,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.9+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -280,7 +280,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -308,7 +308,7 @@ Und die Abhängigkeitsfunktion `get_current_active_user` kann auch Unterabhängi In diesem Fall erfordert sie den Scope `me` (sie könnte mehr als einen Scope erfordern). -/// note | "Hinweis" +/// note | Hinweis Sie müssen nicht unbedingt an verschiedenen Stellen verschiedene Scopes hinzufügen. @@ -342,7 +342,7 @@ Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -356,7 +356,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.9+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -370,7 +370,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -382,7 +382,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// -/// info | "Technische Details" +/// info | Technische Details `Security` ist tatsächlich eine Unterklasse von `Depends` und hat nur noch einen zusätzlichen Parameter, den wir später kennenlernen werden. @@ -432,7 +432,7 @@ Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um d //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -446,7 +446,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.9+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -460,7 +460,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -510,7 +510,7 @@ In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als du //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -524,7 +524,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.9+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -538,7 +538,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -590,7 +590,7 @@ Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, u //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -604,7 +604,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.9+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -618,7 +618,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -662,7 +662,7 @@ Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -676,7 +676,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.9+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -690,7 +690,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -727,7 +727,7 @@ So sieht die Hierarchie der Abhängigkeiten und Scopes aus: * `security_scopes.scopes` enthält `["me"]` für die *Pfadoperation* `read_users_me`, da das in der Abhängigkeit `get_current_active_user` deklariert ist. * `security_scopes.scopes` wird `[]` (nichts) für die *Pfadoperation* `read_system_status` enthalten, da diese keine `Security` mit `scopes` deklariert hat, und deren Abhängigkeit `get_current_user` ebenfalls keinerlei `scopes` deklariert. -/// tip | "Tipp" +/// tip | Tipp Das Wichtige und „Magische“ hier ist, dass `get_current_user` für jede *Pfadoperation* eine andere Liste von `scopes` hat, die überprüft werden. @@ -771,7 +771,7 @@ Am häufigsten ist der „Implicit“-Flow. Am sichersten ist der „Code“-Flow, die Implementierung ist jedoch komplexer, da mehr Schritte erforderlich sind. Da er komplexer ist, schlagen viele Anbieter letztendlich den „Implicit“-Flow vor. -/// note | "Hinweis" +/// note | Hinweis Es ist üblich, dass jeder Authentifizierungsanbieter seine Flows anders benennt, um sie zu einem Teil seiner Marke zu machen. diff --git a/docs/de/docs/advanced/settings.md b/docs/de/docs/advanced/settings.md index 8b9ba2f48..c90f74844 100644 --- a/docs/de/docs/advanced/settings.md +++ b/docs/de/docs/advanced/settings.md @@ -8,7 +8,7 @@ Aus diesem Grund werden diese üblicherweise in Umgebungsvariablen bereitgestell ## Umgebungsvariablen -/// tip | "Tipp" +/// tip | Tipp Wenn Sie bereits wissen, was „Umgebungsvariablen“ sind und wie man sie verwendet, können Sie gerne mit dem nächsten Abschnitt weiter unten fortfahren. @@ -67,7 +67,7 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -/// tip | "Tipp" +/// tip | Tipp Das zweite Argument für `os.getenv()` ist der zurückzugebende Defaultwert. @@ -124,7 +124,7 @@ Hello World from Python -/// tip | "Tipp" +/// tip | Tipp Weitere Informationen dazu finden Sie unter The Twelve-Factor App: Config. @@ -200,7 +200,7 @@ In Pydantic v1 würden Sie `BaseSettings` direkt von `pydantic` statt von `pydan //// -/// tip | "Tipp" +/// tip | Tipp Für ein schnelles Copy-and-paste verwenden Sie nicht dieses Beispiel, sondern das letzte unten. @@ -232,7 +232,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app -/// tip | "Tipp" +/// tip | Tipp Um mehrere Umgebungsvariablen für einen einzelnen Befehl festzulegen, trennen Sie diese einfach durch ein Leerzeichen und fügen Sie alle vor dem Befehl ein. @@ -260,7 +260,7 @@ Und dann verwenden Sie diese in einer Datei `main.py`: {!../../docs_src/settings/app01/main.py!} ``` -/// tip | "Tipp" +/// tip | Tipp Sie benötigen außerdem eine Datei `__init__.py`, wie in [Größere Anwendungen – mehrere Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gesehen. @@ -304,7 +304,7 @@ Jetzt erstellen wir eine Abhängigkeit, die ein neues `config.Settings()` zurüc //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -316,7 +316,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// -/// tip | "Tipp" +/// tip | Tipp Wir werden das `@lru_cache` in Kürze besprechen. @@ -344,7 +344,7 @@ Und dann können wir das von der *Pfadoperation-Funktion* als Abhängigkeit einf //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -374,7 +374,7 @@ Wenn Sie viele Einstellungen haben, die sich möglicherweise oft ändern, vielle Diese Praxis ist so weit verbreitet, dass sie einen Namen hat. Diese Umgebungsvariablen werden üblicherweise in einer Datei `.env` abgelegt und die Datei wird „dotenv“ genannt. -/// tip | "Tipp" +/// tip | Tipp Eine Datei, die mit einem Punkt (`.`) beginnt, ist eine versteckte Datei in Unix-ähnlichen Systemen wie Linux und macOS. @@ -384,7 +384,7 @@ Aber eine dotenv-Datei muss nicht unbedingt genau diesen Dateinamen haben. Pydantic unterstützt das Lesen dieser Dateitypen mithilfe einer externen Bibliothek. Weitere Informationen finden Sie unter Pydantic Settings: Dotenv (.env) support. -/// tip | "Tipp" +/// tip | Tipp Damit das funktioniert, müssen Sie `pip install python-dotenv` ausführen. @@ -409,7 +409,7 @@ Und dann aktualisieren Sie Ihre `config.py` mit: {!> ../../docs_src/settings/app03_an/config.py!} ``` -/// tip | "Tipp" +/// tip | Tipp Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter Pydantic: Configuration. @@ -423,7 +423,7 @@ Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. {!> ../../docs_src/settings/app03_an/config_pv1.py!} ``` -/// tip | "Tipp" +/// tip | Tipp Die Klasse `Config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter Pydantic Model Config. @@ -480,7 +480,7 @@ Da wir jedoch den `@lru_cache`-Dekorator oben verwenden, wird das `Settings`-Obj //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. diff --git a/docs/de/docs/advanced/templates.md b/docs/de/docs/advanced/templates.md index 6cb3fcf6c..658a2592e 100644 --- a/docs/de/docs/advanced/templates.md +++ b/docs/de/docs/advanced/templates.md @@ -31,7 +31,7 @@ $ pip install jinja2 {!../../docs_src/templates/tutorial001.py!} ``` -/// note | "Hinweis" +/// note | Hinweis Vor FastAPI 0.108.0 und Starlette 0.29.0 war `name` der erste Parameter. @@ -39,13 +39,13 @@ Außerdem wurde in früheren Versionen das `request`-Objekt als Teil der Schlüs /// -/// tip | "Tipp" +/// tip | Tipp Durch die Deklaration von `response_class=HTMLResponse` kann die Dokumentationsoberfläche erkennen, dass die Response HTML sein wird. /// -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.templating import Jinja2Templates` verwenden. diff --git a/docs/de/docs/advanced/testing-dependencies.md b/docs/de/docs/advanced/testing-dependencies.md index c565b30f2..3b4604da3 100644 --- a/docs/de/docs/advanced/testing-dependencies.md +++ b/docs/de/docs/advanced/testing-dependencies.md @@ -54,7 +54,7 @@ Und dann ruft **FastAPI** diese Überschreibung anstelle der ursprünglichen Abh //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -68,7 +68,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -80,7 +80,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// -/// tip | "Tipp" +/// tip | Tipp Sie können eine Überschreibung für eine Abhängigkeit festlegen, die an einer beliebigen Stelle in Ihrer **FastAPI**-Anwendung verwendet wird. @@ -96,7 +96,7 @@ Anschließend können Sie Ihre Überschreibungen zurücksetzen (entfernen), inde app.dependency_overrides = {} ``` -/// tip | "Tipp" +/// tip | Tipp Wenn Sie eine Abhängigkeit nur während einiger Tests überschreiben möchten, können Sie die Überschreibung zu Beginn des Tests (innerhalb der Testfunktion) festlegen und am Ende (am Ende der Testfunktion) zurücksetzen. diff --git a/docs/de/docs/advanced/testing-websockets.md b/docs/de/docs/advanced/testing-websockets.md index 7ae7d92d6..5122e1f33 100644 --- a/docs/de/docs/advanced/testing-websockets.md +++ b/docs/de/docs/advanced/testing-websockets.md @@ -8,7 +8,7 @@ Dazu verwenden Sie den `TestClient` in einer `with`-Anweisung, eine Verbindung z {!../../docs_src/app_testing/tutorial002.py!} ``` -/// note | "Hinweis" +/// note | Hinweis Weitere Informationen finden Sie in der Starlette-Dokumentation zum Testen von WebSockets. diff --git a/docs/de/docs/advanced/using-request-directly.md b/docs/de/docs/advanced/using-request-directly.md index 6a0b96680..1c2a6f852 100644 --- a/docs/de/docs/advanced/using-request-directly.md +++ b/docs/de/docs/advanced/using-request-directly.md @@ -35,7 +35,7 @@ Dazu müssen Sie direkt auf den Request zugreifen. Durch die Deklaration eines *Pfadoperation-Funktionsparameters*, dessen Typ der `Request` ist, weiß **FastAPI**, dass es den `Request` diesem Parameter übergeben soll. -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass wir in diesem Fall einen Pfad-Parameter zusätzlich zum Request-Parameter deklarieren. @@ -49,7 +49,7 @@ Auf die gleiche Weise können Sie wie gewohnt jeden anderen Parameter deklariere Weitere Details zum `Request`-Objekt finden Sie in der offiziellen Starlette-Dokumentation. -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.requests import Request` verwenden. diff --git a/docs/de/docs/advanced/websockets.md b/docs/de/docs/advanced/websockets.md index cf13fa23c..5bc5f6902 100644 --- a/docs/de/docs/advanced/websockets.md +++ b/docs/de/docs/advanced/websockets.md @@ -50,7 +50,7 @@ Erstellen Sie in Ihrer **FastAPI**-Anwendung einen `websocket`: {!../../docs_src/websockets/tutorial001.py!} ``` -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.websockets import WebSocket` verwenden. @@ -141,7 +141,7 @@ Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfa //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -155,7 +155,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -196,7 +196,7 @@ Dort können Sie einstellen: * Die „Item ID“, die im Pfad verwendet wird. * Das „Token“, das als Query-Parameter verwendet wird. -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass der Query-„Token“ von einer Abhängigkeit verarbeitet wird. @@ -238,7 +238,7 @@ Das wird die Ausnahme `WebSocketDisconnect` auslösen und alle anderen Clients e Client #1596980209979 left the chat ``` -/// tip | "Tipp" +/// tip | Tipp Die obige Anwendung ist ein minimales und einfaches Beispiel, das zeigt, wie Nachrichten verarbeitet und an mehrere WebSocket-Verbindungen gesendet werden. diff --git a/docs/de/docs/alternatives.md b/docs/de/docs/alternatives.md index 49e1cc6f0..611315501 100644 --- a/docs/de/docs/alternatives.md +++ b/docs/de/docs/alternatives.md @@ -30,13 +30,13 @@ Es wird von vielen Unternehmen verwendet, darunter Mozilla, Red Hat und Eventbri Es war eines der ersten Beispiele für **automatische API-Dokumentation**, und dies war insbesondere eine der ersten Ideen, welche „die Suche nach“ **FastAPI** inspirierten. -/// note | "Hinweis" +/// note | Hinweis Das Django REST Framework wurde von Tom Christie erstellt. Derselbe Schöpfer von Starlette und Uvicorn, auf denen **FastAPI** basiert. /// -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Eine automatische API-Dokumentationsoberfläche zu haben. @@ -56,7 +56,7 @@ Diese Entkopplung der Teile und die Tatsache, dass es sich um ein „Mikroframew Angesichts der Einfachheit von Flask schien es eine gute Ergänzung zum Erstellen von APIs zu sein. Als Nächstes musste ein „Django REST Framework“ für Flask gefunden werden. -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Ein Mikroframework zu sein. Es einfach zu machen, die benötigten Tools und Teile zu kombinieren. @@ -98,7 +98,7 @@ def read_url(): Sehen Sie sich die Ähnlichkeiten in `requests.get(...)` und `@app.get(...)` an. -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** * Über eine einfache und intuitive API zu verfügen. * HTTP-Methodennamen (Operationen) direkt, auf einfache und intuitive Weise zu verwenden. @@ -118,7 +118,7 @@ Irgendwann wurde Swagger an die Linux Foundation übergeben und in OpenAPI umben Aus diesem Grund spricht man bei Version 2.0 häufig von „Swagger“ und ab Version 3 von „OpenAPI“. -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Einen offenen Standard für API-Spezifikationen zu übernehmen und zu verwenden, anstelle eines benutzerdefinierten Schemas. @@ -147,7 +147,7 @@ Für diese Funktionen wurde Marshmallow entwickelt. Es ist eine großartige Bibl Aber sie wurde erstellt, bevor Typhinweise in Python existierten. Um also ein Schema zu definieren, müssen Sie bestimmte Werkzeuge und Klassen verwenden, die von Marshmallow bereitgestellt werden. -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Code zu verwenden, um „Schemas“ zu definieren, welche Datentypen und Validierung automatisch bereitstellen. @@ -169,7 +169,7 @@ Webargs wurde von denselben Marshmallow-Entwicklern erstellt. /// -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Eingehende Requestdaten automatisch zu validieren. @@ -199,7 +199,7 @@ APISpec wurde von denselben Marshmallow-Entwicklern erstellt. /// -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Den offenen Standard für APIs, OpenAPI, zu unterstützen. @@ -231,7 +231,7 @@ Flask-apispec wurde von denselben Marshmallow-Entwicklern erstellt. /// -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Das OpenAPI-Schema automatisch zu generieren, aus demselben Code, welcher die Serialisierung und Validierung definiert. @@ -251,7 +251,7 @@ Da TypeScript-Daten jedoch nach der Kompilierung nach JavaScript nicht erhalten Es kann nicht sehr gut mit verschachtelten Modellen umgehen. Wenn es sich beim JSON-Body in der Anfrage also um ein JSON-Objekt mit inneren Feldern handelt, die wiederum verschachtelte JSON-Objekte sind, kann er nicht richtig dokumentiert und validiert werden. -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Python-Typen zu verwenden, um eine hervorragende Editorunterstützung zu erhalten. @@ -263,7 +263,7 @@ Python-Typen zu verwenden, um eine hervorragende Editorunterstützung zu erhalte Es war eines der ersten extrem schnellen Python-Frameworks, welches auf `asyncio` basierte. Es wurde so gestaltet, dass es Flask sehr ähnlich ist. -/// note | "Technische Details" +/// note | Technische Details Es verwendete `uvloop` anstelle der standardmäßigen Python-`asyncio`-Schleife. Das hat es so schnell gemacht. @@ -271,7 +271,7 @@ Hat eindeutig Uvicorn und Starlette inspiriert, welche derzeit in offenen Benchm /// -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Einen Weg zu finden, eine hervorragende Performanz zu haben. @@ -287,7 +287,7 @@ Es ist so konzipiert, dass es über Funktionen verfügt, welche zwei Parameter e Daher müssen Datenvalidierung, Serialisierung und Dokumentation im Code und nicht automatisch erfolgen. Oder sie müssen als Framework oberhalb von Falcon implementiert werden, so wie Hug. Dieselbe Unterscheidung findet auch in anderen Frameworks statt, die vom Design von Falcon inspiriert sind und ein Requestobjekt und ein Responseobjekt als Parameter haben. -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Wege zu finden, eine großartige Performanz zu erzielen. @@ -313,7 +313,7 @@ Das Dependency Injection System erfordert eine Vorab-Registrierung der Abhängig Routen werden an einer einzigen Stelle deklariert, indem Funktionen verwendet werden, die an anderen Stellen deklariert wurden (anstatt Dekoratoren zu verwenden, welche direkt über der Funktion platziert werden können, welche den Endpunkt verarbeitet). Dies ähnelt eher der Vorgehensweise von Django als der Vorgehensweise von Flask (und Starlette). Es trennt im Code Dinge, die relativ eng miteinander gekoppelt sind. -/// check | "Inspirierte **FastAPI**" +/// check | Inspirierte **FastAPI** Zusätzliche Validierungen für Datentypen zu definieren, mithilfe des „Default“-Werts von Modellattributen. Dies verbessert die Editorunterstützung und war zuvor in Pydantic nicht verfügbar. @@ -341,7 +341,7 @@ Hug wurde von Timothy Crosley erstellt, dem gleichen Schöpfer von -/// tip | "Tipp" +/// tip | Tipp Aktivieren Sie jedes Mal, wenn Sie ein neues Package mit `pip` in dieser Umgebung installieren, die Umgebung erneut. @@ -138,7 +138,7 @@ Und wenn Sie diesen lokalen FastAPI-Quellcode aktualisieren und dann die Python- Auf diese Weise müssen Sie Ihre lokale Version nicht „installieren“, um jede Änderung testen zu können. -/// note | "Technische Details" +/// note | Technische Details Das geschieht nur, wenn Sie die Installation mit der enthaltenen `requirements.txt` durchführen, anstatt `pip install fastapi` direkt auszuführen. @@ -186,7 +186,7 @@ Das stellt die Dokumentation unter `http://127.0.0.1:8008` bereit. Auf diese Weise können Sie die Dokumentation/Quelldateien bearbeiten und die Änderungen live sehen. -/// tip | "Tipp" +/// tip | Tipp Alternativ können Sie die Schritte des Skripts auch manuell ausführen. @@ -229,7 +229,7 @@ Die Dokumentation verwendet Kommentare mit Änderungsvorschlägen zu vorhandenen Pull Requests hinzufügen. @@ -303,7 +303,7 @@ Angenommen, Sie möchten eine Seite für eine Sprache übersetzen, die bereits Im Spanischen lautet der Zwei-Buchstaben-Code `es`. Das Verzeichnis für spanische Übersetzungen befindet sich also unter `docs/es/`. -/// tip | "Tipp" +/// tip | Tipp Die Haupt („offizielle“) Sprache ist Englisch und befindet sich unter `docs/en/`. @@ -324,7 +324,7 @@ $ python ./scripts/docs.py live es -/// tip | "Tipp" +/// tip | Tipp Alternativ können Sie die Schritte des Skripts auch manuell ausführen. @@ -360,7 +360,7 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass die einzige Änderung in Pfad und Dateiname der Sprachcode ist, von `en` zu `es`. @@ -399,7 +399,7 @@ Obiges Kommando hat eine Datei `docs/ht/mkdocs.yml` mit einer Minimal-Konfigurat INHERIT: ../en/mkdocs.yml ``` -/// tip | "Tipp" +/// tip | Tipp Sie können diese Datei mit diesem Inhalt auch einfach manuell erstellen. diff --git a/docs/de/docs/deployment/concepts.md b/docs/de/docs/deployment/concepts.md index 3c1c0cfce..97ad854e2 100644 --- a/docs/de/docs/deployment/concepts.md +++ b/docs/de/docs/deployment/concepts.md @@ -151,7 +151,7 @@ Und dennoch möchten Sie wahrscheinlich nicht, dass die Anwendung tot bleibt, we Aber in den Fällen mit wirklich schwerwiegenden Fehlern, die den laufenden **Prozess** zum Absturz bringen, benötigen Sie eine externe Komponente, die den Prozess **neu startet**, zumindest ein paar Mal ... -/// tip | "Tipp" +/// tip | Tipp ... Obwohl es wahrscheinlich keinen Sinn macht, sie immer wieder neu zu starten, wenn die gesamte Anwendung einfach **sofort abstürzt**. Aber in diesen Fällen werden Sie es wahrscheinlich während der Entwicklung oder zumindest direkt nach dem Deployment bemerken. @@ -241,7 +241,7 @@ Hier sind einige mögliche Kombinationen und Strategien: * **Cloud-Dienste**, welche das für Sie erledigen * Der Cloud-Dienst wird wahrscheinlich **die Replikation für Sie übernehmen**. Er würde Sie möglicherweise **einen auszuführenden Prozess** oder ein **zu verwendendes Container-Image** definieren lassen, in jedem Fall wäre es höchstwahrscheinlich **ein einzelner Uvicorn-Prozess**, und der Cloud-Dienst wäre auch verantwortlich für die Replikation. -/// tip | "Tipp" +/// tip | Tipp Machen Sie sich keine Sorgen, wenn einige dieser Punkte zu **Containern**, Docker oder Kubernetes noch nicht viel Sinn ergeben. @@ -263,7 +263,7 @@ Und Sie müssen sicherstellen, dass es sich um einen einzelnen Prozess handelt, Natürlich gibt es Fälle, in denen es kein Problem darstellt, die Vorab-Schritte mehrmals auszuführen. In diesem Fall ist die Handhabung viel einfacher. -/// tip | "Tipp" +/// tip | Tipp Bedenken Sie außerdem, dass Sie, abhängig von Ihrer Einrichtung, in manchen Fällen **gar keine Vorab-Schritte** benötigen, bevor Sie die Anwendung starten. @@ -281,7 +281,7 @@ Hier sind einige mögliche Ideen: * Ein Bash-Skript, das die Vorab-Schritte ausführt und dann Ihre Anwendung startet * Sie benötigen immer noch eine Möglichkeit, *dieses* Bash-Skript zu starten/neu zu starten, Fehler zu erkennen, usw. -/// tip | "Tipp" +/// tip | Tipp Konkretere Beispiele hierfür mit Containern gebe ich Ihnen in einem späteren Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. diff --git a/docs/de/docs/deployment/docker.md b/docs/de/docs/deployment/docker.md index c11dc4127..a2734e068 100644 --- a/docs/de/docs/deployment/docker.md +++ b/docs/de/docs/deployment/docker.md @@ -4,7 +4,7 @@ Beim Deployment von FastAPI-Anwendungen besteht ein gängiger Ansatz darin, ein Die Verwendung von Linux-Containern bietet mehrere Vorteile, darunter **Sicherheit**, **Replizierbarkeit**, **Einfachheit** und andere. -/// tip | "Tipp" +/// tip | Tipp Sie haben es eilig und kennen sich bereits aus? Springen Sie zum [`Dockerfile` unten 👇](#ein-docker-image-fur-fastapi-erstellen). @@ -231,7 +231,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Da das Programm unter `/code` gestartet wird und sich darin das Verzeichnis `./app` mit Ihrem Code befindet, kann **Uvicorn** `app` sehen und aus `app.main` **importieren**. -/// tip | "Tipp" +/// tip | Tipp Lernen Sie, was jede Zeile bewirkt, indem Sie auf die Zahlenblasen im Code klicken. 👆 @@ -305,7 +305,7 @@ $ docker build -t myimage . -/// tip | "Tipp" +/// tip | Tipp Beachten Sie das `.` am Ende, es entspricht `./` und teilt Docker mit, welches Verzeichnis zum Erstellen des Containerimages verwendet werden soll. @@ -409,7 +409,7 @@ Wenn wir uns nur auf das **Containerimage** für eine FastAPI-Anwendung (und sp Es könnte sich um einen anderen Container handeln, zum Beispiel mit Traefik, welcher **HTTPS** und **automatischen** Erwerb von **Zertifikaten** handhabt. -/// tip | "Tipp" +/// tip | Tipp Traefik verfügt über Integrationen mit Docker, Kubernetes und anderen, sodass Sie damit ganz einfach HTTPS für Ihre Container einrichten und konfigurieren können. @@ -441,7 +441,7 @@ Bei der Verwendung von Containern ist normalerweise eine Komponente vorhanden, * Da diese Komponente die **Last** an Requests aufnehmen und diese (hoffentlich) **ausgewogen** auf die Worker verteilen würde, wird sie üblicherweise auch **Load Balancer** – Lastverteiler – genannt. -/// tip | "Tipp" +/// tip | Tipp Die gleiche **TLS-Terminierungsproxy**-Komponente, die für HTTPS verwendet wird, wäre wahrscheinlich auch ein **Load Balancer**. @@ -544,7 +544,7 @@ Dieses Image wäre vor allem in den oben beschriebenen Situationen nützlich: [C * tiangolo/uvicorn-gunicorn-fastapi. -/// warning | "Achtung" +/// warning | Achtung Es besteht eine hohe Wahrscheinlichkeit, dass Sie dieses oder ein ähnliches Basisimage **nicht** benötigen und es besser wäre, wenn Sie das Image von Grund auf neu erstellen würden, wie [oben beschrieben in: Ein Docker-Image für FastAPI erstellen](#ein-docker-image-fur-fastapi-erstellen). @@ -556,7 +556,7 @@ Es verfügt über **vernünftige Standardeinstellungen**, aber Sie können trotz Es unterstützt auch die Ausführung von **Vorab-Schritten vor dem Start** mit einem Skript. -/// tip | "Tipp" +/// tip | Tipp Um alle Konfigurationen und Optionen anzuzeigen, gehen Sie zur Docker-Image-Seite: tiangolo/uvicorn-gunicorn-fastapi. @@ -687,7 +687,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. Führe den Befehl `uvicorn` aus und weise ihn an, das aus `app.main` importierte `app`-Objekt zu verwenden. -/// tip | "Tipp" +/// tip | Tipp Klicken Sie auf die Zahlenblasen, um zu sehen, was jede Zeile bewirkt. diff --git a/docs/de/docs/deployment/https.md b/docs/de/docs/deployment/https.md index b1f0aca77..630582995 100644 --- a/docs/de/docs/deployment/https.md +++ b/docs/de/docs/deployment/https.md @@ -4,7 +4,7 @@ Es ist leicht anzunehmen, dass HTTPS etwas ist, was einfach nur „aktiviert“ Aber es ist viel komplexer als das. -/// tip | "Tipp" +/// tip | Tipp Wenn Sie es eilig haben oder es Ihnen egal ist, fahren Sie mit den nächsten Abschnitten fort, um Schritt-für-Schritt-Anleitungen für die Einrichtung der verschiedenen Technologien zu erhalten. @@ -71,7 +71,7 @@ In dem oder den DNS-Server(n) würden Sie einen Eintrag (einen „`A record`“) Sie würden dies wahrscheinlich nur einmal tun, beim ersten Mal, wenn Sie alles einrichten. -/// tip | "Tipp" +/// tip | Tipp Dieser Domainnamen-Aspekt liegt weit vor HTTPS, aber da alles von der Domain und der IP-Adresse abhängt, lohnt es sich, das hier zu erwähnen. @@ -121,7 +121,7 @@ Danach verfügen der Client und der Server über eine **verschlüsselte TCP-Verb Und genau das ist **HTTPS**, es ist einfach **HTTP** innerhalb einer **sicheren TLS-Verbindung**, statt einer puren (unverschlüsselten) TCP-Verbindung. -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass die Verschlüsselung der Kommunikation auf der **TCP-Ebene** und nicht auf der HTTP-Ebene erfolgt. diff --git a/docs/de/docs/deployment/manually.md b/docs/de/docs/deployment/manually.md index 2b4ed3fad..fdb33f7fe 100644 --- a/docs/de/docs/deployment/manually.md +++ b/docs/de/docs/deployment/manually.md @@ -36,7 +36,7 @@ $ pip install "uvicorn[standard]" -/// tip | "Tipp" +/// tip | Tipp Durch das Hinzufügen von `standard` installiert und verwendet Uvicorn einige empfohlene zusätzliche Abhängigkeiten. @@ -96,7 +96,7 @@ Running on 0.0.0.0:8080 over http (CTRL + C to quit) //// -/// warning | "Achtung" +/// warning | Achtung Denken Sie daran, die Option `--reload` zu entfernen, wenn Sie diese verwendet haben. diff --git a/docs/de/docs/deployment/versions.md b/docs/de/docs/deployment/versions.md index 2d10ac4b6..5b8c69754 100644 --- a/docs/de/docs/deployment/versions.md +++ b/docs/de/docs/deployment/versions.md @@ -42,7 +42,7 @@ Gemäß den Konventionen zur semantischen Versionierung könnte jede Version unt FastAPI folgt auch der Konvention, dass jede „PATCH“-Versionsänderung für Bugfixes und abwärtskompatible Änderungen gedacht ist. -/// tip | "Tipp" +/// tip | Tipp Der „PATCH“ ist die letzte Zahl, zum Beispiel ist in `0.2.3` die PATCH-Version `3`. @@ -56,7 +56,7 @@ fastapi>=0.45.0,<0.46.0 Nicht abwärtskompatible Änderungen und neue Funktionen werden in „MINOR“-Versionen hinzugefügt. -/// tip | "Tipp" +/// tip | Tipp „MINOR“ ist die Zahl in der Mitte, zum Beispiel ist in `0.2.3` die MINOR-Version `2`. diff --git a/docs/de/docs/help-fastapi.md b/docs/de/docs/help-fastapi.md index 2c84a5e5b..0b9c52316 100644 --- a/docs/de/docs/help-fastapi.md +++ b/docs/de/docs/help-fastapi.md @@ -228,7 +228,7 @@ Wenn Sie mir dabei helfen können, **helfen Sie mir, FastAPI am Laufen zu erhalt Treten Sie dem 👥 Discord-Chatserver 👥 bei und treffen Sie sich mit anderen Mitgliedern der FastAPI-Community. -/// tip | "Tipp" +/// tip | Tipp Wenn Sie Fragen haben, stellen Sie sie bei GitHub Diskussionen, es besteht eine viel bessere Chance, dass Sie hier Hilfe von den [FastAPI-Experten](fastapi-people.md#experten){.internal-link target=_blank} erhalten. diff --git a/docs/de/docs/how-to/custom-docs-ui-assets.md b/docs/de/docs/how-to/custom-docs-ui-assets.md index e5fd20a10..a292be69b 100644 --- a/docs/de/docs/how-to/custom-docs-ui-assets.md +++ b/docs/de/docs/how-to/custom-docs-ui-assets.md @@ -40,7 +40,7 @@ Und genau so für ReDoc ... {!../../docs_src/custom_docs_ui/tutorial001.py!} ``` -/// tip | "Tipp" +/// tip | Tipp Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. @@ -180,7 +180,7 @@ Und genau so für ReDoc ... {!../../docs_src/custom_docs_ui/tutorial002.py!} ``` -/// tip | "Tipp" +/// tip | Tipp Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. diff --git a/docs/de/docs/how-to/custom-request-and-route.md b/docs/de/docs/how-to/custom-request-and-route.md index f81fa1da3..ef71d96dc 100644 --- a/docs/de/docs/how-to/custom-request-and-route.md +++ b/docs/de/docs/how-to/custom-request-and-route.md @@ -6,7 +6,7 @@ Das kann insbesondere eine gute Alternative zur Logik in einer Middleware sein. Wenn Sie beispielsweise den Requestbody lesen oder manipulieren möchten, bevor er von Ihrer Anwendung verarbeitet wird. -/// danger | "Gefahr" +/// danger | Gefahr Dies ist eine „fortgeschrittene“ Funktion. @@ -30,7 +30,7 @@ Und eine `APIRoute`-Unterklasse zur Verwendung dieser benutzerdefinierten Reques ### Eine benutzerdefinierte `GzipRequest`-Klasse erstellen -/// tip | "Tipp" +/// tip | Tipp Dies ist nur ein einfaches Beispiel, um zu demonstrieren, wie es funktioniert. Wenn Sie Gzip-Unterstützung benötigen, können Sie die bereitgestellte [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} verwenden. @@ -60,7 +60,7 @@ Hier verwenden wir sie, um aus dem ursprünglichen Request einen `GzipRequest` z {!../../docs_src/custom_request_and_route/tutorial001.py!} ``` -/// note | "Technische Details" +/// note | Technische Details Ein `Request` hat ein `request.scope`-Attribut, welches einfach ein Python-`dict` ist, welches die mit dem Request verbundenen Metadaten enthält. @@ -84,7 +84,7 @@ Aufgrund unserer Änderungen in `GzipRequest.body` wird der Requestbody jedoch b ## Zugriff auf den Requestbody in einem Exceptionhandler -/// tip | "Tipp" +/// tip | Tipp Um dasselbe Problem zu lösen, ist es wahrscheinlich viel einfacher, den `body` in einem benutzerdefinierten Handler für `RequestValidationError` zu verwenden ([Fehlerbehandlung](../tutorial/handling-errors.md#den-requestvalidationerror-body-verwenden){.internal-link target=_blank}). diff --git a/docs/de/docs/how-to/graphql.md b/docs/de/docs/how-to/graphql.md index cde56ffde..4366ea52d 100644 --- a/docs/de/docs/how-to/graphql.md +++ b/docs/de/docs/how-to/graphql.md @@ -4,7 +4,7 @@ Da **FastAPI** auf dem **ASGI**-Standard basiert, ist es sehr einfach, jede **Gr Sie können normale FastAPI-*Pfadoperationen* mit GraphQL in derselben Anwendung kombinieren. -/// tip | "Tipp" +/// tip | Tipp **GraphQL** löst einige sehr spezifische Anwendungsfälle. @@ -49,7 +49,7 @@ Frühere Versionen von Starlette enthielten eine `GraphQLApp`-Klasse zur Integra Das wurde von Starlette deprecated, aber wenn Sie Code haben, der das verwendet, können Sie einfach zu starlette-graphene3 **migrieren**, welches denselben Anwendungsfall abdeckt und über eine **fast identische Schnittstelle** verfügt. -/// tip | "Tipp" +/// tip | Tipp Wenn Sie GraphQL benötigen, würde ich Ihnen trotzdem empfehlen, sich Strawberry anzuschauen, da es auf Typannotationen basiert, statt auf benutzerdefinierten Klassen und Typen. diff --git a/docs/de/docs/how-to/index.md b/docs/de/docs/how-to/index.md index 75779a01c..84a178fc8 100644 --- a/docs/de/docs/how-to/index.md +++ b/docs/de/docs/how-to/index.md @@ -6,7 +6,7 @@ Die meisten dieser Ideen sind mehr oder weniger **unabhängig**, und in den meis Wenn etwas für Ihr Projekt interessant und nützlich erscheint, lesen Sie es, andernfalls überspringen Sie es einfach. -/// tip | "Tipp" +/// tip | Tipp Wenn Sie strukturiert **FastAPI lernen** möchten (empfohlen), lesen Sie stattdessen Kapitel für Kapitel das [Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank}. diff --git a/docs/de/docs/python-types.md b/docs/de/docs/python-types.md index a9ab4beab..81d43bc5b 100644 --- a/docs/de/docs/python-types.md +++ b/docs/de/docs/python-types.md @@ -12,7 +12,7 @@ Dies ist lediglich eine **schnelle Anleitung / Auffrischung** über Pythons Typh Aber selbst wenn Sie **FastAPI** nie verwenden, wird es für Sie nützlich sein, ein wenig darüber zu lernen. -/// note | "Hinweis" +/// note | Hinweis Wenn Sie ein Python-Experte sind und bereits alles über Typhinweise wissen, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort. @@ -195,7 +195,7 @@ Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckige //// -/// tip | "Tipp" +/// tip | Tipp Die inneren Typen in den eckigen Klammern werden als „Typ-Parameter“ bezeichnet. @@ -205,7 +205,7 @@ In diesem Fall ist `str` der Typ-Parameter, der an `List` übergeben wird (oder Das bedeutet: Die Variable `items` ist eine Liste – `list` – und jedes der Elemente in dieser Liste ist ein String – `str`. -/// tip | "Tipp" +/// tip | Tipp Wenn Sie Python 3.9 oder höher verwenden, müssen Sie `List` nicht von `typing` importieren, Sie können stattdessen den regulären `list`-Typ verwenden. @@ -495,7 +495,7 @@ Um mehr über Required fields mehr erfahren. @@ -537,7 +537,7 @@ Im Moment müssen Sie nur wissen, dass `Annotated` existiert, und dass es Standa Später werden Sie sehen, wie **mächtig** es sein kann. -/// tip | "Tipp" +/// tip | Tipp Der Umstand, dass es **Standard-Python** ist, bedeutet, dass Sie immer noch die **bestmögliche Entwickler-Erfahrung** in ihrem Editor haben, sowie mit den Tools, die Sie nutzen, um ihren Code zu analysieren, zu refaktorisieren, usw. ✨ diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md index cd857f5e7..d40b6d4fb 100644 --- a/docs/de/docs/tutorial/background-tasks.md +++ b/docs/de/docs/tutorial/background-tasks.md @@ -83,7 +83,7 @@ Die Verwendung von `BackgroundTasks` funktioniert auch mit dem -/// tip | "Tipp" +/// tip | Tipp Wenn Sie PyCharm als Ihren Editor verwenden, probieren Sie das Pydantic PyCharm Plugin aus. @@ -233,7 +233,7 @@ Die Funktionsparameter werden wie folgt erkannt: * Wenn der Parameter ein **einfacher Typ** ist (wie `int`, `float`, `str`, `bool`, usw.), wird er als **Query**-Parameter interpretiert. * Wenn der Parameter vom Typ eines **Pydantic-Modells** ist, wird er als Request**body** interpretiert. -/// note | "Hinweis" +/// note | Hinweis FastAPI weiß, dass der Wert von `q` nicht erforderlich ist, wegen des definierten Defaultwertes `= None` diff --git a/docs/de/docs/tutorial/cookie-params.md b/docs/de/docs/tutorial/cookie-params.md index 4714a59ae..ecb14ad03 100644 --- a/docs/de/docs/tutorial/cookie-params.md +++ b/docs/de/docs/tutorial/cookie-params.md @@ -32,7 +32,7 @@ Importieren Sie zuerst `Cookie`: //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -46,7 +46,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -90,7 +90,7 @@ Der erste Wert ist der Typ. Sie können `Cookie` die gehabten Extra Validierungs //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -104,7 +104,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -116,7 +116,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// -/// note | "Technische Details" +/// note | Technische Details `Cookie` ist eine Schwesterklasse von `Path` und `Query`. Sie erbt von derselben gemeinsamen `Param`-Elternklasse. diff --git a/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md index a660ab337..a3e3d2c60 100644 --- a/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md @@ -32,7 +32,7 @@ Im vorherigen Beispiel haben wir ein `dict` von unserer Abhängigkeit („Depend //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -46,7 +46,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -145,7 +145,7 @@ Dann können wir das „Dependable“ `common_parameters` der Abhängigkeit von //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -159,7 +159,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -199,7 +199,7 @@ Achten Sie auf die Methode `__init__`, die zum Erstellen der Instanz der Klasse //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -213,7 +213,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -253,7 +253,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -267,7 +267,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -319,7 +319,7 @@ Jetzt können Sie Ihre Abhängigkeit mithilfe dieser Klasse deklarieren. //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -333,7 +333,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -361,7 +361,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -397,7 +397,7 @@ commons: Annotated[CommonQueryParams, ... //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -423,7 +423,7 @@ commons: Annotated[Any, Depends(CommonQueryParams)] //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -463,7 +463,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -477,7 +477,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -507,7 +507,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -535,7 +535,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -559,7 +559,7 @@ commons: Annotated[CommonQueryParams, Depends()] //// tab | Python 3.8 nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -601,7 +601,7 @@ Dasselbe Beispiel würde dann so aussehen: //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -615,7 +615,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -629,7 +629,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. ... und **FastAPI** wird wissen, was zu tun ist. -/// tip | "Tipp" +/// tip | Tipp Wenn Sie das eher verwirrt, als Ihnen zu helfen, ignorieren Sie es, Sie *brauchen* es nicht. diff --git a/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 3bb261e44..6aa5ef199 100644 --- a/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -32,7 +32,7 @@ Es sollte eine `list`e von `Depends()` sein: //// tab | Python 3.8 nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -46,7 +46,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. Diese Abhängigkeiten werden auf die gleiche Weise wie normale Abhängigkeiten ausgeführt/aufgelöst. Aber ihr Wert (falls sie einen zurückgeben) wird nicht an Ihre *Pfadoperation-Funktion* übergeben. -/// tip | "Tipp" +/// tip | Tipp Einige Editoren prüfen, ob Funktionsparameter nicht verwendet werden, und zeigen das als Fehler an. @@ -90,7 +90,7 @@ Sie können Anforderungen für einen Request (wie Header) oder andere Unterabhä //// tab | Python 3.8 nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -124,7 +124,7 @@ Die Abhängigkeiten können Exceptions `raise`n, genau wie normale Abhängigkeit //// tab | Python 3.8 nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -160,7 +160,7 @@ Sie können also eine normale Abhängigkeit (die einen Wert zurückgibt), die Si //// tab | Python 3.8 nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. diff --git a/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md index 48b057e28..ce6bbad69 100644 --- a/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,13 +4,13 @@ FastAPI unterstützt Abhängigkeiten, die nach Abschluss einige Kontextmanager. @@ -163,7 +163,7 @@ Sie haben gesehen, dass Ihre Abhängigkeiten `yield` verwenden können und `try` Auf die gleiche Weise könnten Sie im Exit-Code nach dem `yield` eine `HTTPException` oder ähnliches auslösen. -/// tip | "Tipp" +/// tip | Tipp Dies ist eine etwas fortgeschrittene Technik, die Sie in den meisten Fällen nicht wirklich benötigen, da Sie Exceptions (einschließlich `HTTPException`) innerhalb des restlichen Anwendungscodes auslösen können, beispielsweise in der *Pfadoperation-Funktion*. @@ -189,7 +189,7 @@ Aber es ist für Sie da, wenn Sie es brauchen. 🤓 //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -250,7 +250,7 @@ Nachdem eine dieser Responses gesendet wurde, kann keine weitere Response gesend /// -/// tip | "Tipp" +/// tip | Tipp Obiges Diagramm verwendet `HTTPException`, aber Sie können auch jede andere Exception auslösen, die Sie in einer Abhängigkeit mit `yield` abfangen, oder mit einem [benutzerdefinierten Exceptionhandler](../handling-errors.md#benutzerdefinierte-exceptionhandler-definieren){.internal-link target=_blank} erstellt haben. @@ -260,7 +260,7 @@ Wenn Sie eine Exception auslösen, wird diese mit yield an die Abhängigkeiten ## Abhängigkeiten mit `yield`, `HTTPException` und Hintergrundtasks -/// warning | "Achtung" +/// warning | Achtung Sie benötigen diese technischen Details höchstwahrscheinlich nicht, Sie können diesen Abschnitt überspringen und weiter unten fortfahren. @@ -274,7 +274,7 @@ Dies wurde hauptsächlich so konzipiert, damit die gleichen Objekte, die durch A Da dies jedoch bedeuten würde, darauf zu warten, dass die Response durch das Netzwerk reist, während eine Ressource unnötigerweise in einer Abhängigkeit mit yield gehalten wird (z. B. eine Datenbankverbindung), wurde dies in FastAPI 0.106.0 geändert. -/// tip | "Tipp" +/// tip | Tipp Darüber hinaus handelt es sich bei einem Hintergrundtask normalerweise um einen unabhängigen Satz von Logik, der separat behandelt werden sollte, mit eigenen Ressourcen (z. B. einer eigenen Datenbankverbindung). @@ -308,7 +308,7 @@ Wenn Sie eine Abhängigkeit mit `yield` erstellen, erstellt **FastAPI** dafür i ### Kontextmanager in Abhängigkeiten mit `yield` verwenden -/// warning | "Achtung" +/// warning | Achtung Dies ist mehr oder weniger eine „fortgeschrittene“ Idee. @@ -324,7 +324,7 @@ Sie können solche auch innerhalb von **FastAPI**-Abhängigkeiten mit `yield` ve {!../../docs_src/dependencies/tutorial010.py!} ``` -/// tip | "Tipp" +/// tip | Tipp Andere Möglichkeiten, einen Kontextmanager zu erstellen, sind: diff --git a/docs/de/docs/tutorial/dependencies/global-dependencies.md b/docs/de/docs/tutorial/dependencies/global-dependencies.md index 6b9e9e395..4df9f64e9 100644 --- a/docs/de/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/de/docs/tutorial/dependencies/global-dependencies.md @@ -24,7 +24,7 @@ In diesem Fall werden sie auf alle *Pfadoperationen* in der Anwendung angewendet //// tab | Python 3.8 nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. diff --git a/docs/de/docs/tutorial/dependencies/index.md b/docs/de/docs/tutorial/dependencies/index.md index 494708d19..2a4a5177a 100644 --- a/docs/de/docs/tutorial/dependencies/index.md +++ b/docs/de/docs/tutorial/dependencies/index.md @@ -56,7 +56,7 @@ Es handelt sich einfach um eine Funktion, die die gleichen Parameter entgegennim //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -70,7 +70,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -138,7 +138,7 @@ Bitte [aktualisieren Sie FastAPI](../../deployment/versions.md#upgrade-der-fasta //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -152,7 +152,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -194,7 +194,7 @@ So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ih //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -208,7 +208,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -230,7 +230,7 @@ Sie **rufen diese nicht direkt auf** (fügen Sie am Ende keine Klammern hinzu), Und diese Funktion akzeptiert Parameter auf die gleiche Weise wie *Pfadoperation-Funktionen*. -/// tip | "Tipp" +/// tip | Tipp Im nächsten Kapitel erfahren Sie, welche anderen „Dinge“, außer Funktionen, Sie als Abhängigkeiten verwenden können. @@ -299,7 +299,7 @@ Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in eine //// -/// tip | "Tipp" +/// tip | Tipp Das ist schlicht Standard-Python, es wird als „Typalias“ bezeichnet und ist eigentlich nicht **FastAPI**-spezifisch. @@ -321,7 +321,7 @@ Und Sie können Abhängigkeiten mit `async def` innerhalb normaler `def`-*Pfadop Es spielt keine Rolle. **FastAPI** weiß, was zu tun ist. -/// note | "Hinweis" +/// note | Hinweis Wenn Ihnen das nichts sagt, lesen Sie den [Async: *„In Eile?“*](../../async.md#in-eile){.internal-link target=_blank}-Abschnitt über `async` und `await` in der Dokumentation. diff --git a/docs/de/docs/tutorial/dependencies/sub-dependencies.md b/docs/de/docs/tutorial/dependencies/sub-dependencies.md index a20aed63b..6da7c64de 100644 --- a/docs/de/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/de/docs/tutorial/dependencies/sub-dependencies.md @@ -36,7 +36,7 @@ Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen: //// tab | Python 3.10 nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -50,7 +50,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8 nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -96,7 +96,7 @@ Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erst //// tab | Python 3.10 nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -110,7 +110,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8 nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -159,7 +159,7 @@ Diese Abhängigkeit verwenden wir nun wie folgt: //// tab | Python 3.10 nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -173,7 +173,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8 nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -223,7 +223,7 @@ async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_ca //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -244,7 +244,7 @@ Einfach Funktionen, die genauso aussehen wie *Pfadoperation-Funktionen*. Dennoch ist es sehr mächtig und ermöglicht Ihnen die Deklaration beliebig tief verschachtelter Abhängigkeits-„Graphen“ (Bäume). -/// tip | "Tipp" +/// tip | Tipp All dies scheint angesichts dieser einfachen Beispiele möglicherweise nicht so nützlich zu sein. diff --git a/docs/de/docs/tutorial/encoder.md b/docs/de/docs/tutorial/encoder.md index 0ab72b8dd..428eee287 100644 --- a/docs/de/docs/tutorial/encoder.md +++ b/docs/de/docs/tutorial/encoder.md @@ -42,7 +42,7 @@ Das Resultat dieses Aufrufs ist etwas, das mit Pythons Standard-gehashtes Passwort haben. -/// danger | "Gefahr" +/// danger | Gefahr Speichern Sie niemals das Klartext-Passwort eines Benutzers. Speichern Sie immer den „sicheren Hash“, den Sie verifizieren können. @@ -154,7 +154,7 @@ UserInDB( ) ``` -/// warning | "Achtung" +/// warning | Achtung Die Hilfsfunktionen `fake_password_hasher` und `fake_save_user` demonstrieren nur den möglichen Fluss der Daten und bieten natürlich keine echte Sicherheit. @@ -200,7 +200,7 @@ Das wird in OpenAPI mit `anyOf` angezeigt. Um das zu tun, verwenden Sie Pythons Standard-Typhinweis `typing.Union`: -/// note | "Hinweis" +/// note | Hinweis Listen Sie, wenn Sie eine `Union` definieren, denjenigen Typ zuerst, der am spezifischsten ist, gefolgt von den weniger spezifischen Typen. Im Beispiel oben, in `Union[PlaneItem, CarItem]` also den spezifischeren `PlaneItem` vor dem weniger spezifischen `CarItem`. diff --git a/docs/de/docs/tutorial/first-steps.md b/docs/de/docs/tutorial/first-steps.md index fe3886b70..debefb156 100644 --- a/docs/de/docs/tutorial/first-steps.md +++ b/docs/de/docs/tutorial/first-steps.md @@ -24,7 +24,7 @@ $ uvicorn main:app --reload -/// note | "Hinweis" +/// note | Hinweis Der Befehl `uvicorn main:app` bezieht sich auf: @@ -139,7 +139,7 @@ Ebenfalls können Sie es verwenden, um automatisch Code für Clients zu generier `FastAPI` ist eine Python-Klasse, die die gesamte Funktionalität für Ihre API bereitstellt. -/// note | "Technische Details" +/// note | Technische Details `FastAPI` ist eine Klasse, die direkt von `Starlette` erbt. @@ -259,7 +259,7 @@ Das `@app.get("/")` sagt **FastAPI**, dass die Funktion direkt darunter für die * den Pfad `/` * unter der Verwendung der get-Operation gehen -/// info | "`@decorator` Information" +/// info | `@decorator` Information Diese `@something`-Syntax wird in Python „Dekorator“ genannt. @@ -286,7 +286,7 @@ Oder die exotischeren: * `@app.patch()` * `@app.trace()` -/// tip | "Tipp" +/// tip | Tipp Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten. @@ -324,7 +324,7 @@ Sie könnten sie auch als normale Funktion anstelle von `async def` definieren: {!../../docs_src/first_steps/tutorial003.py!} ``` -/// note | "Hinweis" +/// note | Hinweis Wenn Sie den Unterschied nicht kennen, lesen Sie [Async: *„In Eile?“*](../async.md#in-eile){.internal-link target=_blank}. diff --git a/docs/de/docs/tutorial/handling-errors.md b/docs/de/docs/tutorial/handling-errors.md index 70dc0c523..85de76ef1 100644 --- a/docs/de/docs/tutorial/handling-errors.md +++ b/docs/de/docs/tutorial/handling-errors.md @@ -63,7 +63,7 @@ Aber wenn der Client `http://example.com/items/bar` anfragt (ein nicht-existiere } ``` -/// tip | "Tipp" +/// tip | Tipp Wenn Sie eine `HTTPException` auslösen, können Sie dem Parameter `detail` jeden Wert übergeben, der nach JSON konvertiert werden kann, nicht nur `str`. @@ -109,7 +109,7 @@ Sie erhalten also einen sauberen Error mit einem Statuscode `418` und dem JSON-I {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.requests import Request` und `from starlette.responses import JSONResponse` verwenden. @@ -166,7 +166,7 @@ path -> item_id #### `RequestValidationError` vs. `ValidationError` -/// warning | "Achtung" +/// warning | Achtung Das folgende sind technische Details, die Sie überspringen können, wenn sie für Sie nicht wichtig sind. @@ -192,7 +192,7 @@ Zum Beispiel könnten Sie eine Klartext-Response statt JSON für diese Fehler zu {!../../docs_src/handling_errors/tutorial004.py!} ``` -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.responses import PlainTextResponse` verwenden. diff --git a/docs/de/docs/tutorial/header-params.md b/docs/de/docs/tutorial/header-params.md index c4901c2ee..40a773f50 100644 --- a/docs/de/docs/tutorial/header-params.md +++ b/docs/de/docs/tutorial/header-params.md @@ -32,7 +32,7 @@ Importieren Sie zuerst `Header`: //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -46,7 +46,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -90,7 +90,7 @@ Der erste Wert ist der Typ. Sie können `Header` die gehabten Extra Validierungs //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -104,7 +104,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -116,7 +116,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// -/// note | "Technische Details" +/// note | Technische Details `Header` ist eine Schwesterklasse von `Path`, `Query` und `Cookie`. Sie erbt von derselben gemeinsamen `Param`-Elternklasse. @@ -172,7 +172,7 @@ Wenn Sie aus irgendeinem Grund das automatische Konvertieren von Unterstrichen z //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -186,7 +186,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -198,7 +198,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// -/// warning | "Achtung" +/// warning | Achtung Bevor Sie `convert_underscores` auf `False` setzen, bedenken Sie, dass manche HTTP-Proxys und Server die Verwendung von Headern mit Unterstrichen nicht erlauben. @@ -240,7 +240,7 @@ Um zum Beispiel einen Header `X-Token` zu deklarieren, der mehrmals vorkommen ka //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -254,7 +254,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.9+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -268,7 +268,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. diff --git a/docs/de/docs/tutorial/index.md b/docs/de/docs/tutorial/index.md index c15d0b0bd..3cbfe37f4 100644 --- a/docs/de/docs/tutorial/index.md +++ b/docs/de/docs/tutorial/index.md @@ -52,7 +52,7 @@ $ pip install "fastapi[all]" ... das beinhaltet auch `uvicorn`, welchen Sie als Server verwenden können, der ihren Code ausführt. -/// note | "Hinweis" +/// note | Hinweis Sie können die einzelnen Teile auch separat installieren. diff --git a/docs/de/docs/tutorial/metadata.md b/docs/de/docs/tutorial/metadata.md index 98724e1e8..5a0b723c5 100644 --- a/docs/de/docs/tutorial/metadata.md +++ b/docs/de/docs/tutorial/metadata.md @@ -22,7 +22,7 @@ Sie können diese wie folgt setzen: {!../../docs_src/metadata/tutorial001.py!} ``` -/// tip | "Tipp" +/// tip | Tipp Sie können Markdown in das Feld `description` schreiben und es wird in der Ausgabe gerendert. @@ -68,7 +68,7 @@ Erstellen Sie Metadaten für Ihre Tags und übergeben Sie sie an den Parameter ` Beachten Sie, dass Sie Markdown in den Beschreibungen verwenden können. Beispielsweise wird „login“ in Fettschrift (**login**) und „fancy“ in Kursivschrift (_fancy_) angezeigt. -/// tip | "Tipp" +/// tip | Tipp Sie müssen nicht für alle von Ihnen verwendeten Tags Metadaten hinzufügen. diff --git a/docs/de/docs/tutorial/middleware.md b/docs/de/docs/tutorial/middleware.md index 6bdececbc..d3699be1b 100644 --- a/docs/de/docs/tutorial/middleware.md +++ b/docs/de/docs/tutorial/middleware.md @@ -11,7 +11,7 @@ Eine „Middleware“ ist eine Funktion, die mit jedem **Request** arbeitet, bev * Sie kann etwas mit dieser **Response** tun oder beliebigen Code ausführen. * Dann gibt sie die **Response** zurück. -/// note | "Technische Details" +/// note | Technische Details Wenn Sie Abhängigkeiten mit `yield` haben, wird der Exit-Code *nach* der Middleware ausgeführt. @@ -33,7 +33,7 @@ Die Middleware-Funktion erhält: {* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass benutzerdefinierte proprietäre Header hinzugefügt werden können. Verwenden Sie dafür das Präfix 'X-'. @@ -41,7 +41,7 @@ Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser /// -/// note | "Technische Details" +/// note | Technische Details Sie könnten auch `from starlette.requests import Request` verwenden. diff --git a/docs/de/docs/tutorial/path-operation-configuration.md b/docs/de/docs/tutorial/path-operation-configuration.md index 411916e9c..55d0f2a91 100644 --- a/docs/de/docs/tutorial/path-operation-configuration.md +++ b/docs/de/docs/tutorial/path-operation-configuration.md @@ -2,7 +2,7 @@ Es gibt mehrere Konfigurations-Parameter, die Sie Ihrem *Pfadoperation-Dekorator* übergeben können. -/// warning | "Achtung" +/// warning | Achtung Beachten Sie, dass diese Parameter direkt dem *Pfadoperation-Dekorator* übergeben werden, nicht der *Pfadoperation-Funktion*. @@ -42,7 +42,7 @@ Aber falls Sie sich nicht mehr erinnern, wofür jede Nummer steht, können Sie d Dieser Statuscode wird in der Response verwendet und zum OpenAPI-Schema hinzugefügt. -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette import status` verwenden. diff --git a/docs/de/docs/tutorial/path-params-numeric-validations.md b/docs/de/docs/tutorial/path-params-numeric-validations.md index fc2d5dff1..b74fc8a04 100644 --- a/docs/de/docs/tutorial/path-params-numeric-validations.md +++ b/docs/de/docs/tutorial/path-params-numeric-validations.md @@ -32,7 +32,7 @@ Importieren Sie zuerst `Path` von `fastapi`, und importieren Sie `Annotated`. //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -46,7 +46,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -100,7 +100,7 @@ Um zum Beispiel einen `title`-Metadaten-Wert für den Pfad-Parameter `item_id` z //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -114,7 +114,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -126,7 +126,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// -/// note | "Hinweis" +/// note | Hinweis Ein Pfad-Parameter ist immer erforderlich, weil er Teil des Pfads sein muss. @@ -138,7 +138,7 @@ Doch selbst wenn Sie ihn mit `None` deklarieren, oder einen Defaultwert setzen, ## Sortieren Sie die Parameter, wie Sie möchten -/// tip | "Tipp" +/// tip | Tipp Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig. @@ -160,7 +160,7 @@ Sie können Ihre Funktion also so deklarieren: //// tab | Python 3.8 nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -192,7 +192,7 @@ Aber bedenken Sie, dass Sie dieses Problem nicht haben, wenn Sie `Annotated` ver ## Sortieren Sie die Parameter wie Sie möchten: Tricks -/// tip | "Tipp" +/// tip | Tipp Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig. @@ -260,7 +260,7 @@ Hier, mit `ge=1`, wird festgelegt, dass `item_id` eine Ganzzahl benötigt, die g //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -297,7 +297,7 @@ Das Gleiche trifft zu auf: //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -337,7 +337,7 @@ Das gleiche gilt für ltModellen für maschinelles Lernen. @@ -199,7 +199,7 @@ Den tatsächlichen Wert (in diesem Fall ein `str`) erhalten Sie via `model_name. {!../../docs_src/path_params/tutorial005.py!} ``` -/// tip | "Tipp" +/// tip | Tipp Sie können den Wert `"lenet"` außerdem mittels `ModelName.lenet.value` abrufen. @@ -256,7 +256,7 @@ Sie verwenden das also wie folgt: {!../../docs_src/path_params/tutorial004.py!} ``` -/// tip | "Tipp" +/// tip | Tipp Der Parameter könnte einen führenden Schrägstrich (`/`) haben, wie etwa in `/home/johndoe/myfile.txt`. diff --git a/docs/de/docs/tutorial/query-params-str-validations.md b/docs/de/docs/tutorial/query-params-str-validations.md index a9f1e0f39..d71a23dc2 100644 --- a/docs/de/docs/tutorial/query-params-str-validations.md +++ b/docs/de/docs/tutorial/query-params-str-validations.md @@ -22,7 +22,7 @@ Nehmen wir als Beispiel die folgende Anwendung: Der Query-Parameter `q` hat den Typ `Union[str, None]` (oder `str | None` in Python 3.10), was bedeutet, er ist entweder ein `str` oder `None`. Der Defaultwert ist `None`, also weiß FastAPI, der Parameter ist nicht erforderlich. -/// note | "Hinweis" +/// note | Hinweis FastAPI weiß nur dank des definierten Defaultwertes `=None`, dass der Wert von `q` nicht erforderlich ist @@ -153,7 +153,7 @@ FastAPI wird nun: Frühere Versionen von FastAPI (vor 0.95.0) benötigten `Query` als Defaultwert des Parameters, statt es innerhalb von `Annotated` unterzubringen. Die Chance ist groß, dass Sie Quellcode sehen, der das immer noch so macht, darum erkläre ich es Ihnen. -/// tip | "Tipp" +/// tip | Tipp Verwenden Sie für neuen Code, und wann immer möglich, `Annotated`, wie oben erklärt. Es gibt mehrere Vorteile (unten erläutert) und keine Nachteile. 🍰 @@ -301,7 +301,7 @@ Sie können auch einen Parameter `min_length` hinzufügen: //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -315,7 +315,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -357,7 +357,7 @@ Sie können einen ../../docs_src/query_params_str_validations/tutorial006.py!} ``` -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass, obwohl in diesem Fall `Query()` der Funktionsparameter-Defaultwert ist, wir nicht `default=None` zu `Query()` hinzufügen. @@ -545,7 +545,7 @@ Es gibt eine Alternative, die explizit deklariert, dass ein Wert erforderlich is //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -599,7 +599,7 @@ Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwe //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -613,7 +613,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -625,13 +625,13 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// -/// tip | "Tipp" +/// tip | Tipp Pydantic, welches die gesamte Datenvalidierung und Serialisierung in FastAPI antreibt, hat ein spezielles Verhalten, wenn Sie `Optional` oder `Union[Something, None]` ohne Defaultwert verwenden, Sie können mehr darüber in der Pydantic-Dokumentation unter Required fields erfahren. /// -/// tip | "Tipp" +/// tip | Tipp Denken Sie daran, dass Sie in den meisten Fällen, wenn etwas erforderlich ist, einfach den Defaultwert weglassen können. Sie müssen also normalerweise `...` nicht verwenden. @@ -669,7 +669,7 @@ Um zum Beispiel einen Query-Parameter `q` zu deklarieren, der mehrere Male in de //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -683,7 +683,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.9+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -697,7 +697,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -728,7 +728,7 @@ Die Response für diese URL wäre also: } ``` -/// tip | "Tipp" +/// tip | Tipp Um einen Query-Parameter vom Typ `list` zu deklarieren, wie im Beispiel oben, müssen Sie explizit `Query` verwenden, sonst würde der Parameter als Requestbody interpretiert werden. @@ -760,7 +760,7 @@ Und Sie können auch eine Default-`list`e von Werten definieren, wenn keine übe //// tab | Python 3.9+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -774,7 +774,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -825,7 +825,7 @@ Sie können auch `list` direkt verwenden, anstelle von `List[str]` (oder `list[s //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -837,7 +837,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// -/// note | "Hinweis" +/// note | Hinweis Beachten Sie, dass FastAPI in diesem Fall den Inhalt der Liste nicht überprüft. @@ -851,7 +851,7 @@ Sie können mehr Informationen zum Parameter hinzufügen. Diese Informationen werden zur generierten OpenAPI hinzugefügt, und von den Dokumentations-Oberflächen und von externen Tools verwendet. -/// note | "Hinweis" +/// note | Hinweis Beachten Sie, dass verschiedene Tools OpenAPI möglicherweise unterschiedlich gut unterstützen. @@ -887,7 +887,7 @@ Sie können einen Titel hinzufügen – `title`: //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -901,7 +901,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -941,7 +941,7 @@ Und eine Beschreibung – `description`: //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -955,7 +955,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -1011,7 +1011,7 @@ Dann können Sie einen `alias` deklarieren, und dieser Alias wird verwendet, um //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -1025,7 +1025,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -1071,7 +1071,7 @@ In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu. //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -1085,7 +1085,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -1131,7 +1131,7 @@ Um einen Query-Parameter vom generierten OpenAPI-Schema auszuschließen (und dah //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -1145,7 +1145,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. diff --git a/docs/de/docs/tutorial/query-params.md b/docs/de/docs/tutorial/query-params.md index bb1dbdf9c..e67fef79d 100644 --- a/docs/de/docs/tutorial/query-params.md +++ b/docs/de/docs/tutorial/query-params.md @@ -241,7 +241,7 @@ In diesem Fall gibt es drei Query-Parameter: * `skip`, ein `int` mit einem Defaultwert `0`. * `limit`, ein optionales `int`. -/// tip | "Tipp" +/// tip | Tipp Sie können auch `Enum`s verwenden, auf die gleiche Weise wie mit [Pfad-Parametern](path-params.md#vordefinierte-parameterwerte){.internal-link target=_blank}. diff --git a/docs/de/docs/tutorial/request-files.md b/docs/de/docs/tutorial/request-files.md index c0d0ef3f2..cbfb4271f 100644 --- a/docs/de/docs/tutorial/request-files.md +++ b/docs/de/docs/tutorial/request-files.md @@ -34,7 +34,7 @@ Importieren Sie `File` und `UploadFile` von `fastapi`: //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -68,7 +68,7 @@ Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen w //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -88,7 +88,7 @@ Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `File` und andere von ` /// -/// tip | "Tipp" +/// tip | Tipp Um Dateibodys zu deklarieren, müssen Sie `File` verwenden, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden. @@ -124,7 +124,7 @@ Definieren Sie einen Datei-Parameter mit dem Typ `UploadFile`: //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -177,13 +177,13 @@ Wenn Sie sich innerhalb einer normalen `def`-*Pfadoperation-Funktion* befinden, contents = myfile.file.read() ``` -/// note | "Technische Details zu `async`" +/// note | Technische Details zu `async` Wenn Sie die `async`-Methoden verwenden, führt **FastAPI** die Datei-Methoden in einem Threadpool aus und erwartet sie. /// -/// note | "Technische Details zu Starlette" +/// note | Technische Details zu Starlette **FastAPI**s `UploadFile` erbt direkt von **Starlette**s `UploadFile`, fügt aber ein paar notwendige Teile hinzu, um es kompatibel mit **Pydantic** und anderen Teilen von FastAPI zu machen. @@ -195,7 +195,7 @@ HTML-Formulare (`
`) senden die Daten in einer „speziellen“ Kodi **FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten. -/// note | "Technische Details" +/// note | Technische Details Daten aus Formularen werden, wenn es keine Dateien sind, normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert. @@ -205,7 +205,7 @@ Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen /// -/// warning | "Achtung" +/// warning | Achtung Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert. @@ -243,7 +243,7 @@ Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwe //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -257,7 +257,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -291,7 +291,7 @@ Sie können auch `File()` zusammen mit `UploadFile` verwenden, um zum Beispiel z //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -329,7 +329,7 @@ Um das zu machen, deklarieren Sie eine Liste von `bytes` oder `UploadFile`s: //// tab | Python 3.9+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -343,7 +343,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -357,7 +357,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. Sie erhalten, wie deklariert, eine `list`e von `bytes` oder `UploadFile`s. -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette.responses import HTMLResponse` verwenden. @@ -387,7 +387,7 @@ Und so wie zuvor können Sie `File()` verwenden, um zusätzliche Parameter zu se //// tab | Python 3.9+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -401,7 +401,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. diff --git a/docs/de/docs/tutorial/request-forms-and-files.md b/docs/de/docs/tutorial/request-forms-and-files.md index 2b89edbb4..bdd1e0fac 100644 --- a/docs/de/docs/tutorial/request-forms-and-files.md +++ b/docs/de/docs/tutorial/request-forms-and-files.md @@ -30,7 +30,7 @@ Z. B. `pip install python-multipart`. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -64,7 +64,7 @@ Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` und `Q //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -80,7 +80,7 @@ Die Datei- und Formularfelder werden als Formulardaten hochgeladen, und Sie erha Und Sie können einige der Dateien als `bytes` und einige als `UploadFile` deklarieren. -/// warning | "Achtung" +/// warning | Achtung Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert. diff --git a/docs/de/docs/tutorial/request-forms.md b/docs/de/docs/tutorial/request-forms.md index 0784aa8c0..2b6aeb41c 100644 --- a/docs/de/docs/tutorial/request-forms.md +++ b/docs/de/docs/tutorial/request-forms.md @@ -32,7 +32,7 @@ Importieren Sie `Form` von `fastapi`: //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -66,7 +66,7 @@ Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` mach //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -90,7 +90,7 @@ Mit `Form` haben Sie die gleichen Konfigurationsmöglichkeiten wie mit `Body` (u /// -/// tip | "Tipp" +/// tip | Tipp Um Formularbodys zu deklarieren, verwenden Sie explizit `Form`, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden. @@ -102,7 +102,7 @@ HTML-Formulare (`
`) senden die Daten in einer „speziellen“ Kodi **FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten. -/// note | "Technische Details" +/// note | Technische Details Daten aus Formularen werden normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert. @@ -112,7 +112,7 @@ Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen /// -/// warning | "Achtung" +/// warning | Achtung Sie können mehrere `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `application/x-www-form-urlencoded` statt `application/json` kodiert. diff --git a/docs/de/docs/tutorial/response-model.md b/docs/de/docs/tutorial/response-model.md index 31ad73c77..aa27e0726 100644 --- a/docs/de/docs/tutorial/response-model.md +++ b/docs/de/docs/tutorial/response-model.md @@ -83,7 +83,7 @@ Sie können `response_model` in jeder möglichen *Pfadoperation* verwenden: //// -/// note | "Hinweis" +/// note | Hinweis Beachten Sie, dass `response_model` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter. @@ -93,7 +93,7 @@ Beachten Sie, dass `response_model` ein Parameter der „Dekorator“-Methode is FastAPI wird dieses `response_model` nehmen, um die Daten zu dokumentieren, validieren, usw. und auch, um **die Ausgabedaten** entsprechend der Typdeklaration **zu konvertieren und filtern**. -/// tip | "Tipp" +/// tip | Tipp Wenn Sie in Ihrem Editor strikte Typchecks haben, mypy, usw., können Sie den Funktions-Rückgabetyp als `Any` deklarieren. @@ -162,7 +162,7 @@ Hier ist das möglicherweise kein Problem, da es derselbe Benutzer ist, der das Aber wenn wir dasselbe Modell für eine andere *Pfadoperation* verwenden, könnten wir das Passwort dieses Benutzers zu jedem Client schicken. -/// danger | "Gefahr" +/// danger | Gefahr Speichern Sie niemals das Klartext-Passwort eines Benutzers, oder versenden Sie es in einer Response wie dieser, wenn Sie sich nicht der resultierenden Gefahren bewusst sind und nicht wissen, was Sie tun. @@ -503,7 +503,7 @@ dann ist FastAPI klug genug (tatsächlich ist Pydantic klug genug) zu erkennen, Diese Felder werden also in der JSON-Response enthalten sein. -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass Defaultwerte alles Mögliche sein können, nicht nur `None`. @@ -519,7 +519,7 @@ Diese nehmen ein `set` von `str`s entgegen, welches Namen von Attributen sind, d Das kann als schnelle Abkürzung verwendet werden, wenn Sie nur ein Pydantic-Modell haben und ein paar Daten von der Ausgabe ausschließen wollen. -/// tip | "Tipp" +/// tip | Tipp Es wird dennoch empfohlen, dass Sie die Ideen von oben verwenden, also mehrere Klassen statt dieser Parameter. @@ -545,7 +545,7 @@ Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert. //// -/// tip | "Tipp" +/// tip | Tipp Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten. diff --git a/docs/de/docs/tutorial/response-status-code.md b/docs/de/docs/tutorial/response-status-code.md index 5f017355b..a1b388a0a 100644 --- a/docs/de/docs/tutorial/response-status-code.md +++ b/docs/de/docs/tutorial/response-status-code.md @@ -10,7 +10,7 @@ So wie ein Responsemodell, können Sie auch einen HTTP-Statuscode für die Respo {* ../../docs_src/response_status_code/tutorial001.py hl[6] *} -/// note | "Hinweis" +/// note | Hinweis Beachten Sie, dass `status_code` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter und der Body. @@ -31,7 +31,7 @@ Das wird: -/// note | "Hinweis" +/// note | Hinweis Einige Responsecodes (siehe nächster Abschnitt) kennzeichnen, dass die Response keinen Body hat. @@ -41,7 +41,7 @@ FastAPI versteht das und wird in der OpenAPI-Dokumentation anzeigen, dass es kei ## Über HTTP-Statuscodes -/// note | "Hinweis" +/// note | Hinweis Wenn Sie bereits wissen, was HTTP-Statuscodes sind, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort. @@ -64,7 +64,7 @@ Kurz: * Für allgemeine Fehler beim Client können Sie einfach `400` verwenden. * `500` und darüber stehen für Server-Fehler. Diese verwenden Sie fast nie direkt. Wenn etwas an irgendeiner Stelle in Ihrem Anwendungscode oder im Server schiefläuft, wird automatisch einer dieser Fehler-Statuscodes zurückgegeben. -/// tip | "Tipp" +/// tip | Tipp Um mehr über Statuscodes zu lernen, und welcher wofür verwendet wird, lesen Sie die MDN Dokumentation über HTTP-Statuscodes. @@ -88,7 +88,7 @@ Diese sind nur eine Annehmlichkeit und enthalten dieselbe Nummer, aber auf diese -/// note | "Technische Details" +/// note | Technische Details Sie können auch `from starlette import status` verwenden. diff --git a/docs/de/docs/tutorial/schema-extra-example.md b/docs/de/docs/tutorial/schema-extra-example.md index ae3b98709..f065ad4ca 100644 --- a/docs/de/docs/tutorial/schema-extra-example.md +++ b/docs/de/docs/tutorial/schema-extra-example.md @@ -38,7 +38,7 @@ Sie können `schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Date //// -/// tip | "Tipp" +/// tip | Tipp Mit derselben Technik können Sie das JSON-Schema erweitern und Ihre eigenen benutzerdefinierten Zusatzinformationen hinzufügen. @@ -143,7 +143,7 @@ Wenn `openapi_examples` zu `Body()` hinzugefügt wird, würde `/docs` so aussehe ## Technische Details -/// tip | "Tipp" +/// tip | Tipp Wenn Sie bereits **FastAPI** Version **0.99.0 oder höher** verwenden, können Sie diese Details wahrscheinlich **überspringen**. @@ -153,7 +153,7 @@ Sie können dies als eine kurze **Geschichtsstunde** zu OpenAPI und JSON Schema /// -/// warning | "Achtung" +/// warning | Achtung Dies sind sehr technische Details zu den Standards **JSON Schema** und **OpenAPI**. diff --git a/docs/de/docs/tutorial/security/first-steps.md b/docs/de/docs/tutorial/security/first-steps.md index c552a681b..935b8ecca 100644 --- a/docs/de/docs/tutorial/security/first-steps.md +++ b/docs/de/docs/tutorial/security/first-steps.md @@ -38,7 +38,7 @@ Kopieren Sie das Beispiel in eine Datei `main.py`: //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -82,7 +82,7 @@ Sie werden etwa Folgendes sehen: -/// check | "Authorize-Button!" +/// check | Authorize-Button! Sie haben bereits einen glänzenden, neuen „Authorize“-Button. @@ -94,7 +94,7 @@ Und wenn Sie darauf klicken, erhalten Sie ein kleines Anmeldeformular zur Eingab -/// note | "Hinweis" +/// note | Hinweis Es spielt keine Rolle, was Sie in das Formular eingeben, es wird noch nicht funktionieren. Wir kommen dahin. @@ -172,7 +172,7 @@ Wenn wir eine Instanz der Klasse `OAuth2PasswordBearer` erstellen, übergeben wi //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -184,7 +184,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// -/// tip | "Tipp" +/// tip | Tipp Hier bezieht sich `tokenUrl="token"` auf eine relative URL `token`, die wir noch nicht erstellt haben. Da es sich um eine relative URL handelt, entspricht sie `./token`. @@ -238,7 +238,7 @@ Jetzt können Sie dieses `oauth2_scheme` als Abhängigkeit `Depends` übergeben. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -254,7 +254,7 @@ Diese Abhängigkeit stellt einen `str` bereit, der dem Parameter `token` der *Pf **FastAPI** weiß, dass es diese Abhängigkeit verwenden kann, um ein „Sicherheitsschema“ im OpenAPI-Schema (und der automatischen API-Dokumentation) zu definieren. -/// info | "Technische Details" +/// info | Technische Details **FastAPI** weiß, dass es die Klasse `OAuth2PasswordBearer` (deklariert in einer Abhängigkeit) verwenden kann, um das Sicherheitsschema in OpenAPI zu definieren, da es von `fastapi.security.oauth2.OAuth2` erbt, das wiederum von `fastapi.security.base.SecurityBase` erbt. diff --git a/docs/de/docs/tutorial/security/get-current-user.md b/docs/de/docs/tutorial/security/get-current-user.md index a9478a36e..5f28f231f 100644 --- a/docs/de/docs/tutorial/security/get-current-user.md +++ b/docs/de/docs/tutorial/security/get-current-user.md @@ -20,7 +20,7 @@ Im vorherigen Kapitel hat das Sicherheitssystem (das auf dem Dependency Injectio //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -68,7 +68,7 @@ So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch üb //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -82,7 +82,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -130,7 +130,7 @@ So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -144,7 +144,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -186,7 +186,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -200,7 +200,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -242,7 +242,7 @@ Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der * //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -256,7 +256,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -272,7 +272,7 @@ Beachten Sie, dass wir als Typ von `current_user` das Pydantic-Modell `User` dek Das wird uns innerhalb der Funktion bei Codevervollständigung und Typprüfungen helfen. -/// tip | "Tipp" +/// tip | Tipp Sie erinnern sich vielleicht, dass Requestbodys ebenfalls mit Pydantic-Modellen deklariert werden. @@ -346,7 +346,7 @@ Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -360,7 +360,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. diff --git a/docs/de/docs/tutorial/security/index.md b/docs/de/docs/tutorial/security/index.md index ad0927361..b01243901 100644 --- a/docs/de/docs/tutorial/security/index.md +++ b/docs/de/docs/tutorial/security/index.md @@ -32,7 +32,7 @@ Heutzutage ist es nicht sehr populär und wird kaum verwendet. OAuth2 spezifiziert nicht, wie die Kommunikation verschlüsselt werden soll, sondern erwartet, dass Ihre Anwendung mit HTTPS bereitgestellt wird. -/// tip | "Tipp" +/// tip | Tipp Im Abschnitt über **Deployment** erfahren Sie, wie Sie HTTPS mithilfe von Traefik und Let's Encrypt kostenlos einrichten. @@ -89,7 +89,7 @@ OpenAPI definiert die folgenden Sicherheitsschemas: * Diese automatische Erkennung ist es, die in der OpenID Connect Spezifikation definiert ist. -/// tip | "Tipp" +/// tip | Tipp Auch die Integration anderer Authentifizierungs-/Autorisierungsanbieter wie Google, Facebook, Twitter, GitHub, usw. ist möglich und relativ einfach. diff --git a/docs/de/docs/tutorial/security/oauth2-jwt.md b/docs/de/docs/tutorial/security/oauth2-jwt.md index 79e817840..25c1e1c97 100644 --- a/docs/de/docs/tutorial/security/oauth2-jwt.md +++ b/docs/de/docs/tutorial/security/oauth2-jwt.md @@ -44,7 +44,7 @@ $ pip install "python-jose[cryptography]" Hier verwenden wir das empfohlene: pyca/cryptography. -/// tip | "Tipp" +/// tip | Tipp Dieses Tutorial verwendete zuvor PyJWT. @@ -86,7 +86,7 @@ $ pip install "passlib[bcrypt]" -/// tip | "Tipp" +/// tip | Tipp Mit `passlib` können Sie sogar konfigurieren, Passwörter zu lesen, die von **Django**, einem **Flask**-Sicherheit-Plugin, oder vielen anderen erstellt wurden. @@ -102,7 +102,7 @@ Importieren Sie die benötigten Tools aus `passlib`. Erstellen Sie einen PassLib-„Kontext“. Der wird für das Hashen und Verifizieren von Passwörtern verwendet. -/// tip | "Tipp" +/// tip | Tipp Der PassLib-Kontext kann auch andere Hashing-Algorithmen verwenden, einschließlich deprecateter Alter, um etwa nur eine Verifizierung usw. zu ermöglichen. @@ -144,7 +144,7 @@ Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben. //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -158,7 +158,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -170,7 +170,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// -/// note | "Hinweis" +/// note | Hinweis Wenn Sie sich die neue (gefakte) Datenbank `fake_users_db` anschauen, sehen Sie, wie das gehashte Passwort jetzt aussieht: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. @@ -230,7 +230,7 @@ Erstellen Sie eine Hilfsfunktion, um einen neuen Zugriffstoken zu generieren. //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -244,7 +244,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -290,7 +290,7 @@ Wenn der Token ungültig ist, geben Sie sofort einen HTTP-Fehler zurück. //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -304,7 +304,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -348,7 +348,7 @@ Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück. //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -362,7 +362,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -436,7 +436,7 @@ Wenn Sie die Developer Tools öffnen, können Sie sehen, dass die gesendeten Dat -/// note | "Hinweis" +/// note | Hinweis Beachten Sie den Header `Authorization` mit einem Wert, der mit `Bearer` beginnt. diff --git a/docs/de/docs/tutorial/security/simple-oauth2.md b/docs/de/docs/tutorial/security/simple-oauth2.md index 4c20fae55..2fa1385b0 100644 --- a/docs/de/docs/tutorial/security/simple-oauth2.md +++ b/docs/de/docs/tutorial/security/simple-oauth2.md @@ -78,7 +78,7 @@ Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als A //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -92,7 +92,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -111,7 +111,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. * Einem optionalen `scope`-Feld als langem String, bestehend aus durch Leerzeichen getrennten Strings. * Einem optionalen `grant_type` („Art der Anmeldung“). -/// tip | "Tipp" +/// tip | Tipp Die OAuth2-Spezifikation *erfordert* tatsächlich ein Feld `grant_type` mit dem festen Wert `password`, aber `OAuth2PasswordRequestForm` erzwingt dies nicht. @@ -136,7 +136,7 @@ Da es sich jedoch um einen häufigen Anwendungsfall handelt, wird er zur Vereinf ### Die Formulardaten verwenden -/// tip | "Tipp" +/// tip | Tipp Die Instanz der Klassenabhängigkeit `OAuth2PasswordRequestForm` verfügt, statt eines Attributs `scope` mit dem durch Leerzeichen getrennten langen String, über das Attribut `scopes` mit einer tatsächlichen Liste von Strings, einem für jeden gesendeten Scope. @@ -176,7 +176,7 @@ Für den Fehler verwenden wir die Exception `HTTPException`: //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -190,7 +190,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -252,7 +252,7 @@ Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen Sy //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -266,7 +266,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -310,7 +310,7 @@ Und es sollte einen `access_token` haben, mit einem String, der unseren Zugriffs In diesem einfachen Beispiel gehen wir einfach völlig unsicher vor und geben denselben `username` wie der Token zurück. -/// tip | "Tipp" +/// tip | Tipp Im nächsten Kapitel sehen Sie eine wirklich sichere Implementierung mit Passwort-Hashing und JWT-Tokens. @@ -344,7 +344,7 @@ Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benö //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -358,7 +358,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -370,7 +370,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// -/// tip | "Tipp" +/// tip | Tipp Gemäß der Spezifikation sollten Sie ein JSON mit einem `access_token` und einem `token_type` zurückgeben, genau wie in diesem Beispiel. @@ -420,7 +420,7 @@ In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -434,7 +434,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. diff --git a/docs/de/docs/tutorial/static-files.md b/docs/de/docs/tutorial/static-files.md index 4afd251aa..aa44e3f4e 100644 --- a/docs/de/docs/tutorial/static-files.md +++ b/docs/de/docs/tutorial/static-files.md @@ -11,7 +11,7 @@ Mit `StaticFiles` können Sie statische Dateien aus einem Verzeichnis automatisc {!../../docs_src/static_files/tutorial001.py!} ``` -/// note | "Technische Details" +/// note | Technische Details Sie könnten auch `from starlette.staticfiles import StaticFiles` verwenden. diff --git a/docs/de/docs/tutorial/testing.md b/docs/de/docs/tutorial/testing.md index bda6d7d60..53459342b 100644 --- a/docs/de/docs/tutorial/testing.md +++ b/docs/de/docs/tutorial/testing.md @@ -30,7 +30,7 @@ Schreiben Sie einfache `assert`-Anweisungen mit den Standard-Python-Ausdrücken, {!../../docs_src/app_testing/tutorial001.py!} ``` -/// tip | "Tipp" +/// tip | Tipp Beachten Sie, dass die Testfunktionen normal `def` und nicht `async def` sind. @@ -40,7 +40,7 @@ Dadurch können Sie `pytest` ohne Komplikationen direkt nutzen. /// -/// note | "Technische Details" +/// note | Technische Details Sie könnten auch `from starlette.testclient import TestClient` verwenden. @@ -48,7 +48,7 @@ Sie könnten auch `from starlette.testclient import TestClient` verwenden. /// -/// tip | "Tipp" +/// tip | Tipp Wenn Sie in Ihren Tests neben dem Senden von Anfragen an Ihre FastAPI-Anwendung auch `async`-Funktionen aufrufen möchten (z. B. asynchrone Datenbankfunktionen), werfen Sie einen Blick auf die [Async-Tests](../advanced/async-tests.md){.internal-link target=_blank} im Handbuch für fortgeschrittene Benutzer. @@ -148,7 +148,7 @@ Beide *Pfadoperationen* erfordern einen `X-Token`-Header. //// tab | Python 3.10+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. @@ -162,7 +162,7 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. //// tab | Python 3.8+ nicht annotiert -/// tip | "Tipp" +/// tip | Tipp Bevorzugen Sie die `Annotated`-Version, falls möglich. diff --git a/docs/em/docs/advanced/additional-status-codes.md b/docs/em/docs/advanced/additional-status-codes.md index 7a50e1bca..5eb2ec90e 100644 --- a/docs/em/docs/advanced/additional-status-codes.md +++ b/docs/em/docs/advanced/additional-status-codes.md @@ -28,7 +28,7 @@ /// -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.responses import JSONResponse`. diff --git a/docs/em/docs/advanced/behind-a-proxy.md b/docs/em/docs/advanced/behind-a-proxy.md index e66ddccf7..36aa2e6b3 100644 --- a/docs/em/docs/advanced/behind-a-proxy.md +++ b/docs/em/docs/advanced/behind-a-proxy.md @@ -80,7 +80,7 @@ $ uvicorn main:app --root-path /api/v1 🚥 👆 ⚙️ Hypercorn, ⚫️ ✔️ 🎛 `--root-path`. -/// note | "📡 ℹ" +/// note | 📡 ℹ 🔫 🔧 🔬 `root_path` 👉 ⚙️ 💼. diff --git a/docs/em/docs/advanced/custom-response.md b/docs/em/docs/advanced/custom-response.md index 7147a4536..301f99957 100644 --- a/docs/em/docs/advanced/custom-response.md +++ b/docs/em/docs/advanced/custom-response.md @@ -121,7 +121,7 @@ ✔️ 🤯 👈 👆 💪 ⚙️ `Response` 📨 🕳 🙆, ⚖️ ✍ 🛃 🎧-🎓. -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`. diff --git a/docs/em/docs/advanced/middleware.md b/docs/em/docs/advanced/middleware.md index 23d2918d7..914ce4a30 100644 --- a/docs/em/docs/advanced/middleware.md +++ b/docs/em/docs/advanced/middleware.md @@ -43,7 +43,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** 🔌 📚 🛠️ ⚠ ⚙️ 💼, 👥 🔜 👀 ⏭ ❔ ⚙️ 👫. -/// note | "📡 ℹ" +/// note | 📡 ℹ ⏭ 🖼, 👆 💪 ⚙️ `from starlette.middleware.something import SomethingMiddleware`. diff --git a/docs/em/docs/advanced/path-operation-advanced-configuration.md b/docs/em/docs/advanced/path-operation-advanced-configuration.md index 805bfdf30..47e89a90f 100644 --- a/docs/em/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/em/docs/advanced/path-operation-advanced-configuration.md @@ -74,7 +74,7 @@ 🕐❔ 👆 📣 *➡ 🛠️* 👆 🈸, **FastAPI** 🔁 🏗 🔗 🗃 🔃 👈 *➡ 🛠️* 🔌 🗄 🔗. -/// note | "📡 ℹ" +/// note | 📡 ℹ 🗄 🔧 ⚫️ 🤙 🛠️ 🎚. diff --git a/docs/em/docs/advanced/response-cookies.md b/docs/em/docs/advanced/response-cookies.md index 6b9e9a4d9..0fe47baec 100644 --- a/docs/em/docs/advanced/response-cookies.md +++ b/docs/em/docs/advanced/response-cookies.md @@ -42,7 +42,7 @@ ### 🌅 ℹ -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`. diff --git a/docs/em/docs/advanced/response-directly.md b/docs/em/docs/advanced/response-directly.md index dcffc56c6..335c381c7 100644 --- a/docs/em/docs/advanced/response-directly.md +++ b/docs/em/docs/advanced/response-directly.md @@ -38,7 +38,7 @@ {!../../docs_src/response_directly/tutorial001.py!} ``` -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.responses import JSONResponse`. diff --git a/docs/em/docs/advanced/response-headers.md b/docs/em/docs/advanced/response-headers.md index cbbbae237..d577347fe 100644 --- a/docs/em/docs/advanced/response-headers.md +++ b/docs/em/docs/advanced/response-headers.md @@ -28,7 +28,7 @@ {!../../docs_src/response_headers/tutorial001.py!} ``` -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`. diff --git a/docs/em/docs/advanced/security/oauth2-scopes.md b/docs/em/docs/advanced/security/oauth2-scopes.md index 661be034e..f4d1a3b82 100644 --- a/docs/em/docs/advanced/security/oauth2-scopes.md +++ b/docs/em/docs/advanced/security/oauth2-scopes.md @@ -134,7 +134,7 @@ Oauth2️⃣ 👫 🎻. {!../../docs_src/security/tutorial005.py!} ``` -/// info | "📡 ℹ" +/// info | 📡 ℹ `Security` 🤙 🏿 `Depends`, & ⚫️ ✔️ 1️⃣ ➕ 🔢 👈 👥 🔜 👀 ⏪. diff --git a/docs/em/docs/advanced/templates.md b/docs/em/docs/advanced/templates.md index 66c7484a6..53428151d 100644 --- a/docs/em/docs/advanced/templates.md +++ b/docs/em/docs/advanced/templates.md @@ -43,7 +43,7 @@ $ pip install jinja2 /// -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.templating import Jinja2Templates`. diff --git a/docs/em/docs/advanced/using-request-directly.md b/docs/em/docs/advanced/using-request-directly.md index ae212364f..3eb0067ad 100644 --- a/docs/em/docs/advanced/using-request-directly.md +++ b/docs/em/docs/advanced/using-request-directly.md @@ -49,7 +49,7 @@ 👆 💪 ✍ 🌅 ℹ 🔃 `Request` 🎚 🛂 💃 🧾 🕸. -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.requests import Request`. diff --git a/docs/em/docs/advanced/websockets.md b/docs/em/docs/advanced/websockets.md index 7957eba1f..4b260e20a 100644 --- a/docs/em/docs/advanced/websockets.md +++ b/docs/em/docs/advanced/websockets.md @@ -50,7 +50,7 @@ $ pip install websockets {!../../docs_src/websockets/tutorial001.py!} ``` -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.websockets import WebSocket`. diff --git a/docs/em/docs/alternatives.md b/docs/em/docs/alternatives.md index 5309de51f..59b587285 100644 --- a/docs/em/docs/alternatives.md +++ b/docs/em/docs/alternatives.md @@ -36,7 +36,7 @@ /// -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** ✔️ 🏧 🛠️ 🧾 🕸 👩‍💻 🔢. @@ -56,7 +56,7 @@ 👐 🦁 🏺, ⚫️ 😑 💖 👍 🏏 🏗 🔗. ⏭ 👜 🔎 "✳ 🎂 🛠️" 🏺. -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** ◾-🛠️. ⚒ ⚫️ ⏩ 🌀 & 🏏 🧰 & 🍕 💪. @@ -98,7 +98,7 @@ def read_url(): 👀 🔀 `requests.get(...)` & `@app.get(...)`. -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** * ✔️ 🙅 & 🏋️ 🛠️. * ⚙️ 🇺🇸🔍 👩‍🔬 📛 (🛠️) 🔗, 🎯 & 🏋️ 🌌. @@ -118,7 +118,7 @@ def read_url(): 👈 ⚫️❔ 🕐❔ 💬 🔃 ⏬ 2️⃣.0️⃣ ⚫️ ⚠ 💬 "🦁", & ⏬ 3️⃣ ➕ "🗄". -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** 🛠️ & ⚙️ 📂 🐩 🛠️ 🔧, ↩️ 🛃 🔗. @@ -147,7 +147,7 @@ def read_url(): ✋️ ⚫️ ✍ ⏭ 📤 🔀 🐍 🆎 🔑. , 🔬 🔠 🔗 👆 💪 ⚙️ 🎯 🇨🇻 & 🎓 🚚 🍭. -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** ⚙️ 📟 🔬 "🔗" 👈 🚚 💽 🆎 & 🔬, 🔁. @@ -169,7 +169,7 @@ Webarg ✍ 🎏 🍭 👩‍💻. /// -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** ✔️ 🏧 🔬 📨 📨 💽. @@ -199,7 +199,7 @@ APISpec ✍ 🎏 🍭 👩‍💻. /// -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** 🐕‍🦺 📂 🐩 🛠️, 🗄. @@ -231,7 +231,7 @@ APISpec ✍ 🎏 🍭 👩‍💻. /// -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** 🏗 🗄 🔗 🔁, ⚪️➡️ 🎏 📟 👈 🔬 🛠️ & 🔬. @@ -251,7 +251,7 @@ APISpec ✍ 🎏 🍭 👩‍💻. ⚫️ 💪 🚫 🍵 🔁 🏷 📶 👍. , 🚥 🎻 💪 📨 🎻 🎚 👈 ✔️ 🔘 🏑 👈 🔄 🐦 🎻 🎚, ⚫️ 🚫🔜 ☑ 📄 & ✔. -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** ⚙️ 🐍 🆎 ✔️ 👑 👨‍🎨 🐕‍🦺. @@ -263,7 +263,7 @@ APISpec ✍ 🎏 🍭 👩‍💻. ⚫️ 🕐 🥇 📶 ⏩ 🐍 🛠️ ⚓️ 🔛 `asyncio`. ⚫️ ⚒ 📶 🎏 🏺. -/// note | "📡 ℹ" +/// note | 📡 ℹ ⚫️ ⚙️ `uvloop` ↩️ 🔢 🐍 `asyncio` ➰. 👈 ⚫️❔ ⚒ ⚫️ ⏩. @@ -271,7 +271,7 @@ APISpec ✍ 🎏 🍭 👩‍💻. /// -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** 🔎 🌌 ✔️ 😜 🎭. @@ -287,7 +287,7 @@ APISpec ✍ 🎏 🍭 👩‍💻. , 💽 🔬, 🛠️, & 🧾, ✔️ ⌛ 📟, 🚫 🔁. ⚖️ 👫 ✔️ 🛠️ 🛠️ 🔛 🔝 🦅, 💖 🤗. 👉 🎏 🔺 🔨 🎏 🛠️ 👈 😮 🦅 🔧, ✔️ 1️⃣ 📨 🎚 & 1️⃣ 📨 🎚 🔢. -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** 🔎 🌌 🤚 👑 🎭. @@ -313,7 +313,7 @@ APISpec ✍ 🎏 🍭 👩‍💻. 🛣 📣 👁 🥉, ⚙️ 🔢 📣 🎏 🥉 (↩️ ⚙️ 👨‍🎨 👈 💪 🥉 ▶️️ 🔛 🔝 🔢 👈 🍵 🔗). 👉 🔐 ❔ ✳ 🔨 ⚫️ 🌘 ❔ 🏺 (& 💃) 🔨 ⚫️. ⚫️ 🎏 📟 👜 👈 📶 😆 🔗. -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** 🔬 ➕ 🔬 💽 🆎 ⚙️ "🔢" 💲 🏷 🔢. 👉 📉 👨‍🎨 🐕‍🦺, & ⚫️ 🚫 💪 Pydantic ⏭. @@ -341,7 +341,7 @@ APISpec ✍ 🎏 🍭 👩‍💻. /// -/// check | "💭 😮 **FastAPI**" +/// check | 💭 😮 **FastAPI** 🤗 😮 🍕 APIStar, & 1️⃣ 🧰 👤 🔎 🏆 👍, 🌟 APIStar. @@ -385,7 +385,7 @@ APIStar ✍ ✡ 🇺🇸🏛. 🎏 👨 👈 ✍: /// -/// check | "😮 **FastAPI** " +/// check | 😮 **FastAPI** 🔀. @@ -409,7 +409,7 @@ Pydantic 🗃 🔬 💽 🔬, 🛠️ & 🧾 (⚙️ 🎻 🔗) ⚓️ 🔛 ⚫️ ⭐ 🍭. 👐 ⚫️ ⏩ 🌘 🍭 📇. & ⚫️ ⚓️ 🔛 🎏 🐍 🆎 🔑, 👨‍🎨 🐕‍🦺 👑. -/// check | "**FastAPI** ⚙️ ⚫️" +/// check | **FastAPI** ⚙️ ⚫️ 🍵 🌐 💽 🔬, 💽 🛠️ & 🏧 🏷 🧾 (⚓️ 🔛 🎻 🔗). @@ -444,7 +444,7 @@ Pydantic 🗃 🔬 💽 🔬, 🛠️ & 🧾 (⚙️ 🎻 🔗) ⚓️ 🔛 👈 1️⃣ 👑 👜 👈 **FastAPI** 🚮 🔛 🔝, 🌐 ⚓️ 🔛 🐍 🆎 🔑 (⚙️ Pydantic). 👈, ➕ 🔗 💉 ⚙️, 💂‍♂ 🚙, 🗄 🔗 ⚡, ♒️. -/// note | "📡 ℹ" +/// note | 📡 ℹ 🔫 🆕 "🐩" ➖ 🛠️ ✳ 🐚 🏉 👨‍🎓. ⚫️ 🚫 "🐍 🐩" (🇩🇬), 👐 👫 🛠️ 🔨 👈. @@ -452,7 +452,7 @@ Pydantic 🗃 🔬 💽 🔬, 🛠️ & 🧾 (⚙️ 🎻 🔗) ⚓️ 🔛 /// -/// check | "**FastAPI** ⚙️ ⚫️" +/// check | **FastAPI** ⚙️ ⚫️ 🍵 🌐 🐚 🕸 🍕. ❎ ⚒ 🔛 🔝. @@ -470,7 +470,7 @@ Uvicorn 🌩-⏩ 🔫 💽, 🏗 🔛 uvloop & httptool. ⚫️ 👍 💽 💃 & **FastAPI**. -/// check | "**FastAPI** 👍 ⚫️" +/// check | **FastAPI** 👍 ⚫️ 👑 🕸 💽 🏃 **FastAPI** 🈸. diff --git a/docs/em/docs/how-to/custom-request-and-route.md b/docs/em/docs/how-to/custom-request-and-route.md index 0425e6267..cd8811d4e 100644 --- a/docs/em/docs/how-to/custom-request-and-route.md +++ b/docs/em/docs/how-to/custom-request-and-route.md @@ -60,7 +60,7 @@ {!../../docs_src/custom_request_and_route/tutorial001.py!} ``` -/// note | "📡 ℹ" +/// note | 📡 ℹ `Request` ✔️ `request.scope` 🔢, 👈 🐍 `dict` ⚗ 🗃 🔗 📨. diff --git a/docs/em/docs/tutorial/bigger-applications.md b/docs/em/docs/tutorial/bigger-applications.md index 074ab302c..68f506f27 100644 --- a/docs/em/docs/tutorial/bigger-applications.md +++ b/docs/em/docs/tutorial/bigger-applications.md @@ -414,7 +414,7 @@ from .routers.users import router ⚫️ 🔜 🔌 🌐 🛣 ⚪️➡️ 👈 📻 🍕 ⚫️. -/// note | "📡 ℹ" +/// note | 📡 ℹ ⚫️ 🔜 🤙 🔘 ✍ *➡ 🛠️* 🔠 *➡ 🛠️* 👈 📣 `APIRouter`. @@ -477,7 +477,7 @@ from .routers.users import router & ⚫️ 🔜 👷 ☑, 👯‍♂️ ⏮️ 🌐 🎏 *➡ 🛠️* 🚮 ⏮️ `app.include_router()`. -/// info | "📶 📡 ℹ" +/// info | 📶 📡 ℹ **🗒**: 👉 📶 📡 ℹ 👈 👆 🎲 💪 **🚶**. diff --git a/docs/em/docs/tutorial/body-fields.md b/docs/em/docs/tutorial/body-fields.md index eb3093de2..be39b4a9a 100644 --- a/docs/em/docs/tutorial/body-fields.md +++ b/docs/em/docs/tutorial/body-fields.md @@ -50,7 +50,7 @@ `Field` 👷 🎏 🌌 `Query`, `Path` & `Body`, ⚫️ ✔️ 🌐 🎏 🔢, ♒️. -/// note | "📡 ℹ" +/// note | 📡 ℹ 🤙, `Query`, `Path` & 🎏 👆 🔜 👀 ⏭ ✍ 🎚 🏿 ⚠ `Param` 🎓, ❔ ⚫️ 🏿 Pydantic `FieldInfo` 🎓. diff --git a/docs/em/docs/tutorial/cookie-params.md b/docs/em/docs/tutorial/cookie-params.md index f4956e76f..5126eab0a 100644 --- a/docs/em/docs/tutorial/cookie-params.md +++ b/docs/em/docs/tutorial/cookie-params.md @@ -44,7 +44,7 @@ //// -/// note | "📡 ℹ" +/// note | 📡 ℹ `Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. diff --git a/docs/em/docs/tutorial/cors.md b/docs/em/docs/tutorial/cors.md index 5829319cb..801d66fdd 100644 --- a/docs/em/docs/tutorial/cors.md +++ b/docs/em/docs/tutorial/cors.md @@ -78,7 +78,7 @@ 🌖 ℹ 🔃 , ✅ 🦎 ⚜ 🧾. -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.middleware.cors import CORSMiddleware`. diff --git a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md index e0d6dba24..2896be39d 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md @@ -10,7 +10,7 @@ FastAPI 🐕‍🦺 🔗 👈 🔑 👨‍💼. diff --git a/docs/em/docs/tutorial/first-steps.md b/docs/em/docs/tutorial/first-steps.md index d8cc05c40..d6762422e 100644 --- a/docs/em/docs/tutorial/first-steps.md +++ b/docs/em/docs/tutorial/first-steps.md @@ -139,7 +139,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) `FastAPI` 🐍 🎓 👈 🚚 🌐 🛠️ 👆 🛠️. -/// note | "📡 ℹ" +/// note | 📡 ℹ `FastAPI` 🎓 👈 😖 🔗 ⚪️➡️ `Starlette`. @@ -259,7 +259,7 @@ https://example.com/items/foo * ➡ `/` * ⚙️ get 🛠️ -/// info | "`@decorator` ℹ" +/// info | `@decorator` ℹ 👈 `@something` ❕ 🐍 🤙 "👨‍🎨". diff --git a/docs/em/docs/tutorial/handling-errors.md b/docs/em/docs/tutorial/handling-errors.md index 7f6a704eb..e0edae51a 100644 --- a/docs/em/docs/tutorial/handling-errors.md +++ b/docs/em/docs/tutorial/handling-errors.md @@ -109,7 +109,7 @@ {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.requests import Request` & `from starlette.responses import JSONResponse`. @@ -192,7 +192,7 @@ path -> item_id {!../../docs_src/handling_errors/tutorial004.py!} ``` -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.responses import PlainTextResponse`. diff --git a/docs/em/docs/tutorial/header-params.md b/docs/em/docs/tutorial/header-params.md index 34abd3a4c..d9eafe77e 100644 --- a/docs/em/docs/tutorial/header-params.md +++ b/docs/em/docs/tutorial/header-params.md @@ -44,7 +44,7 @@ //// -/// note | "📡 ℹ" +/// note | 📡 ℹ `Header` "👭" 🎓 `Path`, `Query` & `Cookie`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. diff --git a/docs/em/docs/tutorial/middleware.md b/docs/em/docs/tutorial/middleware.md index cd0777ebb..a794ab019 100644 --- a/docs/em/docs/tutorial/middleware.md +++ b/docs/em/docs/tutorial/middleware.md @@ -11,7 +11,7 @@ * ⚫️ 💪 🕳 👈 **📨** ⚖️ 🏃 🙆 💪 📟. * ⤴️ ⚫️ 📨 **📨**. -/// note | "📡 ℹ" +/// note | 📡 ℹ 🚥 👆 ✔️ 🔗 ⏮️ `yield`, 🚪 📟 🔜 🏃 *⏮️* 🛠️. @@ -43,7 +43,7 @@ /// -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.requests import Request`. diff --git a/docs/em/docs/tutorial/path-operation-configuration.md b/docs/em/docs/tutorial/path-operation-configuration.md index 9529928fb..deb71c807 100644 --- a/docs/em/docs/tutorial/path-operation-configuration.md +++ b/docs/em/docs/tutorial/path-operation-configuration.md @@ -42,7 +42,7 @@ 👈 👔 📟 🔜 ⚙️ 📨 & 🔜 🚮 🗄 🔗. -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette import status`. diff --git a/docs/em/docs/tutorial/path-params-numeric-validations.md b/docs/em/docs/tutorial/path-params-numeric-validations.md index c25f0323e..74dbb55f7 100644 --- a/docs/em/docs/tutorial/path-params-numeric-validations.md +++ b/docs/em/docs/tutorial/path-params-numeric-validations.md @@ -140,7 +140,7 @@ /// -/// note | "📡 ℹ" +/// note | 📡 ℹ 🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢. diff --git a/docs/em/docs/tutorial/request-files.md b/docs/em/docs/tutorial/request-files.md index 102690f4b..9dcad81b4 100644 --- a/docs/em/docs/tutorial/request-files.md +++ b/docs/em/docs/tutorial/request-files.md @@ -99,13 +99,13 @@ contents = await myfile.read() contents = myfile.file.read() ``` -/// note | "`async` 📡 ℹ" +/// note | `async` 📡 ℹ 🕐❔ 👆 ⚙️ `async` 👩‍🔬, **FastAPI** 🏃 📁 👩‍🔬 🧵 & ⌛ 👫. /// -/// note | "💃 📡 ℹ" +/// note | 💃 📡 ℹ **FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI. @@ -117,7 +117,7 @@ contents = myfile.file.read() **FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻. -/// note | "📡 ℹ" +/// note | 📡 ℹ 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded` 🕐❔ ⚫️ 🚫 🔌 📁. @@ -189,7 +189,7 @@ contents = myfile.file.read() 👆 🔜 📨, 📣, `list` `bytes` ⚖️ `UploadFile`Ⓜ. -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`. diff --git a/docs/em/docs/tutorial/request-forms.md b/docs/em/docs/tutorial/request-forms.md index cbe4e2862..d364d2c92 100644 --- a/docs/em/docs/tutorial/request-forms.md +++ b/docs/em/docs/tutorial/request-forms.md @@ -50,7 +50,7 @@ **FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻. -/// note | "📡 ℹ" +/// note | 📡 ℹ 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`. diff --git a/docs/em/docs/tutorial/response-status-code.md b/docs/em/docs/tutorial/response-status-code.md index cefff708f..478060326 100644 --- a/docs/em/docs/tutorial/response-status-code.md +++ b/docs/em/docs/tutorial/response-status-code.md @@ -94,7 +94,7 @@ FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅‍♂ 📨 -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette import status`. diff --git a/docs/em/docs/tutorial/security/first-steps.md b/docs/em/docs/tutorial/security/first-steps.md index 6245f52ab..21c48757f 100644 --- a/docs/em/docs/tutorial/security/first-steps.md +++ b/docs/em/docs/tutorial/security/first-steps.md @@ -56,7 +56,7 @@ $ uvicorn main:app --reload -/// check | "✔ 🔼 ❗" +/// check | ✔ 🔼 ❗ 👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼. @@ -176,7 +176,7 @@ oauth2_scheme(some, parameters) **FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 👉 🔗 🔬 "💂‍♂ ⚖" 🗄 🔗 (& 🏧 🛠️ 🩺). -/// info | "📡 ℹ" +/// info | 📡 ℹ **FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 🎓 `OAuth2PasswordBearer` (📣 🔗) 🔬 💂‍♂ ⚖ 🗄 ↩️ ⚫️ 😖 ⚪️➡️ `fastapi.security.oauth2.OAuth2`, ❔ 🔄 😖 ⚪️➡️ `fastapi.security.base.SecurityBase`. diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md index c59d8c131..49162dd62 100644 --- a/docs/em/docs/tutorial/sql-databases.md +++ b/docs/em/docs/tutorial/sql-databases.md @@ -159,7 +159,7 @@ connect_args={"check_same_thread": False} ...💪 🕴 `SQLite`. ⚫️ 🚫 💪 🎏 💽. -/// info | "📡 ℹ" +/// info | 📡 ℹ 🔢 🗄 🔜 🕴 ✔ 1️⃣ 🧵 🔗 ⏮️ ⚫️, 🤔 👈 🔠 🧵 🔜 🍵 🔬 📨. @@ -622,7 +622,7 @@ current_user.items //// -/// info | "📡 ℹ" +/// info | 📡 ℹ 🔢 `db` 🤙 🆎 `SessionLocal`, ✋️ 👉 🎓 (✍ ⏮️ `sessionmaker()`) "🗳" 🇸🇲 `Session`,, 👨‍🎨 🚫 🤙 💭 ⚫️❔ 👩‍🔬 🚚. @@ -705,7 +705,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): /// -/// note | "📶 📡 ℹ" +/// note | 📶 📡 ℹ 🚥 👆 😟 & ✔️ ⏬ 📡 💡, 👆 💪 ✅ 📶 📡 ℹ ❔ 👉 `async def` 🆚 `def` 🍵 [🔁](../async.md#i_2){.internal-link target=_blank} 🩺. diff --git a/docs/em/docs/tutorial/static-files.md b/docs/em/docs/tutorial/static-files.md index 0627031b3..c9bb9ff6a 100644 --- a/docs/em/docs/tutorial/static-files.md +++ b/docs/em/docs/tutorial/static-files.md @@ -11,7 +11,7 @@ {!../../docs_src/static_files/tutorial001.py!} ``` -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.staticfiles import StaticFiles`. diff --git a/docs/em/docs/tutorial/testing.md b/docs/em/docs/tutorial/testing.md index 5f3d5e736..27cf9f16e 100644 --- a/docs/em/docs/tutorial/testing.md +++ b/docs/em/docs/tutorial/testing.md @@ -40,7 +40,7 @@ /// -/// note | "📡 ℹ" +/// note | 📡 ℹ 👆 💪 ⚙️ `from starlette.testclient import TestClient`. diff --git a/docs/en/docs/advanced/additional-status-codes.md b/docs/en/docs/advanced/additional-status-codes.md index e39249467..077a00488 100644 --- a/docs/en/docs/advanced/additional-status-codes.md +++ b/docs/en/docs/advanced/additional-status-codes.md @@ -26,7 +26,7 @@ Make sure it has the data you want it to have, and that the values are valid JSO /// -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.responses import JSONResponse`. diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index 87a62e88b..1f0d0fd9f 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -82,7 +82,7 @@ $ fastapi run main.py --root-path /api/v1 If you use Hypercorn, it also has the option `--root-path`. -/// note | "Technical Details" +/// note | Technical Details The ASGI specification defines a `root_path` for this use case. diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index 95152b9fe..8268dd81a 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -113,7 +113,7 @@ Here are some of the available responses. Keep in mind that you can use `Response` to return anything else, or even create a custom sub-class. -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.responses import HTMLResponse`. diff --git a/docs/en/docs/advanced/middleware.md b/docs/en/docs/advanced/middleware.md index 3faf3fbf9..1d40b1c8f 100644 --- a/docs/en/docs/advanced/middleware.md +++ b/docs/en/docs/advanced/middleware.md @@ -43,7 +43,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** includes several middlewares for common use cases, we'll see next how to use them. -/// note | "Technical Details" +/// note | Technical Details For the next examples, you could also use `from starlette.middleware.something import SomethingMiddleware`. diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md index fea1e4db0..c4814ebd2 100644 --- a/docs/en/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md @@ -66,7 +66,7 @@ There's a whole chapter here in the documentation about it, you can read it at [ When you declare a *path operation* in your application, **FastAPI** automatically generates the relevant metadata about that *path operation* to be included in the OpenAPI schema. -/// note | "Technical details" +/// note | Technical details In the OpenAPI specification it is called the Operation Object. diff --git a/docs/en/docs/advanced/response-cookies.md b/docs/en/docs/advanced/response-cookies.md index 988394d06..f6d17f35d 100644 --- a/docs/en/docs/advanced/response-cookies.md +++ b/docs/en/docs/advanced/response-cookies.md @@ -38,7 +38,7 @@ And also that you are not sending any data that should have been filtered by a ` ### More info -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md index 09947a2ee..691b1e7cd 100644 --- a/docs/en/docs/advanced/response-directly.md +++ b/docs/en/docs/advanced/response-directly.md @@ -36,7 +36,7 @@ For those cases, you can use the `jsonable_encoder` to convert your data before {* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.responses import JSONResponse`. diff --git a/docs/en/docs/advanced/response-headers.md b/docs/en/docs/advanced/response-headers.md index fca641d89..97e888983 100644 --- a/docs/en/docs/advanced/response-headers.md +++ b/docs/en/docs/advanced/response-headers.md @@ -24,7 +24,7 @@ Create a response as described in [Return a Response Directly](response-directly {* ../../docs_src/response_headers/tutorial001.py hl[10:12] *} -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index 5ba0b1c14..4cb0b39bc 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -126,7 +126,7 @@ We are doing it here to demonstrate how **FastAPI** handles scopes declared at d {* ../../docs_src/security/tutorial005_an_py310.py hl[5,140,171] *} -/// info | "Technical Details" +/// info | Technical Details `Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later. diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index d688c5cb7..76f0ef1de 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -45,7 +45,7 @@ By declaring `response_class=HTMLResponse` the docs UI will be able to know that /// -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.templating import Jinja2Templates`. diff --git a/docs/en/docs/advanced/using-request-directly.md b/docs/en/docs/advanced/using-request-directly.md index 3e35734bc..2f88c8f20 100644 --- a/docs/en/docs/advanced/using-request-directly.md +++ b/docs/en/docs/advanced/using-request-directly.md @@ -47,7 +47,7 @@ The same way, you can declare any other parameter as normally, and additionally, You can read more details about the `Request` object in the official Starlette documentation site. -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.requests import Request`. diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index 95a394749..ee8e901df 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -46,7 +46,7 @@ In your **FastAPI** application, create a `websocket`: {* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.websockets import WebSocket`. diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md index f596232d3..326f0dbe1 100644 --- a/docs/en/docs/alternatives.md +++ b/docs/en/docs/alternatives.md @@ -36,7 +36,7 @@ Django REST Framework was created by Tom Christie. The same creator of Starlette /// -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Have an automatic API documentation web user interface. @@ -56,7 +56,7 @@ This decoupling of parts, and being a "microframework" that could be extended to Given the simplicity of Flask, it seemed like a good match for building APIs. The next thing to find was a "Django REST Framework" for Flask. -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Be a micro-framework. Making it easy to mix and match the tools and parts needed. @@ -98,7 +98,7 @@ def read_url(): See the similarities in `requests.get(...)` and `@app.get(...)`. -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to * Have a simple and intuitive API. * Use HTTP method names (operations) directly, in a straightforward and intuitive way. @@ -118,7 +118,7 @@ At some point, Swagger was given to the Linux Foundation, to be renamed OpenAPI. That's why when talking about version 2.0 it's common to say "Swagger", and for version 3+ "OpenAPI". -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Adopt and use an open standard for API specifications, instead of a custom schema. @@ -147,7 +147,7 @@ These features are what Marshmallow was built to provide. It is a great library, But it was created before there existed Python type hints. So, to define every schema you need to use specific utils and classes provided by Marshmallow. -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Use code to define "schemas" that provide data types and validation, automatically. @@ -169,7 +169,7 @@ Webargs was created by the same Marshmallow developers. /// -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Have automatic validation of incoming request data. @@ -199,7 +199,7 @@ APISpec was created by the same Marshmallow developers. /// -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Support the open standard for APIs, OpenAPI. @@ -231,7 +231,7 @@ Flask-apispec was created by the same Marshmallow developers. /// -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Generate the OpenAPI schema automatically, from the same code that defines serialization and validation. @@ -251,7 +251,7 @@ But as TypeScript data is not preserved after compilation to JavaScript, it cann It can't handle nested models very well. So, if the JSON body in the request is a JSON object that has inner fields that in turn are nested JSON objects, it cannot be properly documented and validated. -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Use Python types to have great editor support. @@ -263,7 +263,7 @@ Have a powerful dependency injection system. Find a way to minimize code repetit It was one of the first extremely fast Python frameworks based on `asyncio`. It was made to be very similar to Flask. -/// note | "Technical Details" +/// note | Technical Details It used `uvloop` instead of the default Python `asyncio` loop. That's what made it so fast. @@ -271,7 +271,7 @@ It clearly inspired Uvicorn and Starlette, that are currently faster than Sanic /// -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Find a way to have a crazy performance. @@ -287,7 +287,7 @@ It is designed to have functions that receive two parameters, one "request" and So, data validation, serialization, and documentation, have to be done in code, not automatically. Or they have to be implemented as a framework on top of Falcon, like Hug. This same distinction happens in other frameworks that are inspired by Falcon's design, of having one request object and one response object as parameters. -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Find ways to get great performance. @@ -313,7 +313,7 @@ The dependency injection system requires pre-registration of the dependencies an Routes are declared in a single place, using functions declared in other places (instead of using decorators that can be placed right on top of the function that handles the endpoint). This is closer to how Django does it than to how Flask (and Starlette) does it. It separates in the code things that are relatively tightly coupled. -/// check | "Inspired **FastAPI** to" +/// check | Inspired **FastAPI** to Define extra validations for data types using the "default" value of model attributes. This improves editor support, and it was not available in Pydantic before. @@ -341,7 +341,7 @@ Hug was created by Timothy Crosley, the same creator of CORS, check the Mozilla CORS documentation. -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.middleware.cors import CORSMiddleware`. diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md index 97da668aa..430b7a73f 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md @@ -10,7 +10,7 @@ Make sure to use `yield` one single time per dependency. /// -/// note | "Technical Details" +/// note | Technical Details Any function that is valid to use with: @@ -149,7 +149,7 @@ You can have any combinations of dependencies that you want. **FastAPI** will make sure everything is run in the correct order. -/// note | "Technical Details" +/// note | Technical Details This works thanks to Python's Context Managers. diff --git a/docs/en/docs/tutorial/first-steps.md b/docs/en/docs/tutorial/first-steps.md index 1c20b945a..783295933 100644 --- a/docs/en/docs/tutorial/first-steps.md +++ b/docs/en/docs/tutorial/first-steps.md @@ -159,7 +159,7 @@ You could also use it to generate code automatically, for clients that communica `FastAPI` is a Python class that provides all the functionality for your API. -/// note | "Technical Details" +/// note | Technical Details `FastAPI` is a class that inherits directly from `Starlette`. @@ -245,7 +245,7 @@ The `@app.get("/")` tells **FastAPI** that the function right below is in charge * the path `/` * using a get operation -/// info | "`@decorator` Info" +/// info | `@decorator` Info That `@something` syntax in Python is called a "decorator". diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index 38c15761b..537cb3e72 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -109,7 +109,7 @@ So, you will receive a clean error, with an HTTP status code of `418` and a JSON {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`. @@ -192,7 +192,7 @@ For example, you could want to return a plain text response instead of JSON for {!../../docs_src/handling_errors/tutorial004.py!} ``` -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.responses import PlainTextResponse`. diff --git a/docs/en/docs/tutorial/header-params.md b/docs/en/docs/tutorial/header-params.md index e34f301a9..49ad7aa25 100644 --- a/docs/en/docs/tutorial/header-params.md +++ b/docs/en/docs/tutorial/header-params.md @@ -16,7 +16,7 @@ You can define the default value as well as all the extra validation or annotati {* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *} -/// note | "Technical Details" +/// note | Technical Details `Header` is a "sister" class of `Path`, `Query` and `Cookie`. It also inherits from the same common `Param` class. diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index 16d853018..4693d977a 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -11,7 +11,7 @@ A "middleware" is a function that works with every **request** before it is proc * It can do something to that **response** or run any needed code. * Then it returns the **response**. -/// note | "Technical Details" +/// note | Technical Details If you have dependencies with `yield`, the exit code will run *after* the middleware. @@ -41,7 +41,7 @@ But if you have custom headers that you want a client in a browser to be able to /// -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.requests import Request`. diff --git a/docs/en/docs/tutorial/path-operation-configuration.md b/docs/en/docs/tutorial/path-operation-configuration.md index c78d20ea6..f2b5fd795 100644 --- a/docs/en/docs/tutorial/path-operation-configuration.md +++ b/docs/en/docs/tutorial/path-operation-configuration.md @@ -20,7 +20,7 @@ But if you don't remember what each number code is for, you can use the shortcut That status code will be used in the response and will be added to the OpenAPI schema. -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette import status`. diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md index dc13a513c..9440bcc03 100644 --- a/docs/en/docs/tutorial/path-params-numeric-validations.md +++ b/docs/en/docs/tutorial/path-params-numeric-validations.md @@ -149,7 +149,7 @@ All of them share the same parameters for additional validation and metadata you /// -/// note | "Technical Details" +/// note | Technical Details When you import `Query`, `Path` and others from `fastapi`, they are actually functions. diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md index 2b433555b..0d57f3566 100644 --- a/docs/en/docs/tutorial/request-files.md +++ b/docs/en/docs/tutorial/request-files.md @@ -97,13 +97,13 @@ If you are inside of a normal `def` *path operation function*, you can access th contents = myfile.file.read() ``` -/// note | "`async` Technical Details" +/// note | `async` Technical Details When you use the `async` methods, **FastAPI** runs the file methods in a threadpool and awaits for them. /// -/// note | "Starlette Technical Details" +/// note | Starlette Technical Details **FastAPI**'s `UploadFile` inherits directly from **Starlette**'s `UploadFile`, but adds some necessary parts to make it compatible with **Pydantic** and the other parts of FastAPI. @@ -115,7 +115,7 @@ The way HTML forms (`
`) sends the data to the server normally uses **FastAPI** will make sure to read that data from the right place instead of JSON. -/// note | "Technical Details" +/// note | Technical Details Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded` when it doesn't include files. @@ -157,7 +157,7 @@ To use that, declare a list of `bytes` or `UploadFile`: You will receive, as declared, a `list` of `bytes` or `UploadFile`s. -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.responses import HTMLResponse`. diff --git a/docs/en/docs/tutorial/request-forms.md b/docs/en/docs/tutorial/request-forms.md index 2ccc6886e..c65e9874c 100644 --- a/docs/en/docs/tutorial/request-forms.md +++ b/docs/en/docs/tutorial/request-forms.md @@ -106,7 +106,7 @@ The way HTML forms (`
`) sends the data to the server normally uses **FastAPI** will make sure to read that data from the right place instead of JSON. -/// note | "Technical Details" +/// note | Technical Details Data from forms is normally encoded using the "media type" `application/x-www-form-urlencoded`. diff --git a/docs/en/docs/tutorial/response-status-code.md b/docs/en/docs/tutorial/response-status-code.md index a32faa40b..711042a46 100644 --- a/docs/en/docs/tutorial/response-status-code.md +++ b/docs/en/docs/tutorial/response-status-code.md @@ -88,7 +88,7 @@ They are just a convenience, they hold the same number, but that way you can use -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette import status`. diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index ead2aa799..37e37cb5b 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -88,7 +88,7 @@ You will see something like this: -/// check | "Authorize button!" +/// check | Authorize button! You already have a shiny new "Authorize" button. @@ -260,7 +260,7 @@ This dependency will provide a `str` that is assigned to the parameter `token` o **FastAPI** will know that it can use this dependency to define a "security scheme" in the OpenAPI schema (and the automatic API docs). -/// info | "Technical Details" +/// info | Technical Details **FastAPI** will know that it can use the class `OAuth2PasswordBearer` (declared in a dependency) to define the security scheme in OpenAPI because it inherits from `fastapi.security.oauth2.OAuth2`, which in turn inherits from `fastapi.security.base.SecurityBase`. diff --git a/docs/en/docs/tutorial/static-files.md b/docs/en/docs/tutorial/static-files.md index 46affd4f2..1d277a51c 100644 --- a/docs/en/docs/tutorial/static-files.md +++ b/docs/en/docs/tutorial/static-files.md @@ -9,7 +9,7 @@ You can serve static files automatically from a directory using `StaticFiles`. {* ../../docs_src/static_files/tutorial001.py hl[2,6] *} -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.staticfiles import StaticFiles`. diff --git a/docs/en/docs/tutorial/testing.md b/docs/en/docs/tutorial/testing.md index 7f609a595..a204f596f 100644 --- a/docs/en/docs/tutorial/testing.md +++ b/docs/en/docs/tutorial/testing.md @@ -44,7 +44,7 @@ This allows you to use `pytest` directly without complications. /// -/// note | "Technical Details" +/// note | Technical Details You could also use `from starlette.testclient import TestClient`. diff --git a/docs/es/docs/advanced/path-operation-advanced-configuration.md b/docs/es/docs/advanced/path-operation-advanced-configuration.md index f6813f0ff..12399d581 100644 --- a/docs/es/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/es/docs/advanced/path-operation-advanced-configuration.md @@ -2,7 +2,7 @@ ## OpenAPI operationId -/// warning | "Advertencia" +/// warning | Advertencia Si no eres una persona "experta" en OpenAPI, probablemente no necesitas leer esto. diff --git a/docs/es/docs/tutorial/cookie-params.md b/docs/es/docs/tutorial/cookie-params.md index db3fc092e..9a3b1a00b 100644 --- a/docs/es/docs/tutorial/cookie-params.md +++ b/docs/es/docs/tutorial/cookie-params.md @@ -16,7 +16,7 @@ El primer valor es el valor por defecto, puedes pasar todos los parámetros adic {* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9]*} -/// note | "Detalles Técnicos" +/// note | Detalles Técnicos `Cookie` es una clase "hermana" de `Path` y `Query`. También hereda de la misma clase común `Param`. diff --git a/docs/es/docs/tutorial/index.md b/docs/es/docs/tutorial/index.md index 46c57c4c3..fa13450f0 100644 --- a/docs/es/docs/tutorial/index.md +++ b/docs/es/docs/tutorial/index.md @@ -50,7 +50,7 @@ $ pip install "fastapi[all]" ...eso también incluye `uvicorn` que puedes usar como el servidor que ejecuta tu código. -/// note | "Nota" +/// note | Nota También puedes instalarlo parte por parte. diff --git a/docs/fa/docs/tutorial/middleware.md b/docs/fa/docs/tutorial/middleware.md index ca631d507..a3ab483fb 100644 --- a/docs/fa/docs/tutorial/middleware.md +++ b/docs/fa/docs/tutorial/middleware.md @@ -11,7 +11,7 @@ * می تواند کاری با **پاسخ** انجام دهید یا هر کد مورد نیازتان را اجرا کند. * سپس **پاسخ** را برمی گرداند. -/// توجه | "جزئیات فنی" +/// توجه | جزئیات فنی در صورت وجود وابستگی هایی با `yield`، کد خروجی **پس از** اجرای میان‌‌افزار اجرا خواهد شد. @@ -40,7 +40,7 @@ /// -/// توجه | "جزئیات فنی" +/// توجه | جزئیات فنی شما همچنین می‌توانید از `from starlette.requests import Request` استفاده کنید. diff --git a/docs/fr/docs/advanced/additional-responses.md b/docs/fr/docs/advanced/additional-responses.md index 12f944b12..38527aad3 100644 --- a/docs/fr/docs/advanced/additional-responses.md +++ b/docs/fr/docs/advanced/additional-responses.md @@ -1,6 +1,6 @@ # Réponses supplémentaires dans OpenAPI -/// warning | "Attention" +/// warning | Attention Ceci concerne un sujet plutôt avancé. @@ -28,7 +28,7 @@ Par exemple, pour déclarer une autre réponse avec un code HTTP `404` et un mod {* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} -/// note | "Remarque" +/// note | Remarque Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`. @@ -177,7 +177,7 @@ Par exemple, vous pouvez ajouter un type de média supplémentaire `image/png`, {* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} -/// note | "Remarque" +/// note | Remarque Notez que vous devez retourner l'image en utilisant directement un `FileResponse`. diff --git a/docs/fr/docs/advanced/additional-status-codes.md b/docs/fr/docs/advanced/additional-status-codes.md index 06a8043ea..c406ae8cb 100644 --- a/docs/fr/docs/advanced/additional-status-codes.md +++ b/docs/fr/docs/advanced/additional-status-codes.md @@ -18,7 +18,7 @@ Pour y parvenir, importez `JSONResponse` et renvoyez-y directement votre contenu {!../../docs_src/additional_status_codes/tutorial001.py!} ``` -/// warning | "Attention" +/// warning | Attention Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement. @@ -28,7 +28,7 @@ Assurez-vous qu'il contient les données souhaitées et que les valeurs soient d /// -/// note | "Détails techniques" +/// note | Détails techniques Vous pouvez également utiliser `from starlette.responses import JSONResponse`. diff --git a/docs/fr/docs/advanced/index.md b/docs/fr/docs/advanced/index.md index 198fa8c30..d9d8ad8e6 100644 --- a/docs/fr/docs/advanced/index.md +++ b/docs/fr/docs/advanced/index.md @@ -6,7 +6,7 @@ Le [Tutoriel - Guide de l'utilisateur](../tutorial/index.md){.internal-link targ Dans les sections suivantes, vous verrez des options, configurations et fonctionnalités supplémentaires. -/// note | "Remarque" +/// note | Remarque Les sections de ce chapitre ne sont **pas nécessairement "avancées"**. diff --git a/docs/fr/docs/advanced/path-operation-advanced-configuration.md b/docs/fr/docs/advanced/path-operation-advanced-configuration.md index b00f46727..7daf0fc65 100644 --- a/docs/fr/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/fr/docs/advanced/path-operation-advanced-configuration.md @@ -2,7 +2,7 @@ ## ID d'opération OpenAPI -/// warning | "Attention" +/// warning | Attention Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin. @@ -22,13 +22,13 @@ Vous devriez le faire après avoir ajouté toutes vos *paramètres de chemin*. {* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *} -/// tip | "Astuce" +/// tip | Astuce Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant. /// -/// warning | "Attention" +/// warning | Attention Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique. @@ -66,7 +66,7 @@ Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le Lorsque vous déclarez un *chemin* dans votre application, **FastAPI** génère automatiquement les métadonnées concernant ce *chemin* à inclure dans le schéma OpenAPI. -/// note | "Détails techniques" +/// note | Détails techniques La spécification OpenAPI appelle ces métadonnées des Objets d'opération. @@ -78,7 +78,7 @@ Il inclut les `tags`, `parameters`, `requestBody`, `responses`, etc. Ce schéma OpenAPI spécifique aux *operations* est normalement généré automatiquement par **FastAPI**, mais vous pouvez également l'étendre. -/// tip | "Astuce" +/// tip | Astuce Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}. @@ -161,7 +161,7 @@ Et nous analysons directement ce contenu YAML, puis nous utilisons à nouveau le {* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} -/// tip | "Astuce" +/// tip | Astuce Ici, nous réutilisons le même modèle Pydantic. diff --git a/docs/fr/docs/advanced/response-directly.md b/docs/fr/docs/advanced/response-directly.md index 338aee017..4ff883c77 100644 --- a/docs/fr/docs/advanced/response-directly.md +++ b/docs/fr/docs/advanced/response-directly.md @@ -14,7 +14,7 @@ Cela peut être utile, par exemple, pour retourner des en-têtes personnalisés En fait, vous pouvez retourner n'importe quelle `Response` ou n'importe quelle sous-classe de celle-ci. -/// note | "Remarque" +/// note | Remarque `JSONResponse` est elle-même une sous-classe de `Response`. @@ -36,7 +36,7 @@ Pour ces cas, vous pouvez spécifier un appel à `jsonable_encoder` pour convert {* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} -/// note | "Détails techniques" +/// note | Détails techniques Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`. diff --git a/docs/fr/docs/alternatives.md b/docs/fr/docs/alternatives.md index d2438dc36..4d6037910 100644 --- a/docs/fr/docs/alternatives.md +++ b/docs/fr/docs/alternatives.md @@ -43,7 +43,7 @@ Django REST framework a été créé par Tom Christie. Le créateur de Starlette /// -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Avoir une interface de documentation automatique de l'API. @@ -65,7 +65,7 @@ qui est nécessaire, était une caractéristique clé que je voulais conserver. Compte tenu de la simplicité de Flask, il semblait bien adapté à la création d'API. La prochaine chose à trouver était un "Django REST Framework" pour Flask. -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Être un micro-framework. Il est donc facile de combiner les outils et les pièces nécessaires. @@ -107,7 +107,7 @@ def read_url(): Notez les similitudes entre `requests.get(...)` et `@app.get(...)`. -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Avoir une API simple et intuitive. @@ -128,7 +128,7 @@ Swagger pour une API permettrait d'utiliser cette interface utilisateur web auto C'est pourquoi, lorsqu'on parle de la version 2.0, il est courant de dire "Swagger", et pour la version 3+ "OpenAPI". -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Adopter et utiliser une norme ouverte pour les spécifications des API, au lieu d'un schéma personnalisé. @@ -166,7 +166,7 @@ Ces fonctionnalités sont ce pourquoi Marshmallow a été construit. C'est une e Mais elle a été créée avant que les type hints n'existent en Python. Ainsi, pour définir chaque schéma, vous devez utiliser des utilitaires et des classes spécifiques fournies par Marshmallow. -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Utilisez du code pour définir des "schémas" qui fournissent automatiquement les types de données et la validation. @@ -189,7 +189,7 @@ Webargs a été créé par les développeurs de Marshmallow. /// -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Disposer d'une validation automatique des données des requêtes entrantes. @@ -219,7 +219,7 @@ APISpec a été créé par les développeurs de Marshmallow. /// -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Supporter la norme ouverte pour les API, OpenAPI. @@ -252,7 +252,7 @@ Flask-apispec a été créé par les développeurs de Marshmallow. /// -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Générer le schéma OpenAPI automatiquement, à partir du même code qui définit la sérialisation et la validation. @@ -273,7 +273,7 @@ Mais comme les données TypeScript ne sont pas préservées après la compilatio Il ne peut pas très bien gérer les modèles imbriqués. Ainsi, si le corps JSON de la requête est un objet JSON comportant des champs internes qui sont à leur tour des objets JSON imbriqués, il ne peut pas être correctement documenté et validé. -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Utiliser les types Python pour bénéficier d'un excellent support de l'éditeur. @@ -285,7 +285,7 @@ Disposer d'un puissant système d'injection de dépendances. Trouver un moyen de C'était l'un des premiers frameworks Python extrêmement rapides basés sur `asyncio`. Il a été conçu pour être très similaire à Flask. -/// note | "Détails techniques" +/// note | Détails techniques Il utilisait `uvloop` au lieu du système par défaut de Python `asyncio`. C'est ce qui l'a rendu si rapide. @@ -293,7 +293,7 @@ Il a clairement inspiré Uvicorn et Starlette, qui sont actuellement plus rapide /// -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Trouvez un moyen d'avoir une performance folle. @@ -313,7 +313,7 @@ pas possible de déclarer des paramètres de requête et des corps avec des indi Ainsi, la validation, la sérialisation et la documentation des données doivent être effectuées dans le code, et non pas automatiquement. Ou bien elles doivent être implémentées comme un framework au-dessus de Falcon, comme Hug. Cette même distinction se retrouve dans d'autres frameworks qui s'inspirent de la conception de Falcon, qui consiste à avoir un objet de requête et un objet de réponse comme paramètres. -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Trouver des moyens d'obtenir de bonnes performances. @@ -343,7 +343,7 @@ d'utiliser des décorateurs qui peuvent être placés juste au-dessus de la fonc méthode est plus proche de celle de Django que de celle de Flask (et Starlette). Il sépare dans le code des choses qui sont relativement fortement couplées. -/// check | "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à Définir des validations supplémentaires pour les types de données utilisant la valeur "par défaut" des attributs du modèle. Ceci améliore le support de l'éditeur, et n'était pas disponible dans Pydantic auparavant. @@ -372,7 +372,7 @@ Hug a été créé par Timothy Crosley, le créateur de tiangolo/uvicorn-gunicorn-fastapi. diff --git a/docs/fr/docs/deployment/manually.md b/docs/fr/docs/deployment/manually.md index 6a737fdef..7c29242a9 100644 --- a/docs/fr/docs/deployment/manually.md +++ b/docs/fr/docs/deployment/manually.md @@ -39,7 +39,7 @@ $ pip install "uvicorn[standard]" -/// tip | "Astuce" +/// tip | Astuce En ajoutant `standard`, Uvicorn va installer et utiliser quelques dépendances supplémentaires recommandées. diff --git a/docs/fr/docs/deployment/versions.md b/docs/fr/docs/deployment/versions.md index 8ea79a172..9d84274e2 100644 --- a/docs/fr/docs/deployment/versions.md +++ b/docs/fr/docs/deployment/versions.md @@ -48,7 +48,7 @@ des changements non rétrocompatibles. FastAPI suit également la convention que tout changement de version "PATCH" est pour des corrections de bogues et des changements rétrocompatibles. -/// tip | "Astuce" +/// tip | Astuce Le "PATCH" est le dernier chiffre, par exemple, dans `0.2.3`, la version PATCH est `3`. @@ -62,7 +62,7 @@ fastapi>=0.45.0,<0.46.0 Les changements non rétrocompatibles et les nouvelles fonctionnalités sont ajoutés dans les versions "MINOR". -/// tip | "Astuce" +/// tip | Astuce Le "MINOR" est le numéro au milieu, par exemple, dans `0.2.3`, la version MINOR est `2`. diff --git a/docs/fr/docs/python-types.md b/docs/fr/docs/python-types.md index 8a0f1f3f4..99ca90827 100644 --- a/docs/fr/docs/python-types.md +++ b/docs/fr/docs/python-types.md @@ -161,7 +161,7 @@ Les listes étant un type contenant des types internes, mettez ces derniers entr {*../../docs_src/python_types/tutorial006.py hl[4] *} -/// tip | "Astuce" +/// tip | Astuce Ces types internes entre crochets sont appelés des "paramètres de type". diff --git a/docs/fr/docs/tutorial/body.md b/docs/fr/docs/tutorial/body.md index c4d493a45..760b6d80a 100644 --- a/docs/fr/docs/tutorial/body.md +++ b/docs/fr/docs/tutorial/body.md @@ -107,7 +107,7 @@ Mais vous auriez le même support de l'éditeur avec -/// tip | "Astuce" +/// tip | Astuce Si vous utilisez PyCharm comme éditeur, vous pouvez utiliser le Plugin Pydantic PyCharm Plugin. diff --git a/docs/fr/docs/tutorial/first-steps.md b/docs/fr/docs/tutorial/first-steps.md index b2fb5181c..758145362 100644 --- a/docs/fr/docs/tutorial/first-steps.md +++ b/docs/fr/docs/tutorial/first-steps.md @@ -136,7 +136,7 @@ Vous pourriez aussi l'utiliser pour générer du code automatiquement, pour les `FastAPI` est une classe Python qui fournit toutes les fonctionnalités nécessaires au lancement de votre API. -/// note | "Détails techniques" +/// note | Détails techniques `FastAPI` est une classe héritant directement de `Starlette`. @@ -249,7 +249,7 @@ Le `@app.get("/")` dit à **FastAPI** que la fonction en dessous est chargée de * le chemin `/` * en utilisant une opération get -/// info | "`@décorateur` Info" +/// info | `@décorateur` Info Cette syntaxe `@something` en Python est appelée un "décorateur". @@ -276,7 +276,7 @@ Tout comme celles les plus exotiques : * `@app.patch()` * `@app.trace()` -/// tip | "Astuce" +/// tip | Astuce Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez. diff --git a/docs/fr/docs/tutorial/path-params-numeric-validations.md b/docs/fr/docs/tutorial/path-params-numeric-validations.md index b3635fb86..3f3280e64 100644 --- a/docs/fr/docs/tutorial/path-params-numeric-validations.md +++ b/docs/fr/docs/tutorial/path-params-numeric-validations.md @@ -148,7 +148,7 @@ Tous partagent les mêmes paramètres pour des validations supplémentaires et d /// -/// note | "Détails techniques" +/// note | Détails techniques Lorsque vous importez `Query`, `Path` et d'autres de `fastapi`, ce sont en fait des fonctions. diff --git a/docs/fr/docs/tutorial/path-params.md b/docs/fr/docs/tutorial/path-params.md index 508529fae..71c96b18e 100644 --- a/docs/fr/docs/tutorial/path-params.md +++ b/docs/fr/docs/tutorial/path-params.md @@ -24,7 +24,7 @@ Vous pouvez déclarer le type d'un paramètre de chemin dans la fonction, en uti Ici, `item_id` est déclaré comme `int`. -/// check | "vérifier" +/// check | vérifier Ceci vous permettra d'obtenir des fonctionnalités de l'éditeur dans votre fonction, telles que des vérifications d'erreur, de l'auto-complétion, etc. @@ -39,7 +39,7 @@ Si vous exécutez cet exemple et allez sur http://127.0.0.1:8000/items/4.2. -/// check | "vérifier" +/// check | vérifier Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données. @@ -151,7 +151,7 @@ Créez ensuite des attributs de classe avec des valeurs fixes, qui seront les va /// -/// tip | "Astuce" +/// tip | Astuce Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms de modèles de Machine Learning. @@ -185,7 +185,7 @@ Vous pouvez obtenir la valeur réel d'un membre (une chaîne de caractères ici) {* ../../docs_src/path_params/tutorial005.py hl[20] *} -/// tip | "Astuce" +/// tip | Astuce Vous pouvez aussi accéder la valeur `"lenet"` avec `ModelName.lenet.value`. @@ -238,7 +238,7 @@ Vous pouvez donc l'utilisez comme tel : {* ../../docs_src/path_params/tutorial004.py hl[6] *} -/// tip | "Astuce" +/// tip | Astuce Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash au début (`/`). diff --git a/docs/fr/docs/tutorial/query-params-str-validations.md b/docs/fr/docs/tutorial/query-params-str-validations.md index a3cf76302..c54c0c717 100644 --- a/docs/fr/docs/tutorial/query-params-str-validations.md +++ b/docs/fr/docs/tutorial/query-params-str-validations.md @@ -106,7 +106,7 @@ Disons que vous déclarez le paramètre `q` comme ayant une longueur minimale de {* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} -/// note | "Rappel" +/// note | Rappel Avoir une valeur par défaut rend le paramètre optionnel. @@ -171,7 +171,7 @@ Donc la réponse de cette URL serait : } ``` -/// tip | "Astuce" +/// tip | Astuce Pour déclarer un paramètre de requête de type `list`, comme dans l'exemple ci-dessus, il faut explicitement utiliser `Query`, sinon cela sera interprété comme faisant partie du corps de la requête. diff --git a/docs/fr/docs/tutorial/query-params.md b/docs/fr/docs/tutorial/query-params.md index 798f84fa3..b87c26c78 100644 --- a/docs/fr/docs/tutorial/query-params.md +++ b/docs/fr/docs/tutorial/query-params.md @@ -65,7 +65,7 @@ De la même façon, vous pouvez définir des paramètres de requête comme optio Ici, le paramètre `q` sera optionnel, et aura `None` comme valeur par défaut. -/// check | "Remarque" +/// check | Remarque On peut voir que **FastAPI** est capable de détecter que le paramètre de chemin `item_id` est un paramètre de chemin et que `q` n'en est pas un, c'est donc un paramètre de requête. @@ -187,7 +187,7 @@ Ici, on a donc 3 paramètres de requête : * `skip`, un `int` avec comme valeur par défaut `0`. * `limit`, un `int` optionnel. -/// tip | "Astuce" +/// tip | Astuce Vous pouvez utiliser les `Enum`s de la même façon qu'avec les [Paramètres de chemin](path-params.md#valeurs-predefinies){.internal-link target=_blank}. diff --git a/docs/id/docs/tutorial/index.md b/docs/id/docs/tutorial/index.md index f0dee3d73..c01ec9a89 100644 --- a/docs/id/docs/tutorial/index.md +++ b/docs/id/docs/tutorial/index.md @@ -52,7 +52,7 @@ $ pip install "fastapi[all]" ...yang juga termasuk `uvicorn`, yang dapat kamu gunakan sebagai server yang menjalankan kodemu. -/// note | "Catatan" +/// note | Catatan Kamu juga dapat meng-installnya bagian demi bagian. diff --git a/docs/ja/docs/advanced/additional-status-codes.md b/docs/ja/docs/advanced/additional-status-codes.md index 904d539e7..fb3164328 100644 --- a/docs/ja/docs/advanced/additional-status-codes.md +++ b/docs/ja/docs/advanced/additional-status-codes.md @@ -18,7 +18,7 @@ {!../../docs_src/additional_status_codes/tutorial001.py!} ``` -/// warning | "注意" +/// warning | 注意 上記の例のように `Response` を明示的に返す場合、それは直接返されます。 @@ -28,7 +28,7 @@ /// -/// note | "技術詳細" +/// note | 技術詳細 `from starlette.responses import JSONResponse` を利用することもできます。 diff --git a/docs/ja/docs/advanced/custom-response.md b/docs/ja/docs/advanced/custom-response.md index 88269700e..15edc11ad 100644 --- a/docs/ja/docs/advanced/custom-response.md +++ b/docs/ja/docs/advanced/custom-response.md @@ -12,7 +12,7 @@ そしてもし、`Response` が、`JSONResponse` や `UJSONResponse` の場合のようにJSONメディアタイプ (`application/json`) ならば、データは *path operationデコレータ* に宣言したPydantic `response_model` により自動的に変換 (もしくはフィルタ) されます。 -/// note | "備考" +/// note | 備考 メディアタイプを指定せずにレスポンスクラスを利用すると、FastAPIは何もコンテンツがないことを期待します。そのため、生成されるOpenAPIドキュメントにレスポンスフォーマットが記載されません。 @@ -28,7 +28,7 @@ {!../../docs_src/custom_response/tutorial001b.py!} ``` -/// info | "情報" +/// info | 情報 パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。 @@ -38,7 +38,7 @@ /// -/// tip | "豆知識" +/// tip | 豆知識 `ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。 @@ -55,7 +55,7 @@ {!../../docs_src/custom_response/tutorial002.py!} ``` -/// info | "情報" +/// info | 情報 パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用されます。 @@ -75,13 +75,13 @@ {!../../docs_src/custom_response/tutorial003.py!} ``` -/// warning | "注意" +/// warning | 注意 *path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。 /// -/// info | "情報" +/// info | 情報 もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。 @@ -115,7 +115,7 @@ `Response` を使って他の何かを返せますし、カスタムのサブクラスも作れることを覚えておいてください。 -/// note | "技術詳細" +/// note | 技術詳細 `from starlette.responses import HTMLResponse` も利用できます。 @@ -168,7 +168,7 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含 `ujson`を使った、代替のJSONレスポンスです。 -/// warning | "注意" +/// warning | 注意 `ujson` は、いくつかのエッジケースの取り扱いについて、Pythonにビルトインされた実装よりも作りこまれていません。 @@ -178,7 +178,7 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含 {!../../docs_src/custom_response/tutorial001.py!} ``` -/// tip | "豆知識" +/// tip | 豆知識 `ORJSONResponse` のほうが高速な代替かもしれません。 @@ -210,7 +210,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス {!../../docs_src/custom_response/tutorial008.py!} ``` -/// tip | "豆知識" +/// tip | 豆知識 ここでは `async` や `await` をサポートしていない標準の `open()` を使っているので、通常の `def` でpath operationを宣言していることに注意してください。 @@ -245,7 +245,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス {!../../docs_src/custom_response/tutorial010.py!} ``` -/// tip | "豆知識" +/// tip | 豆知識 前に見たように、 *path operation* の中で `response_class` をオーバーライドできます。 diff --git a/docs/ja/docs/advanced/index.md b/docs/ja/docs/advanced/index.md index da3c2a2bf..22eaf6eb8 100644 --- a/docs/ja/docs/advanced/index.md +++ b/docs/ja/docs/advanced/index.md @@ -6,7 +6,7 @@ 以降のセクションでは、チュートリアルでは説明しきれなかったオプションや設定、および機能について説明します。 -/// tip | "豆知識" +/// tip | 豆知識 以降のセクションは、 **必ずしも"応用編"ではありません**。 diff --git a/docs/ja/docs/advanced/path-operation-advanced-configuration.md b/docs/ja/docs/advanced/path-operation-advanced-configuration.md index 2dab4aec1..99428bcbe 100644 --- a/docs/ja/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/ja/docs/advanced/path-operation-advanced-configuration.md @@ -2,7 +2,7 @@ ## OpenAPI operationId -/// warning | "注意" +/// warning | 注意 あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。 @@ -26,13 +26,13 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP {!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -/// tip | "豆知識" +/// tip | 豆知識 `app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。 /// -/// warning | "注意" +/// warning | 注意 この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。 diff --git a/docs/ja/docs/advanced/response-directly.md b/docs/ja/docs/advanced/response-directly.md index 167d15589..dc66e238c 100644 --- a/docs/ja/docs/advanced/response-directly.md +++ b/docs/ja/docs/advanced/response-directly.md @@ -14,7 +14,7 @@ 実際は、`Response` やそのサブクラスを返すことができます。 -/// tip | "豆知識" +/// tip | 豆知識 `JSONResponse` それ自体は、 `Response` のサブクラスです。 @@ -38,7 +38,7 @@ {!../../docs_src/response_directly/tutorial001.py!} ``` -/// note | "技術詳細" +/// note | 技術詳細 また、`from starlette.responses import JSONResponse` も利用できます。 diff --git a/docs/ja/docs/advanced/websockets.md b/docs/ja/docs/advanced/websockets.md index f7bcb6af3..365ceca9d 100644 --- a/docs/ja/docs/advanced/websockets.md +++ b/docs/ja/docs/advanced/websockets.md @@ -50,7 +50,7 @@ $ pip install websockets {!../../docs_src/websockets/tutorial001.py!} ``` -/// note | "技術詳細" +/// note | 技術詳細 `from starlette.websockets import WebSocket` を使用しても構いません. @@ -119,7 +119,7 @@ WebSocketエンドポイントでは、`fastapi` から以下をインポート {!../../docs_src/websockets/tutorial002.py!} ``` -/// info | "情報" +/// info | 情報 WebSocket で `HTTPException` を発生させることはあまり意味がありません。したがって、WebSocketの接続を直接閉じる方がよいでしょう。 @@ -150,7 +150,7 @@ $ uvicorn main:app --reload * パスで使用される「Item ID」 * クエリパラメータとして使用される「Token」 -/// tip | "豆知識" +/// tip | 豆知識 クエリ `token` は依存パッケージによって処理されることに注意してください。 @@ -180,7 +180,7 @@ WebSocket接続が閉じられると、 `await websocket.receive_text()` は例 Client #1596980209979 left the chat ``` -/// tip | "豆知識" +/// tip | 豆知識 上記のアプリは、複数の WebSocket 接続に対してメッセージを処理し、ブロードキャストする方法を示すための最小限のシンプルな例です。 diff --git a/docs/ja/docs/alternatives.md b/docs/ja/docs/alternatives.md index 343ae4ed8..8129a7002 100644 --- a/docs/ja/docs/alternatives.md +++ b/docs/ja/docs/alternatives.md @@ -30,13 +30,13 @@ Mozilla、Red Hat、Eventbrite など多くの企業で利用されています これは**自動的なAPIドキュメント生成**の最初の例であり、これは**FastAPI**に向けた「調査」を触発した最初のアイデアの一つでした。 -/// note | "備考" +/// note | 備考 Django REST Framework は Tom Christie によって作成されました。StarletteとUvicornの生みの親であり、**FastAPI**のベースとなっています。 /// -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション 自動でAPIドキュメントを生成するWebユーザーインターフェースを持っている点。 @@ -56,7 +56,7 @@ Flask は「マイクロフレームワーク」であり、データベース Flaskのシンプルさを考えると、APIを構築するのに適しているように思えました。次に見つけるべきは、Flask 用の「Django REST Framework」でした。 -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。 @@ -98,7 +98,7 @@ def read_url(): `requests.get(...)` と`@app.get(...)` には類似点が見受けられます。 -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション * シンプルで直感的なAPIを持っている点。 * HTTPメソッド名を直接利用し、単純で直感的である。 @@ -118,7 +118,7 @@ def read_url(): そのため、バージョン2.0では「Swagger」、バージョン3以上では「OpenAPI」と表記するのが一般的です。 -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション 独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。 @@ -147,7 +147,7 @@ APIが必要とするもう一つの大きな機能はデータのバリデー しかし、それはPythonの型ヒントが存在する前に作られたものです。そのため、すべてのスキーマを定義するためには、Marshmallowが提供する特定のユーティリティやクラスを使用する必要があります。 -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。 @@ -163,13 +163,13 @@ WebargsはFlaskをはじめとするいくつかのフレームワークの上 素晴らしいツールで、私も**FastAPI**を持つ前はよく使っていました。 -/// info | "情報" +/// info | 情報 Webargsは、Marshmallowと同じ開発者により作られました。 /// -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション 受信したデータに対する自動的なバリデーションを持っている点。 @@ -193,13 +193,13 @@ Flask, Starlette, Responderなどにおいてはそのように動作します エディタでは、この問題を解決することはできません。また、パラメータやMarshmallowスキーマを変更したときに、YAMLのdocstringを変更するのを忘れてしまうと、生成されたスキーマが古くなってしまいます。 -/// info | "情報" +/// info | 情報 APISpecは、Marshmallowと同じ開発者により作成されました。 /// -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション OpenAPIという、APIについてのオープンな標準をサポートしている点。 @@ -225,13 +225,13 @@ Flask、Flask-apispec、Marshmallow、Webargsの組み合わせは、**FastAPI** そして、これらのフルスタックジェネレーターは、[**FastAPI** Project Generators](project-generation.md){.internal-link target=_blank}の元となっていました。 -/// info | "情報" +/// info | 情報 Flask-apispecはMarshmallowと同じ開発者により作成されました。 /// -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。 @@ -251,7 +251,7 @@ Angular 2にインスピレーションを受けた、統合された依存性 入れ子になったモデルをうまく扱えません。そのため、リクエストのJSONボディが内部フィールドを持つJSONオブジェクトで、それが順番にネストされたJSONオブジェクトになっている場合、適切にドキュメント化やバリデーションをすることができません。 -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション 素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。 @@ -263,7 +263,7 @@ Angular 2にインスピレーションを受けた、統合された依存性 `asyncio`に基づいた、Pythonのフレームワークの中でも非常に高速なものの一つです。Flaskと非常に似た作りになっています。 -/// note | "技術詳細" +/// note | 技術詳細 Pythonの`asyncio`ループの代わりに、`uvloop`が利用されています。それにより、非常に高速です。 @@ -271,7 +271,7 @@ Pythonの`asyncio`ループの代わりに、`uvloop`が利用されています /// -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション 物凄い性能を出す方法を見つけた点。 @@ -289,7 +289,7 @@ Pythonのウェブフレームワーク標準規格 (WSGI) を使用していま そのため、データのバリデーション、シリアライゼーション、ドキュメント化は、自動的にできずコードの中で行わなければなりません。あるいは、HugのようにFalconの上にフレームワークとして実装されなければなりません。このような分断は、パラメータとして1つのリクエストオブジェクトと1つのレスポンスオブジェクトを持つというFalconのデザインにインスピレーションを受けた他のフレームワークでも起こります。 -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション 素晴らしい性能を得るための方法を見つけた点。 @@ -315,7 +315,7 @@ Pydanticのようなデータのバリデーション、シリアライゼーシ ルーティングは一つの場所で宣言され、他の場所で宣言された関数を使用します (エンドポイントを扱う関数のすぐ上に配置できるデコレータを使用するのではなく) 。これはFlask (やStarlette) よりも、Djangoに近いです。これは、比較的緊密に結合されているものをコードの中で分離しています。 -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。 @@ -337,13 +337,13 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ 以前のPythonの同期型Webフレームワーク標準 (WSGI) をベースにしているため、Websocketなどは扱えませんが、それでも高性能です。 -/// info | "情報" +/// info | 情報 HugはTimothy Crosleyにより作成されました。彼は`isort`など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。 /// -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。 @@ -377,7 +377,7 @@ Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数 今ではAPIStarはOpenAPI仕様を検証するためのツールセットであり、ウェブフレームワークではありません。 -/// info | "情報" +/// info | 情報 APIStarはTom Christieにより開発されました。以下の開発者でもあります: @@ -387,7 +387,7 @@ APIStarはTom Christieにより開発されました。以下の開発者でも /// -/// check | "**FastAPI**へ与えたインスピレーション" +/// check | **FastAPI**へ与えたインスピレーション 存在そのもの。 @@ -411,7 +411,7 @@ Pydanticは、Pythonの型ヒントを元にデータのバリデーション、 Marshmallowに匹敵しますが、ベンチマークではMarshmallowよりも高速です。また、Pythonの型ヒントを元にしているので、エディタの補助が素晴らしいです。 -/// check | "**FastAPI**での使用用途" +/// check | **FastAPI**での使用用途 データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。 @@ -447,7 +447,7 @@ Starletteは基本的なWebマイクロフレームワークの機能をすべ これは **FastAPI** が追加する主な機能の一つで、すべての機能は Pythonの型ヒントに基づいています (Pydanticを使用しています) 。これに加えて、依存性注入の仕組み、セキュリティユーティリティ、OpenAPIスキーマ生成などがあります。 -/// note | "技術詳細" +/// note | 技術詳細 ASGIはDjangoのコアチームメンバーにより開発された新しい「標準」です。まだ「Pythonの標準 (PEP) 」ではありませんが、現在そうなるように進めています。 @@ -455,7 +455,7 @@ ASGIはDjangoのコアチームメンバーにより開発された新しい「 /// -/// check | "**FastAPI**での使用用途" +/// check | **FastAPI**での使用用途 webに関するコアな部分を全て扱います。その上に機能を追加します。 @@ -473,7 +473,7 @@ Uvicornは非常に高速なASGIサーバーで、uvloopとhttptoolsにより構 Starletteや**FastAPI**のサーバーとして推奨されています。 -/// check | "**FastAPI**が推奨する理由" +/// check | **FastAPI**が推奨する理由 **FastAPI**アプリケーションを実行するメインのウェブサーバーである点。 diff --git a/docs/ja/docs/async.md b/docs/ja/docs/async.md index ce9dac56f..d1da1f82d 100644 --- a/docs/ja/docs/async.md +++ b/docs/ja/docs/async.md @@ -21,7 +21,7 @@ async def read_results(): return results ``` -/// note | "備考" +/// note | 備考 `async def` を使用して作成された関数の内部でしか `await` は使用できません。 @@ -358,7 +358,7 @@ async def read_burgers(): ## 非常に発展的な技術的詳細 -/// warning | "注意" +/// warning | 注意 恐らくスキップしても良いでしょう。 diff --git a/docs/ja/docs/contributing.md b/docs/ja/docs/contributing.md index 86926b213..3ee742ec2 100644 --- a/docs/ja/docs/contributing.md +++ b/docs/ja/docs/contributing.md @@ -95,7 +95,7 @@ some/directory/fastapi/env/bin/pip `env/bin/pip`に`pip`バイナリが表示される場合は、正常に機能しています。🎉 -/// tip | "豆知識" +/// tip | 豆知識 この環境で`pip`を使って新しいパッケージをインストールするたびに、仮想環境を再度有効化します。 @@ -165,7 +165,7 @@ $ bash scripts/format-imports.sh そして、翻訳を処理するためのツール/スクリプトが、`./scripts/docs.py`に用意されています。 -/// tip | "豆知識" +/// tip | 豆知識 `./scripts/docs.py`のコードを見る必要はなく、コマンドラインからただ使うだけです。 @@ -254,7 +254,7 @@ Uvicornはデフォルトでポート`8000`を使用するため、ポート`800 * あなたの言語の今あるプルリクエストを確認し、変更や承認をするレビューを追加します。 -/// tip | "豆知識" +/// tip | 豆知識 すでにあるプルリクエストに修正提案つきのコメントを追加できます。 @@ -282,7 +282,7 @@ Uvicornはデフォルトでポート`8000`を使用するため、ポート`800 スペイン語の場合、2文字のコードは`es`です。したがって、スペイン語のディレクトリは`docs/es/`です。 -/// tip | "豆知識" +/// tip | 豆知識 メイン (「公式」) 言語は英語で、`docs/en/`にあります。 @@ -323,7 +323,7 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -/// tip | "豆知識" +/// tip | 豆知識 パスとファイル名の変更は、`en`から`es`への言語コードだけであることに注意してください。 @@ -398,7 +398,7 @@ Updating en これで、新しく作成された`docs/ht/`ディレクトリをコードエディターから確認できます。 -/// tip | "豆知識" +/// tip | 豆知識 翻訳を追加する前に、これだけで最初のプルリクエストを作成し、新しい言語の設定をセットアップします。 diff --git a/docs/ja/docs/deployment/manually.md b/docs/ja/docs/deployment/manually.md index c17e63728..4ea6bd8ff 100644 --- a/docs/ja/docs/deployment/manually.md +++ b/docs/ja/docs/deployment/manually.md @@ -20,7 +20,7 @@ $ pip install "uvicorn[standard]" //// -/// tip | "豆知識" +/// tip | 豆知識 `standard` を加えることで、Uvicornがインストールされ、いくつかの推奨される依存関係を利用するようになります。 diff --git a/docs/ja/docs/deployment/versions.md b/docs/ja/docs/deployment/versions.md index 941ddb71b..7575fc4f7 100644 --- a/docs/ja/docs/deployment/versions.md +++ b/docs/ja/docs/deployment/versions.md @@ -42,7 +42,7 @@ PoetryやPipenvなど、他のインストール管理ツールを使用して FastAPIでは「パッチ」バージョンはバグ修正と非破壊的な変更に留めるという規約に従っています。 -/// tip | "豆知識" +/// tip | 豆知識 「パッチ」は最後の数字を指します。例えば、`0.2.3` ではパッチバージョンは `3` です。 @@ -56,7 +56,7 @@ fastapi>=0.45.0,<0.46.0 破壊的な変更と新機能実装は「マイナー」バージョンで加えられます。 -/// tip | "豆知識" +/// tip | 豆知識 「マイナー」は真ん中の数字です。例えば、`0.2.3` ではマイナーバージョンは `2` です。 diff --git a/docs/ja/docs/features.md b/docs/ja/docs/features.md index 73c0192c7..4024590cf 100644 --- a/docs/ja/docs/features.md +++ b/docs/ja/docs/features.md @@ -62,7 +62,7 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -/// info | "情報" +/// info | 情報 `**second_user_data` は以下を意味します: diff --git a/docs/ja/docs/python-types.md b/docs/ja/docs/python-types.md index 7af6ce0c0..77ddf4654 100644 --- a/docs/ja/docs/python-types.md +++ b/docs/ja/docs/python-types.md @@ -12,7 +12,7 @@ しかしたとえまったく **FastAPI** を使用しない場合でも、それらについて少し学ぶことで利点を得ることができるでしょう。 -/// note | "備考" +/// note | 備考 もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。 @@ -175,7 +175,7 @@ John Doe {!../../docs_src/python_types/tutorial006.py!} ``` -/// tip | "豆知識" +/// tip | 豆知識 角括弧内の内部の型は「型パラメータ」と呼ばれています。 @@ -288,7 +288,7 @@ Pydanticの公式ドキュメントから引用: {!../../docs_src/python_types/tutorial011.py!} ``` -/// info | "情報" +/// info | 情報 Pydanticについてより学びたい方はドキュメントを参照してください. @@ -320,7 +320,7 @@ Pydanticについてより学びたい方は`mypy`のチートシートを参照してください diff --git a/docs/ja/docs/tutorial/body-fields.md b/docs/ja/docs/tutorial/body-fields.md index 1d386040a..5b3b3622b 100644 --- a/docs/ja/docs/tutorial/body-fields.md +++ b/docs/ja/docs/tutorial/body-fields.md @@ -10,7 +10,7 @@ {!../../docs_src/body_fields/tutorial001.py!} ``` -/// warning | "注意" +/// warning | 注意 `Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。 @@ -26,7 +26,7 @@ `Field`は`Query`や`Path`、`Body`と同じように動作し、全く同様のパラメータなどを持ちます。 -/// note | "技術詳細" +/// note | 技術詳細 実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。 @@ -38,7 +38,7 @@ /// -/// tip | "豆知識" +/// tip | 豆知識 型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。 diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md index 647143ee5..982c23565 100644 --- a/docs/ja/docs/tutorial/body-multiple-params.md +++ b/docs/ja/docs/tutorial/body-multiple-params.md @@ -12,7 +12,7 @@ {!../../docs_src/body_multiple_params/tutorial001.py!} ``` -/// note | "備考" +/// note | 備考 この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。 @@ -56,7 +56,7 @@ } ``` -/// note | "備考" +/// note | 備考 以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。 @@ -118,7 +118,7 @@ q: str = None {!../../docs_src/body_multiple_params/tutorial004.py!} ``` -/// info | "情報" +/// info | 情報 `Body`もまた、後述する `Query` や `Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。 diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md index 8703a40e7..dc2d5e81a 100644 --- a/docs/ja/docs/tutorial/body-nested-models.md +++ b/docs/ja/docs/tutorial/body-nested-models.md @@ -162,7 +162,7 @@ Pydanticモデルを`list`や`set`などのサブタイプとして使用する } ``` -/// info | "情報" +/// info | 情報 `images`キーが画像オブジェクトのリストを持つようになったことに注目してください。 @@ -176,7 +176,7 @@ Pydanticモデルを`list`や`set`などのサブタイプとして使用する {!../../docs_src/body_nested_models/tutorial007.py!} ``` -/// info | "情報" +/// info | 情報 `Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。 @@ -228,7 +228,7 @@ Pydanticモデルではなく、`dict`を直接使用している場合はこの {!../../docs_src/body_nested_models/tutorial009.py!} ``` -/// tip | "豆知識" +/// tip | 豆知識 JSONはキーとして`str`しかサポートしていないことに注意してください。 diff --git a/docs/ja/docs/tutorial/body-updates.md b/docs/ja/docs/tutorial/body-updates.md index fde9f4f5e..fcaeb0d16 100644 --- a/docs/ja/docs/tutorial/body-updates.md +++ b/docs/ja/docs/tutorial/body-updates.md @@ -34,7 +34,7 @@ つまり、更新したいデータだけを送信して、残りはそのままにしておくことができます。 -/// note | "備考" +/// note | 備考 `PATCH`は`PUT`よりもあまり使われておらず、知られていません。 @@ -89,7 +89,7 @@ {!../../docs_src/body_updates/tutorial002.py!} ``` -/// tip | "豆知識" +/// tip | 豆知識 実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。 @@ -97,7 +97,7 @@ /// -/// note | "備考" +/// note | 備考 入力モデルがまだ検証されていることに注目してください。 diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md index 888d4388a..277ee79c8 100644 --- a/docs/ja/docs/tutorial/body.md +++ b/docs/ja/docs/tutorial/body.md @@ -8,7 +8,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ **リクエスト** ボディを宣言するために Pydantic モデルを使用します。そして、その全てのパワーとメリットを利用します。 -/// info | "情報" +/// info | 情報 データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。 @@ -113,7 +113,7 @@ GET リクエストでボディを送信することは、仕様では未定義 -/// tip | "豆知識" +/// tip | 豆知識 PyCharmエディタを使用している場合は、Pydantic PyCharm Pluginが使用可能です。 @@ -161,7 +161,7 @@ GET リクエストでボディを送信することは、仕様では未定義 * パラメータが**単数型** (`int`、`float`、`str`、`bool` など)の場合は**クエリ**パラメータとして解釈されます。 * パラメータが **Pydantic モデル**型で宣言された場合、リクエスト**ボディ**として解釈されます。 -/// note | "備考" +/// note | 備考 FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。 diff --git a/docs/ja/docs/tutorial/cookie-params.md b/docs/ja/docs/tutorial/cookie-params.md index 1f45db17c..7f029b483 100644 --- a/docs/ja/docs/tutorial/cookie-params.md +++ b/docs/ja/docs/tutorial/cookie-params.md @@ -20,7 +20,7 @@ {!../../docs_src/cookie_params/tutorial001.py!} ``` -/// note | "技術詳細" +/// note | 技術詳細 `Cookie`は`Path`と`Query`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。 @@ -28,7 +28,7 @@ /// -/// info | "情報" +/// info | 情報 クッキーを宣言するには、`Cookie`を使う必要があります。なぜなら、そうしないとパラメータがクエリのパラメータとして解釈されてしまうからです。 diff --git a/docs/ja/docs/tutorial/cors.md b/docs/ja/docs/tutorial/cors.md index 9530c51bf..9834a460b 100644 --- a/docs/ja/docs/tutorial/cors.md +++ b/docs/ja/docs/tutorial/cors.md @@ -78,7 +78,7 @@ CORSについてより詳しい情報は、Mozilla CORS documentation を参照して下さい。 -/// note | "技術詳細" +/// note | 技術詳細 `from starlette.middleware.cors import CORSMiddleware` も使用できます。 diff --git a/docs/ja/docs/tutorial/debugging.md b/docs/ja/docs/tutorial/debugging.md index be0ff81d4..7413332a8 100644 --- a/docs/ja/docs/tutorial/debugging.md +++ b/docs/ja/docs/tutorial/debugging.md @@ -74,7 +74,7 @@ from myapp import app は実行されません。 -/// info | "情報" +/// info | 情報 より詳しい情報は、公式Pythonドキュメントを参照してください。 diff --git a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md index fb23a7b2b..55885a61f 100644 --- a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md @@ -185,7 +185,7 @@ commons: CommonQueryParams = Depends() ...そして **FastAPI** は何をすべきか知っています。 -/// tip | "豆知識" +/// tip | 豆知識 役に立つというよりも、混乱するようであれば無視してください。それをする*必要*はありません。 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 59f21c3df..3b78f4e0b 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -20,7 +20,7 @@ これらの依存関係は、通常の依存関係と同様に実行・解決されます。しかし、それらの値(何かを返す場合)は*path operation関数*には渡されません。 -/// tip | "豆知識" +/// tip | 豆知識 エディタによっては、未使用の関数パラメータをチェックしてエラーとして表示するものもあります。 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md index 7ef1caf0d..bd4e689bf 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,13 +4,13 @@ FastAPIは、いくつかのしてカスタムの独自ヘッダーを追加できます。 @@ -43,7 +43,7 @@ /// -/// note | "技術詳細" +/// note | 技術詳細 `from starlette.requests import Request` を使用することもできます。 diff --git a/docs/ja/docs/tutorial/path-operation-configuration.md b/docs/ja/docs/tutorial/path-operation-configuration.md index 7eceb377d..36223d35d 100644 --- a/docs/ja/docs/tutorial/path-operation-configuration.md +++ b/docs/ja/docs/tutorial/path-operation-configuration.md @@ -2,7 +2,7 @@ *path operationデコレータ*を設定するためのパラメータがいくつかあります。 -/// warning | "注意" +/// warning | 注意 これらのパラメータは*path operation関数*ではなく、*path operationデコレータ*に直接渡されることに注意してください。 @@ -22,7 +22,7 @@ そのステータスコードはレスポンスで使用され、OpenAPIスキーマに追加されます。 -/// note | "技術詳細" +/// note | 技術詳細 また、`from starlette import status`を使用することもできます。 @@ -72,13 +72,13 @@ docstringにhttp://127.0.0.1:8000/items/4.2 で見られるように、intのかわりに `float` が与えられた場合にも同様なエラーが表示されます。 -/// check | "確認" +/// check | 確認 したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。 @@ -85,7 +85,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー -/// check | "確認" +/// check | 確認 繰り返しになりますが、Python型宣言を使用するだけで、**FastAPI**は対話的なAPIドキュメントを自動的に生成します(Swagger UIを統合)。 @@ -143,13 +143,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー {!../../docs_src/path_params/tutorial005.py!} ``` -/// info | "情報" +/// info | 情報 Enumerations (もしくは、enums)はPython 3.4以降で利用できます。 /// -/// tip | "豆知識" +/// tip | 豆知識 "AlexNet"、"ResNet"そして"LeNet"は機械学習モデルの名前です。 @@ -189,7 +189,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー {!../../docs_src/path_params/tutorial005.py!} ``` -/// tip | "豆知識" +/// tip | 豆知識 `ModelName.lenet.value` でも `"lenet"` 値にアクセスできます。 @@ -246,7 +246,7 @@ Starletteのオプションを直接使用することで、以下のURLの様 {!../../docs_src/path_params/tutorial004.py!} ``` -/// tip | "豆知識" +/// tip | 豆知識 最初のスラッシュ (`/`)が付いている `/home/johndoe/myfile.txt` をパラメータが含んでいる必要があります。 diff --git a/docs/ja/docs/tutorial/query-params-str-validations.md b/docs/ja/docs/tutorial/query-params-str-validations.md index 9e54a6f55..6450c91c4 100644 --- a/docs/ja/docs/tutorial/query-params-str-validations.md +++ b/docs/ja/docs/tutorial/query-params-str-validations.md @@ -10,7 +10,7 @@ クエリパラメータ `q` は `Optional[str]` 型で、`None` を許容する `str` 型を意味しており、デフォルトは `None` です。そのため、FastAPIはそれが必須ではないと理解します。 -/// note | "備考" +/// note | 備考 FastAPIは、 `q` はデフォルト値が `=None` であるため、必須ではないと理解します。 @@ -54,7 +54,7 @@ q: Optional[str] = None しかし、これはクエリパラメータとして明示的に宣言しています。 -/// info | "情報" +/// info | 情報 FastAPIは以下の部分を気にすることを覚えておいてください: @@ -118,7 +118,7 @@ q: Union[str, None] = Query(default=None, max_length=50) {!../../docs_src/query_params_str_validations/tutorial005.py!} ``` -/// note | "備考" +/// note | 備考 デフォルト値を指定すると、パラメータは任意になります。 @@ -150,7 +150,7 @@ q: Union[str, None] = Query(default=None, min_length=3) {!../../docs_src/query_params_str_validations/tutorial006.py!} ``` -/// info | "情報" +/// info | 情報 これまで`...`を見たことがない方へ: これは特殊な単一値です。Pythonの一部であり、"Ellipsis"と呼ばれています。 @@ -187,7 +187,7 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -/// tip | "豆知識" +/// tip | 豆知識 上述の例のように、`list`型のクエリパラメータを宣言するには明示的に`Query`を使用する必要があります。そうしない場合、リクエストボディと解釈されます。 @@ -230,7 +230,7 @@ http://localhost:8000/items/ {!../../docs_src/query_params_str_validations/tutorial013.py!} ``` -/// note | "備考" +/// note | 備考 この場合、FastAPIはリストの内容をチェックしないことを覚えておいてください。 @@ -244,7 +244,7 @@ http://localhost:8000/items/ その情報は、生成されたOpenAPIに含まれ、ドキュメントのユーザーインターフェースや外部のツールで使用されます。 -/// note | "備考" +/// note | 備考 ツールによってOpenAPIのサポートのレベルが異なる可能性があることを覚えておいてください。 diff --git a/docs/ja/docs/tutorial/query-params.md b/docs/ja/docs/tutorial/query-params.md index 6d41d3742..71f78eca5 100644 --- a/docs/ja/docs/tutorial/query-params.md +++ b/docs/ja/docs/tutorial/query-params.md @@ -69,7 +69,7 @@ http://127.0.0.1:8000/items/?skip=20 この場合、関数パラメータ `q` はオプショナルとなり、デフォルトでは `None` になります。 -/// check | "確認" +/// check | 確認 パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。 @@ -191,7 +191,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`、デフォルト値を `0` とする `int` 。 * `limit`、オプショナルな `int` 。 -/// tip | "豆知識" +/// tip | 豆知識 [パスパラメータ](path-params.md#_8){.internal-link target=_blank}と同様に `Enum` を使用できます。 diff --git a/docs/ja/docs/tutorial/request-forms-and-files.md b/docs/ja/docs/tutorial/request-forms-and-files.md index e03b9166d..1e4237b20 100644 --- a/docs/ja/docs/tutorial/request-forms-and-files.md +++ b/docs/ja/docs/tutorial/request-forms-and-files.md @@ -2,7 +2,7 @@ `File`と`Form`を同時に使うことでファイルとフォームフィールドを定義することができます。 -/// info | "情報" +/// info | 情報 アップロードされたファイルやフォームデータを受信するには、まず`python-multipart`をインストールします。 @@ -28,7 +28,7 @@ また、いくつかのファイルを`bytes`として、いくつかのファイルを`UploadFile`として宣言することができます。 -/// warning | "注意" +/// warning | 注意 *path operation*で複数の`File`と`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストのボディは`application/json`の代わりに`multipart/form-data`を使ってエンコードされているからです。 diff --git a/docs/ja/docs/tutorial/request-forms.md b/docs/ja/docs/tutorial/request-forms.md index eb453c04a..f130c067f 100644 --- a/docs/ja/docs/tutorial/request-forms.md +++ b/docs/ja/docs/tutorial/request-forms.md @@ -2,7 +2,7 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用します。 -/// info | "情報" +/// info | 情報 フォームを使うためには、まず`python-multipart`をインストールします。 @@ -32,13 +32,13 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用し `Form`では`Body`(および`Query`や`Path`、`Cookie`)と同じメタデータとバリデーションを宣言することができます。 -/// info | "情報" +/// info | 情報 `Form`は`Body`を直接継承するクラスです。 /// -/// tip | "豆知識" +/// tip | 豆知識 フォームのボディを宣言するには、明示的に`Form`を使用する必要があります。なぜなら、これを使わないと、パラメータはクエリパラメータやボディ(JSON)パラメータとして解釈されるからです。 @@ -50,7 +50,7 @@ HTMLフォーム(`
`)がサーバにデータを送信する方 **FastAPI** は、JSONの代わりにそのデータを適切な場所から読み込むようにします。 -/// note | "技術詳細" +/// note | 技術詳細 フォームからのデータは通常、`application/x-www-form-urlencoded`の「media type」を使用してエンコードされます。 @@ -60,7 +60,7 @@ HTMLフォーム(`
`)がサーバにデータを送信する方 /// -/// warning | "注意" +/// warning | 注意 *path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。 diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md index 973f893de..97821f125 100644 --- a/docs/ja/docs/tutorial/response-model.md +++ b/docs/ja/docs/tutorial/response-model.md @@ -12,7 +12,7 @@ {!../../docs_src/response_model/tutorial001.py!} ``` -/// note | "備考" +/// note | 備考 `response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。 @@ -31,7 +31,7 @@ FastAPIは`response_model`を使って以下のことをします: * 出力データをモデルのデータに限定します。これがどのように重要なのか以下で見ていきましょう。 -/// note | "技術詳細" +/// note | 技術詳細 レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。 @@ -57,7 +57,7 @@ FastAPIは`response_model`を使って以下のことをします: しかし、同じモデルを別の*path operation*に使用すると、すべてのクライアントにユーザーのパスワードを送信してしまうことになります。 -/// danger | "危険" +/// danger | 危険 ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。 @@ -130,13 +130,13 @@ FastAPIは`response_model`を使って以下のことをします: } ``` -/// info | "情報" +/// info | 情報 FastAPIはこれをするために、Pydanticモデルの`.dict()`をその`exclude_unset`パラメータで使用しています。 /// -/// info | "情報" +/// info | 情報 以下も使用することができます: @@ -180,7 +180,7 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d そのため、それらはJSONレスポンスに含まれることになります。 -/// tip | "豆知識" +/// tip | 豆知識 デフォルト値は`None`だけでなく、なんでも良いことに注意してください。 例えば、リスト(`[]`)や`10.5`の`float`などです。 @@ -195,7 +195,7 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d これは、Pydanticモデルが1つしかなく、出力からいくつかのデータを削除したい場合のクイックショートカットとして使用することができます。 -/// tip | "豆知識" +/// tip | 豆知識 それでも、これらのパラメータではなく、複数のクラスを使用して、上記のようなアイデアを使うことをおすすめします。 @@ -209,7 +209,7 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d {!../../docs_src/response_model/tutorial005.py!} ``` -/// tip | "豆知識" +/// tip | 豆知識 `{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。 diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md index 90b290887..56bcdaf6c 100644 --- a/docs/ja/docs/tutorial/response-status-code.md +++ b/docs/ja/docs/tutorial/response-status-code.md @@ -12,7 +12,7 @@ {!../../docs_src/response_status_code/tutorial001.py!} ``` -/// note | "備考" +/// note | 備考 `status_code`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数*のものではありません。 @@ -20,7 +20,7 @@ `status_code`パラメータはHTTPステータスコードを含む数値を受け取ります。 -/// info | "情報" +/// info | 情報 `status_code`は代わりに、Pythonの`http.HTTPStatus`のように、`IntEnum`を受け取ることもできます。 @@ -33,7 +33,7 @@ -/// note | "備考" +/// note | 備考 いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。 @@ -43,7 +43,7 @@ FastAPIはこれを知っていて、レスポンスボディがないというO ## HTTPステータスコードについて -/// note | "備考" +/// note | 備考 すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。 @@ -66,7 +66,7 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス * クライアントからの一般的なエラーについては、`400`を使用することができます。 * `500`以上はサーバーエラーのためのものです。これらを直接使うことはほとんどありません。アプリケーションコードやサーバーのどこかで何か問題が発生した場合、これらのステータスコードのいずれかが自動的に返されます。 -/// tip | "豆知識" +/// tip | 豆知識 それぞれのステータスコードとどのコードが何のためのコードなのかについて詳細はMDN HTTP レスポンスステータスコードについてのドキュメントを参照してください。 @@ -94,7 +94,7 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス -/// note | "技術詳細" +/// note | 技術詳細 また、`from starlette import status`を使うこともできます。 diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md index baf1bbedd..44dfad737 100644 --- a/docs/ja/docs/tutorial/schema-extra-example.md +++ b/docs/ja/docs/tutorial/schema-extra-example.md @@ -24,7 +24,7 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 {!../../docs_src/schema_extra_example/tutorial002.py!} ``` -/// warning | "注意" +/// warning | 注意 これらの追加引数が渡されても、文書化のためのバリデーションは追加されず、注釈だけが追加されることを覚えておいてください。 diff --git a/docs/ja/docs/tutorial/security/first-steps.md b/docs/ja/docs/tutorial/security/first-steps.md index 51f7bf829..6ace1b542 100644 --- a/docs/ja/docs/tutorial/security/first-steps.md +++ b/docs/ja/docs/tutorial/security/first-steps.md @@ -26,7 +26,7 @@ ## 実行 -/// info | "情報" +/// info | 情報 まず`python-multipart`をインストールします。 @@ -56,7 +56,7 @@ $ uvicorn main:app --reload -/// check | "Authorizeボタン!" +/// check | Authorizeボタン! すでにピカピカの新しい「Authorize」ボタンがあります。 @@ -68,7 +68,7 @@ $ uvicorn main:app --reload -/// note | "備考" +/// note | 備考 フォームに何を入力しても、まだうまくいきません。ですが、これから動くようになります。 @@ -114,7 +114,7 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー この例では、**Bearer**トークンを使用して**OAuth2**を**パスワード**フローで使用します。これには`OAuth2PasswordBearer`クラスを使用します。 -/// info | "情報" +/// info | 情報 「bearer」トークンが、唯一の選択肢ではありません。 @@ -132,7 +132,7 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー {!../../docs_src/security/tutorial001.py!} ``` -/// tip | "豆知識" +/// tip | 豆知識 ここで、`tokenUrl="token"`は、まだ作成していない相対URL`token`を指します。相対URLなので、`./token`と同じです。 @@ -146,7 +146,7 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー 実際のpath operationもすぐに作ります。 -/// info | "情報" +/// info | 情報 非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`token_url`ではなく`tokenUrl`であることを気に入らないかもしれません。 @@ -176,7 +176,7 @@ oauth2_scheme(some, parameters) **FastAPI**は、この依存関係を使用してOpenAPIスキーマ (および自動APIドキュメント) で「セキュリティスキーム」を定義できることを知っています。 -/// info | "技術詳細" +/// info | 技術詳細 **FastAPI**は、`OAuth2PasswordBearer` クラス (依存関係で宣言されている) を使用してOpenAPIのセキュリティスキームを定義できることを知っています。これは`fastapi.security.oauth2.OAuth2`、`fastapi.security.base.SecurityBase`を継承しているからです。 diff --git a/docs/ja/docs/tutorial/security/get-current-user.md b/docs/ja/docs/tutorial/security/get-current-user.md index 0edbd983f..898bbd797 100644 --- a/docs/ja/docs/tutorial/security/get-current-user.md +++ b/docs/ja/docs/tutorial/security/get-current-user.md @@ -54,7 +54,7 @@ Pydanticモデルの `User` として、 `current_user` の型を宣言するこ その関数の中ですべての入力補完や型チェックを行う際に役に立ちます。 -/// tip | "豆知識" +/// tip | 豆知識 リクエストボディはPydanticモデルでも宣言できることを覚えているかもしれません。 @@ -62,7 +62,7 @@ Pydanticモデルの `User` として、 `current_user` の型を宣言するこ /// -/// check | "確認" +/// check | 確認 依存関係システムがこのように設計されているおかげで、 `User` モデルを返却する別の依存関係(別の"dependables")を持つことができます。 diff --git a/docs/ja/docs/tutorial/security/index.md b/docs/ja/docs/tutorial/security/index.md index c68e7e7f2..37b8bb958 100644 --- a/docs/ja/docs/tutorial/security/index.md +++ b/docs/ja/docs/tutorial/security/index.md @@ -32,7 +32,7 @@ OAuth 1というものもありましたが、これはOAuth2とは全く異な OAuth2は、通信を暗号化する方法を指定せず、アプリケーションがHTTPSで提供されることを想定しています。 -/// tip | "豆知識" +/// tip | 豆知識 **デプロイ**のセクションでは、TraefikとLet's Encryptを使用して、無料でHTTPSを設定する方法が紹介されています。 @@ -89,7 +89,7 @@ OpenAPIでは、以下のセキュリティスキームを定義しています: * この自動検出メカニズムは、OpenID Connectの仕様で定義されているものです。 -/// tip | "豆知識" +/// tip | 豆知識 Google、Facebook、Twitter、GitHubなど、他の認証/認可プロバイダを統合することも可能で、比較的簡単です。 diff --git a/docs/ja/docs/tutorial/security/oauth2-jwt.md b/docs/ja/docs/tutorial/security/oauth2-jwt.md index b2f511610..825a1b2b3 100644 --- a/docs/ja/docs/tutorial/security/oauth2-jwt.md +++ b/docs/ja/docs/tutorial/security/oauth2-jwt.md @@ -44,7 +44,7 @@ $ pip install python-jose[cryptography] ここでは、推奨されているものを使用します:pyca/cryptography。 -/// tip | "豆知識" +/// tip | 豆知識 このチュートリアルでは以前、PyJWTを使用していました。 @@ -86,7 +86,7 @@ $ pip install passlib[bcrypt] -/// tip | "豆知識" +/// tip | 豆知識 `passlib`を使用すると、**Django**や**Flask**のセキュリティプラグインなどで作成されたパスワードを読み取れるように設定できます。 @@ -102,7 +102,7 @@ $ pip install passlib[bcrypt] PassLib の「context」を作成します。これは、パスワードのハッシュ化と検証に使用されるものです。 -/// tip | "豆知識" +/// tip | 豆知識 PassLibのcontextには、検証だけが許された非推奨の古いハッシュアルゴリズムを含む、様々なハッシュアルゴリズムを使用した検証機能もあります。 @@ -122,7 +122,7 @@ PassLibのcontextには、検証だけが許された非推奨の古いハッシ {!../../docs_src/security/tutorial004.py!} ``` -/// note | "備考" +/// note | 備考 新しい(偽の)データベース`fake_users_db`を確認すると、ハッシュ化されたパスワードが次のようになっていることがわかります:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"` @@ -219,7 +219,7 @@ IDの衝突を回避するために、ユーザーのJWTトークンを作成す Username: `johndoe` Password: `secret` -/// check | "確認" +/// check | 確認 コードのどこにも平文のパスワード"`secret`"はなく、ハッシュ化されたものしかないことを確認してください。 @@ -244,7 +244,7 @@ Password: `secret` -/// note | "備考" +/// note | 備考 ヘッダーの`Authorization`には、`Bearer`で始まる値があります。 diff --git a/docs/ja/docs/tutorial/static-files.md b/docs/ja/docs/tutorial/static-files.md index e6002a1fb..37ea22dd7 100644 --- a/docs/ja/docs/tutorial/static-files.md +++ b/docs/ja/docs/tutorial/static-files.md @@ -11,7 +11,7 @@ {!../../docs_src/static_files/tutorial001.py!} ``` -/// note | "技術詳細" +/// note | 技術詳細 `from starlette.staticfiles import StaticFiles` も使用できます。 diff --git a/docs/ja/docs/tutorial/testing.md b/docs/ja/docs/tutorial/testing.md index 6c5e712e8..b7e80cb8d 100644 --- a/docs/ja/docs/tutorial/testing.md +++ b/docs/ja/docs/tutorial/testing.md @@ -22,7 +22,7 @@ {!../../docs_src/app_testing/tutorial001.py!} ``` -/// tip | "豆知識" +/// tip | 豆知識 テスト関数は `async def` ではなく、通常の `def` であることに注意してください。 @@ -32,7 +32,7 @@ /// -/// note | "技術詳細" +/// note | 技術詳細 `from starlette.testclient import TestClient` も使用できます。 @@ -40,7 +40,7 @@ /// -/// tip | "豆知識" +/// tip | 豆知識 FastAPIアプリケーションへのリクエストの送信とは別に、テストで `async` 関数 (非同期データベース関数など) を呼び出したい場合は、高度なチュートリアルの[Async Tests](../advanced/async-tests.md){.internal-link target=_blank} を参照してください。 @@ -121,7 +121,7 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ (`httpx` または `TestClient` を使用して) バックエンドにデータを渡す方法の詳細は、HTTPXのドキュメントを確認してください。 -/// info | "情報" +/// info | 情報 `TestClient` は、Pydanticモデルではなく、JSONに変換できるデータを受け取ることに注意してください。 diff --git a/docs/ko/docs/advanced/events.md b/docs/ko/docs/advanced/events.md index 94867c198..273c9a479 100644 --- a/docs/ko/docs/advanced/events.md +++ b/docs/ko/docs/advanced/events.md @@ -4,7 +4,7 @@ 이 함수들은 `async def` 또는 평범하게 `def`으로 선언할 수 있습니다. -/// warning | "경고" +/// warning | 경고 이벤트 핸들러는 주 응용 프로그램에서만 작동합니다. [하위 응용 프로그램 - 마운트](./sub-applications.md){.internal-link target=_blank}에서는 작동하지 않습니다. @@ -34,13 +34,13 @@ 이 예제에서 `shutdown` 이벤트 핸들러 함수는 `"Application shutdown"`이라는 텍스트가 적힌 `log.txt` 파일을 추가할 것입니다. -/// info | "정보" +/// info | 정보 `open()` 함수에서 `mode="a"`는 "추가"를 의미합니다. 따라서 이미 존재하는 파일의 내용을 덮어쓰지 않고 새로운 줄을 추가합니다. /// -/// tip | "팁" +/// tip | 팁 이 예제에서는 파일과 상호작용 하기 위해 파이썬 표준 함수인 `open()`을 사용하고 있습니다. @@ -50,7 +50,7 @@ /// -/// info | "정보" +/// info | 정보 이벤트 핸들러에 관한 내용은 Starlette 이벤트 문서에서 추가로 확인할 수 있습니다. diff --git a/docs/ko/docs/advanced/index.md b/docs/ko/docs/advanced/index.md index cb628fa10..31704727c 100644 --- a/docs/ko/docs/advanced/index.md +++ b/docs/ko/docs/advanced/index.md @@ -6,7 +6,7 @@ 이어지는 장에서는 여러분이 다른 옵션, 구성 및 추가 기능을 보실 수 있습니다. -/// tip | "팁" +/// tip | 팁 다음 장들이 **반드시 "심화"**인 것은 아닙니다. diff --git a/docs/ko/docs/advanced/response-cookies.md b/docs/ko/docs/advanced/response-cookies.md index 3f87b320a..f762e94b5 100644 --- a/docs/ko/docs/advanced/response-cookies.md +++ b/docs/ko/docs/advanced/response-cookies.md @@ -40,7 +40,7 @@ ### 추가 정보 -/// note | "기술적 세부사항" +/// note | 기술적 세부사항 `from starlette.responses import Response` 또는 `from starlette.responses import JSONResponse`를 사용할 수도 있습니다. diff --git a/docs/ko/docs/advanced/response-directly.md b/docs/ko/docs/advanced/response-directly.md index 20389ff2a..aedebff9d 100644 --- a/docs/ko/docs/advanced/response-directly.md +++ b/docs/ko/docs/advanced/response-directly.md @@ -38,7 +38,7 @@ Pydantic 모델로 데이터 변환을 수행하지 않으며, 내용을 다른 {!../../docs_src/response_directly/tutorial001.py!} ``` -/// note | "기술적 세부 사항" +/// note | 기술적 세부 사항 `from starlette.responses import JSONResponse`를 사용할 수도 있습니다. diff --git a/docs/ko/docs/advanced/response-headers.md b/docs/ko/docs/advanced/response-headers.md index 54cf655c5..974a06969 100644 --- a/docs/ko/docs/advanced/response-headers.md +++ b/docs/ko/docs/advanced/response-headers.md @@ -28,7 +28,7 @@ {!../../docs_src/response_headers/tutorial001.py!} ``` -/// note | "기술적 세부사항" +/// note | 기술적 세부사항 `from starlette.responses import Response`나 `from starlette.responses import JSONResponse`를 사용할 수도 있습니다. diff --git a/docs/ko/docs/async.md b/docs/ko/docs/async.md index dfc2caa78..fa0d20488 100644 --- a/docs/ko/docs/async.md +++ b/docs/ko/docs/async.md @@ -21,7 +21,7 @@ async def read_results(): return results ``` -/// note | "참고" +/// note | 참고 `async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다. @@ -369,7 +369,7 @@ FastAPI를 사용하지 않더라도, 높은 호환성 및 -/// info | "정보" +/// info | 정보 패키지 종속성을 정의하고 설치하기 위한 방법과 도구는 다양합니다. @@ -231,7 +231,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 프로그램이 `/code`에서 시작하고 그 속에 `./app` 디렉터리가 여러분의 코드와 함께 들어있기 때문에, **Uvicorn**은 이를 보고 `app`을 `app.main`으로부터 **불러 올** 것입니다. -/// tip | "팁" +/// tip | 팁 각 코드 라인을 코드의 숫자 버블을 클릭하여 리뷰할 수 있습니다. 👆 @@ -305,7 +305,7 @@ $ docker build -t myimage . -/// tip | "팁" +/// tip | 팁 맨 끝에 있는 `.` 에 주목합시다. 이는 `./`와 동등하며, 도커에게 컨테이너 이미지를 빌드하기 위한 디렉터리를 알려줍니다. @@ -409,7 +409,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] **HTTPS**와 **인증서**의 **자동** 취득을 다루는 것은 다른 컨테이너가 될 수 있는데, 예를 들어 Traefik을 사용하는 것입니다. -/// tip | "팁" +/// tip | 팁 Traefik은 도커, 쿠버네티스, 그리고 다른 도구와 통합되어 있어 여러분의 컨테이너를 포함하는 HTTPS를 셋업하고 설정하는 것이 매우 쉽습니다. @@ -441,7 +441,7 @@ Traefik은 도커, 쿠버네티스, 그리고 다른 도구와 통합되어 있 이 요소가 요청들의 **로드**를 읽어들이고 각 워커에게 (바라건대) **균형적으로** 분배한다면, 이 요소는 일반적으로 **로드 밸런서**라고 불립니다. -/// tip | "팁" +/// tip | 팁 HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런서**가 될 수 있습니다. @@ -524,7 +524,7 @@ HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런 만약 여러분이 **여러개의 컨테이너**를 가지고 있다면, 아마도 각각의 컨테이너는 **하나의 프로세스**를 가지고 있을 것입니다(예를 들어, **쿠버네티스** 클러스터에서). 그러면 여러분은 복제된 워커 컨테이너를 실행하기 **이전에**, 하나의 컨테이너에 있는 **이전의 단계들을** 수행하는 단일 프로세스를 가지는 **별도의 컨테이너들**을 가지고 싶을 것입니다. -/// info | "정보" +/// info | 정보 만약 여러분이 쿠버네티스를 사용하고 있다면, 아마도 이는 Init Container일 것입니다. @@ -544,7 +544,7 @@ HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런 * tiangolo/uvicorn-gunicorn-fastapi. -/// warning | "경고" +/// warning | 경고 여러분이 이 베이스 이미지 또는 다른 유사한 이미지를 필요로 하지 **않을** 높은 가능성이 있으며, [위에서 설명된 것처럼: FastAPI를 위한 도커 이미지 빌드하기](#build-a-docker-image-for-fastapi) 처음부터 이미지를 빌드하는 것이 더 나을 수 있습니다. @@ -556,7 +556,7 @@ HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런 또한 스크립트를 통해 **시작하기 전 사전 단계**를 실행하는 것을 지원합니다. -/// tip | "팁" +/// tip | 팁 모든 설정과 옵션을 보려면, 도커 이미지 페이지로 이동합니다: tiangolo/uvicorn-gunicorn-fastapi. @@ -687,7 +687,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. `uvicorn` 커맨드를 실행하여, `app.main`에서 불러온 `app` 객체를 사용하도록 합니다. -/// tip | "팁" +/// tip | 팁 버블 숫자를 클릭해 각 줄이 하는 일을 알아볼 수 있습니다. diff --git a/docs/ko/docs/deployment/server-workers.md b/docs/ko/docs/deployment/server-workers.md index 39976faf5..b40b25cd8 100644 --- a/docs/ko/docs/deployment/server-workers.md +++ b/docs/ko/docs/deployment/server-workers.md @@ -17,7 +17,7 @@ 지금부터 **구니콘**을 **유비콘 워커 프로세스**와 함께 사용하는 방법을 알려드리겠습니다. -/// info | "정보" +/// info | 정보 만약 도커와 쿠버네티스 같은 컨테이너를 사용하고 있다면 다음 챕터 [FastAPI와 컨테이너 - 도커](docker.md){.internal-link target=_blank}에서 더 많은 정보를 얻을 수 있습니다. diff --git a/docs/ko/docs/deployment/versions.md b/docs/ko/docs/deployment/versions.md index f3b3c2d7b..559a892ab 100644 --- a/docs/ko/docs/deployment/versions.md +++ b/docs/ko/docs/deployment/versions.md @@ -43,7 +43,7 @@ fastapi>=0.45.0,<0.46.0 FastAPI는 오류를 수정하고, 일반적인 변경사항을 위해 "패치"버전의 관습을 따릅니다. -/// tip | "팁" +/// tip | 팁 여기서 말하는 "패치"란 버전의 마지막 숫자로, 예를 들어 `0.2.3` 버전에서 "패치"는 `3`을 의미합니다. @@ -57,7 +57,7 @@ fastapi>=0.45.0,<0.46.0 수정된 사항과 새로운 요소들이 "마이너" 버전에 추가되었습니다. -/// tip | "팁" +/// tip | 팁 "마이너"란 버전 넘버의 가운데 숫자로, 예를 들어서 `0.2.3`의 "마이너" 버전은 `2`입니다. diff --git a/docs/ko/docs/environment-variables.md b/docs/ko/docs/environment-variables.md index 09c2fd6d3..1e6af3ceb 100644 --- a/docs/ko/docs/environment-variables.md +++ b/docs/ko/docs/environment-variables.md @@ -1,6 +1,6 @@ # 환경 변수 -/// tip | "팁" +/// tip | 팁 만약 "환경 변수"가 무엇이고, 어떻게 사용하는지 알고 계시다면, 이 챕터를 스킵하셔도 좋습니다. @@ -63,7 +63,7 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -/// tip | "팁" +/// tip | 팁 `os.getenv()` 의 두 번째 인자는 반환할 기본값입니다. @@ -151,7 +151,7 @@ Hello World from Python -/// tip | "팁" +/// tip | 팁 The Twelve-Factor App: Config 에서 좀 더 자세히 알아볼 수 있습니다. diff --git a/docs/ko/docs/features.md b/docs/ko/docs/features.md index b6f6f7af2..5e880c298 100644 --- a/docs/ko/docs/features.md +++ b/docs/ko/docs/features.md @@ -63,7 +63,7 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -/// info | "정보" +/// info | 정보 `**second_user_data`가 뜻하는 것: diff --git a/docs/ko/docs/python-types.md b/docs/ko/docs/python-types.md index 6d7346189..7cc98ba76 100644 --- a/docs/ko/docs/python-types.md +++ b/docs/ko/docs/python-types.md @@ -12,7 +12,7 @@ 비록 **FastAPI**를 쓰지 않는다고 하더라도, 조금이라도 알아두면 도움이 될 것입니다. -/// note | "참고" +/// note | 참고 파이썬에 능숙하셔서 타입 힌트에 대해 모두 아신다면, 다음 챕터로 건너뛰세요. @@ -175,7 +175,7 @@ John Doe {!../../docs_src/python_types/tutorial006.py!} ``` -/// tip | "팁" +/// tip | 팁 대괄호 안의 내부 타입은 "타입 매개변수(type paramters)"라고 합니다. @@ -287,7 +287,7 @@ Pydantic 공식 문서 예시: {!../../docs_src/python_types/tutorial011.py!} ``` -/// info | "정보" +/// info | 정보 Pydantic<에 대해 더 배우고 싶다면 공식 문서를 참고하세요. @@ -319,7 +319,7 @@ Pydantic<에 대해 더 배우고 싶다면 `mypy`에서 제공하는 "cheat sheet"이 좋은 자료가 될 겁니다. diff --git a/docs/ko/docs/tutorial/body-fields.md b/docs/ko/docs/tutorial/body-fields.md index a13159c27..f6532f369 100644 --- a/docs/ko/docs/tutorial/body-fields.md +++ b/docs/ko/docs/tutorial/body-fields.md @@ -32,7 +32,7 @@ //// tab | Python 3.10+ Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. @@ -46,7 +46,7 @@ //// tab | Python 3.8+ Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. @@ -58,7 +58,7 @@ //// -/// warning | "경고" +/// warning | 경고 `Field`는 다른 것들처럼 (`Query`, `Path`, `Body` 등) `fastapi`에서가 아닌 `pydantic`에서 바로 임포트 되는 점에 주의하세요. @@ -94,7 +94,7 @@ //// tab | Python 3.10+ Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. @@ -108,7 +108,7 @@ //// tab | Python 3.8+ Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. @@ -122,7 +122,7 @@ `Field`는 `Query`, `Path`와 `Body`와 같은 방식으로 동작하며, 모두 같은 매개변수들 등을 가집니다. -/// note | "기술적 세부사항" +/// note | 기술적 세부사항 실제로 `Query`, `Path`등, 여러분이 앞으로 볼 다른 것들은 공통 클래스인 `Param` 클래스의 서브클래스 객체를 만드는데, 그 자체로 Pydantic의 `FieldInfo` 클래스의 서브클래스입니다. @@ -134,7 +134,7 @@ /// -/// tip | "팁" +/// tip | 팁 주목할 점은 타입, 기본 값 및 `Field`로 이루어진 각 모델 어트리뷰트가 `Path`, `Query`와 `Body`대신 `Field`를 사용하는 *경로 작동 함수*의 매개변수와 같은 구조를 가진다는 점 입니다. @@ -146,7 +146,7 @@ 여러분이 예제를 선언할 때 나중에 이 공식 문서에서 별도 정보를 추가하는 방법을 배울 것입니다. -/// warning | "경고" +/// warning | 경고 별도 키가 전달된 `Field` 또한 여러분의 어플리케이션의 OpenAPI 스키마에 나타날 것입니다. 이런 키가 OpenAPI 명세서, [the OpenAPI validator](https://validator.swagger.io/)같은 몇몇 OpenAPI 도구들에 포함되지 못할 수 있으며, 여러분이 생성한 스키마와 호환되지 않을 수 있습니다. diff --git a/docs/ko/docs/tutorial/body-multiple-params.md b/docs/ko/docs/tutorial/body-multiple-params.md index 0a0f34585..569ff016e 100644 --- a/docs/ko/docs/tutorial/body-multiple-params.md +++ b/docs/ko/docs/tutorial/body-multiple-params.md @@ -14,7 +14,7 @@ {!../../docs_src/body_multiple_params/tutorial001.py!} ``` -/// note | "참고" +/// note | 참고 이 경우에는 본문으로 부터 가져온 ` item`은 기본값이 `None`이기 때문에, 선택사항이라는 점을 유의해야 합니다. @@ -58,7 +58,7 @@ } ``` -/// note | "참고" +/// note | 참고 이전과 같이 `item`이 선언 되었더라도, 본문 내의 `item` 키가 있을 것이라고 예측합니다. @@ -120,7 +120,7 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 q: Optional[str] = None ``` -/// info | "정보" +/// info | 정보 `Body` 또한 `Query`, `Path` 그리고 이후에 볼 다른 것들처럼 동일한 추가 검증과 메타데이터 매개변수를 갖고 있습니다. diff --git a/docs/ko/docs/tutorial/body-nested-models.md b/docs/ko/docs/tutorial/body-nested-models.md index 12fb4e0cc..e9b1d2e18 100644 --- a/docs/ko/docs/tutorial/body-nested-models.md +++ b/docs/ko/docs/tutorial/body-nested-models.md @@ -161,7 +161,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. } ``` -/// info | "정보" +/// info | 정보 `images` 키가 어떻게 이미지 객체 리스트를 갖는지 주목하세요. @@ -175,7 +175,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. {!../../docs_src/body_nested_models/tutorial007.py!} ``` -/// info | "정보" +/// info | 정보 `Offer`가 선택사항 `Image` 리스트를 차례로 갖는 `Item` 리스트를 어떻게 가지고 있는지 주목하세요 @@ -227,7 +227,7 @@ Pydantic 모델 대신에 `dict`를 직접 사용하여 작업할 경우, 이러 {!../../docs_src/body_nested_models/tutorial009.py!} ``` -/// tip | "팁" +/// tip | 팁 JSON은 오직 `str`형 키만 지원한다는 것을 염두에 두세요. diff --git a/docs/ko/docs/tutorial/body.md b/docs/ko/docs/tutorial/body.md index 8df8d556e..9e614ef1c 100644 --- a/docs/ko/docs/tutorial/body.md +++ b/docs/ko/docs/tutorial/body.md @@ -8,7 +8,7 @@ **요청** 본문을 선언하기 위해서 모든 강력함과 이점을 갖춘 Pydantic 모델을 사용합니다. -/// info | "정보" +/// info | 정보 데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다. @@ -149,7 +149,7 @@ -/// tip | "팁" +/// tip | 팁 만약 PyCharm를 편집기로 사용한다면, Pydantic PyCharm Plugin을 사용할 수 있습니다. @@ -233,7 +233,7 @@ * 만약 매개변수가 (`int`, `float`, `str`, `bool` 등과 같은) **유일한 타입**으로 되어있으면, **쿼리** 매개변수로 해석될 것입니다. * 만약 매개변수가 **Pydantic 모델** 타입으로 선언되어 있으면, 요청 **본문**으로 해석될 것입니다. -/// note | "참고" +/// note | 참고 FastAPI는 `q`의 값이 필요없음을 알게 될 것입니다. 기본 값이 `= None`이기 때문입니다. diff --git a/docs/ko/docs/tutorial/cookie-params.md b/docs/ko/docs/tutorial/cookie-params.md index 1e21e069d..427539210 100644 --- a/docs/ko/docs/tutorial/cookie-params.md +++ b/docs/ko/docs/tutorial/cookie-params.md @@ -32,7 +32,7 @@ //// tab | Python 3.10+ Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. @@ -46,7 +46,7 @@ //// tab | Python 3.8+ Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. @@ -90,7 +90,7 @@ //// tab | Python 3.10+ Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. @@ -104,7 +104,7 @@ //// tab | Python 3.8+ Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. @@ -116,7 +116,7 @@ //// -/// note | "기술 세부사항" +/// note | 기술 세부사항 `Cookie`는 `Path` 및 `Query`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. @@ -124,7 +124,7 @@ /// -/// info | "정보" +/// info | 정보 쿠키를 선언하기 위해서는 `Cookie`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. diff --git a/docs/ko/docs/tutorial/cors.md b/docs/ko/docs/tutorial/cors.md index 65357ae3f..0222e6258 100644 --- a/docs/ko/docs/tutorial/cors.md +++ b/docs/ko/docs/tutorial/cors.md @@ -78,7 +78,7 @@ CORS에 대한 더 많은 정보를 알고싶다면, Mozilla CORS 문서를 참고하기 바랍니다. -/// note | "기술적 세부 사항" +/// note | 기술적 세부 사항 `from starlette.middleware.cors import CORSMiddleware` 역시 사용할 수 있습니다. diff --git a/docs/ko/docs/tutorial/debugging.md b/docs/ko/docs/tutorial/debugging.md index 27e8f9abf..fcb68b565 100644 --- a/docs/ko/docs/tutorial/debugging.md +++ b/docs/ko/docs/tutorial/debugging.md @@ -74,7 +74,7 @@ from myapp import app 은 실행되지 않습니다. -/// info | "정보" +/// info | 정보 자세한 내용은 공식 Python 문서를 확인하세요 diff --git a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md index 7430efbb4..41e48aefc 100644 --- a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md @@ -266,7 +266,7 @@ commons: CommonQueryParams = Depends() ...이렇게 코드를 단축하여도 **FastAPI**는 무엇을 해야하는지 알고 있습니다. -/// tip | "팁" +/// tip | 팁 만약 이것이 도움이 되기보다 더 헷갈리게 만든다면, 잊어버리십시오. 이것이 반드시 필요한 것은 아닙니다. diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index e71ba8546..fab636b7f 100644 --- a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -32,7 +32,7 @@ //// tab | Python 3.8 Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. @@ -46,7 +46,7 @@ 이러한 의존성들은 기존 의존성들과 같은 방식으로 실행/해결됩니다. 그러나 값은 (무엇이든 반환한다면) *경로 작동 함수*에 제공되지 않습니다. -/// tip | "팁" +/// tip | 팁 일부 편집기에서는 사용되지 않는 함수 매개변수를 검사하고 오류로 표시합니다. @@ -56,7 +56,7 @@ /// -/// info | "정보" +/// info | 정보 이 예시에서 `X-Key`와 `X-Token`이라는 커스텀 헤더를 만들어 사용했습니다. @@ -90,7 +90,7 @@ //// tab | Python 3.8 Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. @@ -124,7 +124,7 @@ //// tab | Python 3.8 Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. @@ -160,7 +160,7 @@ //// tab | Python 3.8 Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. diff --git a/docs/ko/docs/tutorial/dependencies/global-dependencies.md b/docs/ko/docs/tutorial/dependencies/global-dependencies.md index dd6586c3e..0ad8b55fd 100644 --- a/docs/ko/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/global-dependencies.md @@ -24,7 +24,7 @@ //// tab | Python 3.8 Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. diff --git a/docs/ko/docs/tutorial/dependencies/index.md b/docs/ko/docs/tutorial/dependencies/index.md index f7b2f1788..1aba6e787 100644 --- a/docs/ko/docs/tutorial/dependencies/index.md +++ b/docs/ko/docs/tutorial/dependencies/index.md @@ -57,7 +57,7 @@ //// tab | Python 3.10+ Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. @@ -71,7 +71,7 @@ //// tab | Python 3.8+ Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. @@ -101,7 +101,7 @@ 그 후 위의 값을 포함한 `dict` 자료형으로 반환할 뿐입니다. -/// info | "정보" +/// info | 정보 FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다. @@ -139,7 +139,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 //// tab | Python 3.10+ Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. @@ -153,7 +153,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 //// tab | Python 3.8+ Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. @@ -195,7 +195,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 //// tab | Python 3.10+ Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. @@ -209,7 +209,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 //// tab | Python 3.8+ Annotated가 없는 경우 -/// tip | "팁" +/// tip | 팁 가능하다면 `Annotated`가 달린 버전을 권장합니다. @@ -231,7 +231,7 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 그리고 그 함수는 *경로 작동 함수*가 작동하는 것과 같은 방식으로 매개변수를 받습니다. -/// tip | "팁" +/// tip | 팁 여러분은 다음 장에서 함수를 제외하고서, "다른 것들"이 어떻게 의존성으로 사용되는지 알게 될 것입니다. @@ -256,7 +256,7 @@ common_parameters --> read_users 이렇게 하면 공용 코드를 한번만 적어도 되며, **FastAPI**는 *경로 작동*을 위해 이에 대한 호출을 처리합니다. -/// check | "확인" +/// check | 확인 특별한 클래스를 만들지 않아도 되며, 이러한 것 혹은 비슷한 종류를 **FastAPI**에 "등록"하기 위해 어떤 곳에 넘겨주지 않아도 됩니다. @@ -300,7 +300,7 @@ commons: Annotated[dict, Depends(common_parameters)] //// -/// tip | "팁" +/// tip | 팁 이는 그저 표준 파이썬이고 "type alias"라고 부르며 사실 **FastAPI**에 국한되는 것은 아닙니다. @@ -322,7 +322,7 @@ commons: Annotated[dict, Depends(common_parameters)] 아무 문제 없습니다. **FastAPI**는 무엇을 할지 알고 있습니다. -/// note | "참고" +/// note | 참고 잘 모르시겠다면, [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} 문서에서 `async`와 `await`에 대해 확인할 수 있습니다. diff --git a/docs/ko/docs/tutorial/encoder.md b/docs/ko/docs/tutorial/encoder.md index 732566d6d..52277f258 100644 --- a/docs/ko/docs/tutorial/encoder.md +++ b/docs/ko/docs/tutorial/encoder.md @@ -30,7 +30,7 @@ Pydantic 모델과 같은 객체를 받고 JSON 호환 가능한 버전으로 길이가 긴 문자열 형태의 JSON 형식(문자열)의 데이터가 들어있는 상황에서는 `str`로 반환하지 않습니다. JSON과 모두 호환되는 값과 하위 값이 있는 Python 표준 데이터 구조 (예: `dict`)를 반환합니다. -/// note | "참고" +/// note | 참고 실제로 `jsonable_encoder`는 **FastAPI** 에서 내부적으로 데이터를 변환하는 데 사용하지만, 다른 많은 곳에서도 이는 유용합니다. diff --git a/docs/ko/docs/tutorial/first-steps.md b/docs/ko/docs/tutorial/first-steps.md index c2c48fb3e..4a689b74a 100644 --- a/docs/ko/docs/tutorial/first-steps.md +++ b/docs/ko/docs/tutorial/first-steps.md @@ -24,7 +24,7 @@ $ uvicorn main:app --reload -/// note | "참고" +/// note | 참고 `uvicorn main:app` 명령은 다음을 의미합니다: @@ -139,7 +139,7 @@ API와 통신하는 클라이언트(프론트엔드, 모바일, IoT 애플리케 `FastAPI`는 당신의 API를 위한 모든 기능을 제공하는 파이썬 클래스입니다. -/// note | "기술 세부사항" +/// note | 기술 세부사항 `FastAPI`는 `Starlette`를 직접 상속하는 클래스입니다. @@ -205,7 +205,7 @@ https://example.com/items/foo /items/foo ``` -/// info | "정보" +/// info | 정보 "경로"는 일반적으로 "엔드포인트" 또는 "라우트"라고도 불립니다. @@ -259,7 +259,7 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 * 경로 `/` * get 작동 사용 -/// info | "`@decorator` 정보" +/// info | `@decorator` 정보 이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다. @@ -286,7 +286,7 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 * `@app.patch()` * `@app.trace()` -/// tip | "팁" +/// tip | 팁 각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다. @@ -324,7 +324,7 @@ URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **Fa {!../../docs_src/first_steps/tutorial003.py!} ``` -/// note | "참고" +/// note | 참고 차이점을 모르겠다면 [Async: *"바쁘신 경우"*](../async.md#_1){.internal-link target=_blank}을 확인하세요. diff --git a/docs/ko/docs/tutorial/header-params.md b/docs/ko/docs/tutorial/header-params.md index 26e198869..972f52a33 100644 --- a/docs/ko/docs/tutorial/header-params.md +++ b/docs/ko/docs/tutorial/header-params.md @@ -20,7 +20,7 @@ {!../../docs_src/header_params/tutorial001.py!} ``` -/// note | "기술 세부사항" +/// note | 기술 세부사항 `Header`는 `Path`, `Query` 및 `Cookie`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. @@ -28,7 +28,7 @@ /// -/// info | "정보" +/// info | 정보 헤더를 선언하기 위해서 `Header`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. @@ -54,7 +54,7 @@ {!../../docs_src/header_params/tutorial002.py!} ``` -/// warning | "경고" +/// warning | 경고 `convert_underscore`를 `False`로 설정하기 전에, 어떤 HTTP 프록시들과 서버들은 언더스코어가 포함된 헤더 사용을 허락하지 않는다는 것을 명심하십시오. diff --git a/docs/ko/docs/tutorial/index.md b/docs/ko/docs/tutorial/index.md index a148bc76e..9f5328992 100644 --- a/docs/ko/docs/tutorial/index.md +++ b/docs/ko/docs/tutorial/index.md @@ -53,7 +53,7 @@ $ pip install "fastapi[all]" ...이는 코드를 실행하는 서버로 사용할 수 있는 `uvicorn` 또한 포함하고 있습니다. -/// note | "참고" +/// note | 참고 부분적으로 설치할 수도 있습니다. diff --git a/docs/ko/docs/tutorial/middleware.md b/docs/ko/docs/tutorial/middleware.md index f36f11a27..0547066f1 100644 --- a/docs/ko/docs/tutorial/middleware.md +++ b/docs/ko/docs/tutorial/middleware.md @@ -11,7 +11,7 @@ * **응답** 또는 다른 필요한 코드를 실행시키는 동작을 할 수 있습니다. * **응답**를 반환합니다. -/// note | "기술 세부사항" +/// note | 기술 세부사항 만약 `yield`를 사용한 의존성을 가지고 있다면, 미들웨어가 실행되고 난 후에 exit이 실행됩니다. @@ -35,7 +35,7 @@ {!../../docs_src/middleware/tutorial001.py!} ``` -/// tip | "팁" +/// tip | 팁 사용자 정의 헤더는 'X-' 접두사를 사용하여 추가할 수 있습니다. @@ -43,7 +43,7 @@ /// -/// note | "기술적 세부사항" +/// note | 기술적 세부사항 `from starlette.requests import request`를 사용할 수도 있습니다. diff --git a/docs/ko/docs/tutorial/path-operation-configuration.md b/docs/ko/docs/tutorial/path-operation-configuration.md index 6ebe613a8..75a9c71ce 100644 --- a/docs/ko/docs/tutorial/path-operation-configuration.md +++ b/docs/ko/docs/tutorial/path-operation-configuration.md @@ -2,7 +2,7 @@ *경로 작동 데코레이터*를 설정하기 위해서 전달할수 있는 몇 가지 매개변수가 있습니다. -/// warning | "경고" +/// warning | 경고 아래 매개변수들은 *경로 작동 함수*가 아닌 *경로 작동 데코레이터*에 직접 전달된다는 사실을 기억하십시오. @@ -22,7 +22,7 @@ 각 상태 코드들은 응답에 사용되며, OpenAPI 스키마에 추가됩니다. -/// note | "기술적 세부사항" +/// note | 기술적 세부사항 다음과 같이 임포트하셔도 좋습니다. `from starlette import status`. @@ -72,13 +72,13 @@ {!../../docs_src/path_operation_configuration/tutorial005.py!} ``` -/// info | "정보" +/// info | 정보 `response_description`은 구체적으로 응답을 지칭하며, `description`은 일반적인 *경로 작동*을 지칭합니다. /// -/// check | "확인" +/// check | 확인 OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 명시합니다. diff --git a/docs/ko/docs/tutorial/path-params-numeric-validations.md b/docs/ko/docs/tutorial/path-params-numeric-validations.md index caab2d453..736f2dc1d 100644 --- a/docs/ko/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ko/docs/tutorial/path-params-numeric-validations.md @@ -20,7 +20,7 @@ {!../../docs_src/path_params_numeric_validations/tutorial001.py!} ``` -/// note | "참고" +/// note | 참고 경로 매개변수는 경로의 일부여야 하므로 언제나 필수적입니다. @@ -108,7 +108,7 @@ * `lt`: 작거나(`l`ess `t`han) * `le`: 작거나 같은(`l`ess than or `e`qual) -/// info | "정보" +/// info | 정보 `Query`, `Path`, 그리고 나중에게 보게될 것들은 (여러분이 사용할 필요가 없는) 공통 `Param` 클래스의 서브 클래스입니다. @@ -116,7 +116,7 @@ /// -/// note | "기술 세부사항" +/// note | 기술 세부사항 `fastapi`에서 `Query`, `Path` 등을 임포트 할 때, 이것들은 실제로 함수입니다. diff --git a/docs/ko/docs/tutorial/path-params.md b/docs/ko/docs/tutorial/path-params.md index 09a27a7b3..21808e2ca 100644 --- a/docs/ko/docs/tutorial/path-params.md +++ b/docs/ko/docs/tutorial/path-params.md @@ -24,7 +24,7 @@ 위의 예시에서, `item_id`는 `int`로 선언되었습니다. -/// check | "확인" +/// check | 확인 이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다. @@ -38,7 +38,7 @@ {"item_id":3} ``` -/// check | "확인" +/// check | 확인 함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다. @@ -69,7 +69,7 @@ `int`가 아닌 `float`을 전달하는 경우에도 동일한 오류가 나타납니다: http://127.0.0.1:8000/items/4.2 -/// check | "확인" +/// check | 확인 즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다. @@ -85,7 +85,7 @@ -/// check | "확인" +/// check | 확인 그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화형 API 문서(Swagger UI)를 제공합니다. @@ -143,13 +143,13 @@ {!../../docs_src/path_params/tutorial005.py!} ``` -/// info | "정보" +/// info | 정보 열거형(또는 enums)은 파이썬 버전 3.4 이후로 사용 가능합니다. /// -/// tip | "팁" +/// tip | 팁 혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 모델들의 이름입니다. @@ -189,7 +189,7 @@ {!../../docs_src/path_params/tutorial005.py!} ``` -/// tip | "팁" +/// tip | 팁 `ModelName.lenet.value`로도 값 `"lenet"`에 접근할 수 있습니다. @@ -246,7 +246,7 @@ Starlette의 옵션을 직접 이용하여 다음과 같은 URL을 사용함으 {!../../docs_src/path_params/tutorial004.py!} ``` -/// tip | "팁" +/// tip | 팁 매개변수가 가져야 하는 값이 `/home/johndoe/myfile.txt`와 같이 슬래시로 시작(`/`)해야 할 수 있습니다. diff --git a/docs/ko/docs/tutorial/query-params-str-validations.md b/docs/ko/docs/tutorial/query-params-str-validations.md index e44f6dd16..71f884e83 100644 --- a/docs/ko/docs/tutorial/query-params-str-validations.md +++ b/docs/ko/docs/tutorial/query-params-str-validations.md @@ -10,7 +10,7 @@ 쿼리 매개변수 `q`는 `Optional[str]` 자료형입니다. 즉, `str` 자료형이지만 `None` 역시 될 수 있음을 뜻하고, 실제로 기본값은 `None`이기 때문에 FastAPI는 이 매개변수가 필수가 아니라는 것을 압니다. -/// note | "참고" +/// note | 참고 FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압니다. @@ -54,7 +54,7 @@ q: Optional[str] = None 하지만 명시적으로 쿼리 매개변수를 선언합니다. -/// info | "정보" +/// info | 정보 FastAPI는 다음 부분에 관심이 있습니다: @@ -118,7 +118,7 @@ q: str = Query(None, max_length=50) {!../../docs_src/query_params_str_validations/tutorial005.py!} ``` -/// note | "참고" +/// note | 참고 기본값을 갖는 것만으로 매개변수는 선택적이 됩니다. @@ -150,7 +150,7 @@ q: Optional[str] = Query(None, min_length=3) {!../../docs_src/query_params_str_validations/tutorial006.py!} ``` -/// info | "정보" +/// info | 정보 이전에 `...`를 본적이 없다면: 특별한 단일값으로, 파이썬의 일부이며 "Ellipsis"라 부릅니다. @@ -187,7 +187,7 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -/// tip | "팁" +/// tip | 팁 위의 예와 같이 `list` 자료형으로 쿼리 매개변수를 선언하려면 `Query`를 명시적으로 사용해야 합니다. 그렇지 않으면 요청 본문으로 해석됩니다. @@ -230,7 +230,7 @@ http://localhost:8000/items/ {!../../docs_src/query_params_str_validations/tutorial013.py!} ``` -/// note | "참고" +/// note | 참고 이 경우 FastAPI는 리스트의 내용을 검사하지 않음을 명심하기 바랍니다. @@ -244,7 +244,7 @@ http://localhost:8000/items/ 해당 정보는 생성된 OpenAPI에 포함되고 문서 사용자 인터페이스 및 외부 도구에서 사용됩니다. -/// note | "참고" +/// note | 참고 도구에 따라 OpenAPI 지원 수준이 다를 수 있음을 명심하기 바랍니다. diff --git a/docs/ko/docs/tutorial/query-params.md b/docs/ko/docs/tutorial/query-params.md index b2a946c09..7fa3e8c53 100644 --- a/docs/ko/docs/tutorial/query-params.md +++ b/docs/ko/docs/tutorial/query-params.md @@ -69,13 +69,13 @@ http://127.0.0.1:8000/items/?skip=20 이 경우 함수 매개변수 `q`는 선택적이며 기본값으로 `None` 값이 됩니다. -/// check | "확인" +/// check | 확인 **FastAPI**는 `item_id`가 경로 매개변수이고 `q`는 경로 매개변수가 아닌 쿼리 매개변수라는 것을 알 정도로 충분히 똑똑합니다. /// -/// note | "참고" +/// note | 참고 FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다. @@ -200,7 +200,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`, 기본값이 `0`인 `int`. * `limit`, 선택적인 `int`. -/// tip | "팁" +/// tip | 팁 [경로 매개변수](path-params.md#_8){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다. diff --git a/docs/ko/docs/tutorial/request-files.md b/docs/ko/docs/tutorial/request-files.md index 40579dd51..ca0f43978 100644 --- a/docs/ko/docs/tutorial/request-files.md +++ b/docs/ko/docs/tutorial/request-files.md @@ -2,7 +2,7 @@ `File`을 사용하여 클라이언트가 업로드할 파일들을 정의할 수 있습니다. -/// info | "정보" +/// info | 정보 업로드된 파일을 전달받기 위해 먼저 `python-multipart`를 설치해야합니다. @@ -28,7 +28,7 @@ {!../../docs_src/request_files/tutorial001.py!} ``` -/// info | "정보" +/// info | 정보 `File` 은 `Form` 으로부터 직접 상속된 클래스입니다. @@ -36,7 +36,7 @@ /// -/// tip | "팁" +/// tip | 팁 File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본문(JSON) 매개변수로 해석되는 것을 방지하기 위해 `File` 을 사용해야합니다. @@ -104,7 +104,7 @@ contents = myfile.file.read() /// -/// note | "Starlette 기술적 세부사항" +/// note | Starlette 기술적 세부사항 **FastAPI**의 `UploadFile` 은 **Starlette**의 `UploadFile` 을 직접적으로 상속받지만, **Pydantic** 및 FastAPI의 다른 부분들과의 호환성을 위해 필요한 부분들이 추가되었습니다. @@ -116,7 +116,7 @@ HTML의 폼들(`
`)이 서버에 데이터를 전송하는 방식은 **FastAPI**는 JSON 대신 올바른 위치에서 데이터를 읽을 수 있도록 합니다. -/// note | "기술적 세부사항" +/// note | 기술적 세부사항 폼의 데이터는 파일이 포함되지 않은 경우 일반적으로 "미디어 유형" `application/x-www-form-urlencoded` 을 사용해 인코딩 됩니다. @@ -126,7 +126,7 @@ HTML의 폼들(`
`)이 서버에 데이터를 전송하는 방식은 /// -/// warning | "경고" +/// warning | 경고 다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. @@ -148,7 +148,7 @@ HTML의 폼들(`
`)이 서버에 데이터를 전송하는 방식은 선언한대로, `bytes` 의 `list` 또는 `UploadFile` 들을 전송받을 것입니다. -/// note | "참고" +/// note | 참고 2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, #4276#3641을 참고하세요. @@ -158,7 +158,7 @@ HTML의 폼들(`
`)이 서버에 데이터를 전송하는 방식은 /// -/// note | "기술적 세부사항" +/// note | 기술적 세부사항 `from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다. diff --git a/docs/ko/docs/tutorial/request-forms-and-files.md b/docs/ko/docs/tutorial/request-forms-and-files.md index 24501fe34..75bca9f15 100644 --- a/docs/ko/docs/tutorial/request-forms-and-files.md +++ b/docs/ko/docs/tutorial/request-forms-and-files.md @@ -2,7 +2,7 @@ `File` 과 `Form` 을 사용하여 파일과 폼을 함께 정의할 수 있습니다. -/// info | "정보" +/// info | 정보 파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 `python-multipart`를 설치해야합니다. @@ -28,7 +28,7 @@ 어떤 파일들은 `bytes`로, 또 어떤 파일들은 `UploadFile`로 선언할 수 있습니다. -/// warning | "경고" +/// warning | 경고 다수의 `File`과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json`가 아닌 `multipart/form-data`로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. diff --git a/docs/ko/docs/tutorial/response-model.md b/docs/ko/docs/tutorial/response-model.md index 74034e34d..6ba9654d6 100644 --- a/docs/ko/docs/tutorial/response-model.md +++ b/docs/ko/docs/tutorial/response-model.md @@ -12,7 +12,7 @@ {!../../docs_src/response_model/tutorial001.py!} ``` -/// note | "참고" +/// note | 참고 `response_model`은 "데코레이터" 메소드(`get`, `post`, 등)의 매개변수입니다. 모든 매개변수들과 본문(body)처럼 *경로 작동 함수*가 아닙니다. @@ -31,7 +31,7 @@ FastAPI는 이 `response_model`를 사용하여: * 해당 모델의 출력 데이터 제한. 이것이 얼마나 중요한지 아래에서 볼 것입니다. -/// note | "기술 세부사항" +/// note | 기술 세부사항 응답 모델은 함수의 타입 어노테이션 대신 이 매개변수로 선언하는데, 경로 함수가 실제 응답 모델을 반환하지 않고 `dict`, 데이터베이스 객체나 기타 다른 모델을 `response_model`을 사용하여 필드 제한과 직렬화를 수행하고 반환할 수 있기 때문입니다 @@ -57,7 +57,7 @@ FastAPI는 이 `response_model`를 사용하여: 그러나 동일한 모델을 다른 *경로 작동*에서 사용할 경우, 모든 클라이언트에게 사용자의 비밀번호를 발신할 수 있습니다. -/// danger | "위험" +/// danger | 위험 절대로 사용자의 평문 비밀번호를 저장하거나 응답으로 발신하지 마십시오. @@ -130,13 +130,13 @@ FastAPI는 이 `response_model`를 사용하여: } ``` -/// info | "정보" +/// info | 정보 FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 `exclude_unset` 매개변수를 사용합니다. /// -/// info | "정보" +/// info | 정보 아래 또한 사용할 수 있습니다: @@ -181,7 +181,7 @@ ID가 `baz`인 항목(items)처럼 기본값과 동일한 값을 갖는다면: 따라서 JSON 스키마에 포함됩니다. -/// tip | "팁" +/// tip | 팁 `None` 뿐만 아니라 다른 어떤 것도 기본값이 될 수 있습니다. @@ -197,7 +197,7 @@ ID가 `baz`인 항목(items)처럼 기본값과 동일한 값을 갖는다면: Pydantic 모델이 하나만 있고 출력에서 ​​일부 데이터를 제거하려는 경우 빠른 지름길로 사용할 수 있습니다. -/// tip | "팁" +/// tip | 팁 하지만 이러한 매개변수 대신 여러 클래스를 사용하여 위 아이디어를 사용하는 것을 추천합니다. @@ -211,7 +211,7 @@ Pydantic 모델이 하나만 있고 출력에서 ​​일부 데이터를 제 {!../../docs_src/response_model/tutorial005.py!} ``` -/// tip | "팁" +/// tip | 팁 문법 `{"name", "description"}`은 두 값을 갖는 `set`을 만듭니다. diff --git a/docs/ko/docs/tutorial/response-status-code.md b/docs/ko/docs/tutorial/response-status-code.md index 57eef6ba1..8e3a16645 100644 --- a/docs/ko/docs/tutorial/response-status-code.md +++ b/docs/ko/docs/tutorial/response-status-code.md @@ -12,7 +12,7 @@ {!../../docs_src/response_status_code/tutorial001.py!} ``` -/// note | "참고" +/// note | 참고 `status_code` 는 "데코레이터" 메소드(`get`, `post` 등)의 매개변수입니다. 모든 매개변수들과 본문처럼 *경로 작동 함수*가 아닙니다. @@ -20,7 +20,7 @@ `status_code` 매개변수는 HTTP 상태 코드를 숫자로 입력받습니다. -/// info | "정보" +/// info | 정보 `status_code` 는 파이썬의 `http.HTTPStatus` 와 같은 `IntEnum` 을 입력받을 수도 있습니다. @@ -33,7 +33,7 @@ -/// note | "참고" +/// note | 참고 어떤 응답 코드들은 해당 응답에 본문이 없다는 것을 의미하기도 합니다 (다음 항목 참고). @@ -43,7 +43,7 @@ ## HTTP 상태 코드에 대하여 -/// note | "참고" +/// note | 참고 만약 HTTP 상태 코드에 대하여 이미 알고있다면, 다음 항목으로 넘어가십시오. @@ -66,7 +66,7 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 * 일반적인 클라이언트 오류의 경우 `400` 을 사용할 수 있습니다. * `5xx` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다. -/// tip | "팁" +/// tip | 팁 각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 MDN HTTP 상태 코드에 관한 문서 를 확인하십시오. @@ -94,7 +94,7 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 -/// note | "기술적 세부사항" +/// note | 기술적 세부사항 `from starlette import status` 역시 사용할 수 있습니다. diff --git a/docs/ko/docs/tutorial/schema-extra-example.md b/docs/ko/docs/tutorial/schema-extra-example.md index b713c8975..77e94db72 100644 --- a/docs/ko/docs/tutorial/schema-extra-example.md +++ b/docs/ko/docs/tutorial/schema-extra-example.md @@ -38,7 +38,7 @@ Pydantic v1에서 serwera czatu na Discordzie 👥 i spędzaj czas z innymi w społeczności FastAPI. -/// tip | "Wskazówka" +/// tip | Wskazówka Jeśli masz pytania, zadaj je w Dyskusjach na GitHubie, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. diff --git a/docs/pl/docs/tutorial/first-steps.md b/docs/pl/docs/tutorial/first-steps.md index 9466ca84d..8fa4c75ad 100644 --- a/docs/pl/docs/tutorial/first-steps.md +++ b/docs/pl/docs/tutorial/first-steps.md @@ -135,7 +135,7 @@ Możesz go również użyć do automatycznego generowania kodu dla klientów, kt `FastAPI` jest klasą, która zapewnia wszystkie funkcjonalności Twojego API. -/// note | "Szczegóły techniczne" +/// note | Szczegóły techniczne `FastAPI` jest klasą, która dziedziczy bezpośrednio z `Starlette`. @@ -249,7 +249,7 @@ Będziemy je również nazywali "**operacjami**". * ścieżki `/` * używając operacji get -/// info | "`@decorator` Info" +/// info | `@decorator` Info Składnia `@something` jest w Pythonie nazywana "dekoratorem". diff --git a/docs/pt/docs/advanced/additional-responses.md b/docs/pt/docs/advanced/additional-responses.md index 46cf1efc3..58e75ad93 100644 --- a/docs/pt/docs/advanced/additional-responses.md +++ b/docs/pt/docs/advanced/additional-responses.md @@ -1,6 +1,6 @@ # Retornos Adicionais no OpenAPI -/// warning | "Aviso" +/// warning | Aviso Este é um tema bem avançado. @@ -30,13 +30,13 @@ Por exemplo, para declarar um outro retorno com o status code `404` e um modelo {!../../docs_src/additional_responses/tutorial001.py!} ``` -/// note | "Nota" +/// note | Nota Lembre-se que você deve retornar o `JSONResponse` diretamente. /// -/// info | "Informação" +/// info | Informação A chave `model` não é parte do OpenAPI. @@ -181,13 +181,13 @@ Por exemplo, você pode adicionar um media type adicional de `image/png`, declar {!../../docs_src/additional_responses/tutorial002.py!} ``` -/// note | "Nota" +/// note | Nota Note que você deve retornar a imagem utilizando um `FileResponse` diretamente. /// -/// info | "Informação" +/// info | Informação A menos que você especifique um media type diferente explicitamente em seu parâmetro `responses`, o FastAPI assumirá que o retorno possui o mesmo media type contido na classe principal de retorno (padrão `application/json`). diff --git a/docs/pt/docs/advanced/additional-status-codes.md b/docs/pt/docs/advanced/additional-status-codes.md index 02bb4c015..5fe970d2a 100644 --- a/docs/pt/docs/advanced/additional-status-codes.md +++ b/docs/pt/docs/advanced/additional-status-codes.md @@ -40,7 +40,7 @@ Para conseguir isso, importe `JSONResponse` e retorne o seu conteúdo diretament //// tab | Python 3.10+ non-Annotated -/// tip | "Dica" +/// tip | Dica Faça uso da versão `Annotated` quando possível. @@ -54,7 +54,7 @@ Faça uso da versão `Annotated` quando possível. //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Faça uso da versão `Annotated` quando possível. @@ -66,7 +66,7 @@ Faça uso da versão `Annotated` quando possível. //// -/// warning | "Aviso" +/// warning | Aviso Quando você retorna um `Response` diretamente, como no exemplo acima, ele será retornado diretamente. @@ -76,7 +76,7 @@ Garanta que ele tenha toda informação que você deseja, e que os valores sejam /// -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Você também pode utilizar `from starlette.responses import JSONResponse`. diff --git a/docs/pt/docs/advanced/advanced-dependencies.md b/docs/pt/docs/advanced/advanced-dependencies.md index a656390a4..52fe121f9 100644 --- a/docs/pt/docs/advanced/advanced-dependencies.md +++ b/docs/pt/docs/advanced/advanced-dependencies.md @@ -36,7 +36,7 @@ Para fazer isso, nós declaramos o método `__call__`: //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Prefira utilizar a versão `Annotated` se possível. @@ -72,7 +72,7 @@ E agora, nós podemos utilizar o `__init__` para declarar os parâmetros da inst //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Prefira utilizar a versão `Annotated` se possível. @@ -108,7 +108,7 @@ Nós poderíamos criar uma instância desta classe com: //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Prefira utilizar a versão `Annotated` se possível. @@ -152,7 +152,7 @@ checker(q="somequery") //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Prefira utilizar a versão `Annotated` se possível. @@ -164,7 +164,7 @@ Prefira utilizar a versão `Annotated` se possível. //// -/// tip | "Dica" +/// tip | Dica Tudo isso parece não ser natural. E pode não estar muito claro ou aparentar ser útil ainda. diff --git a/docs/pt/docs/advanced/async-tests.md b/docs/pt/docs/advanced/async-tests.md index c81d6124b..8fae97298 100644 --- a/docs/pt/docs/advanced/async-tests.md +++ b/docs/pt/docs/advanced/async-tests.md @@ -64,7 +64,7 @@ O marcador `@pytest.mark.anyio` informa ao pytest que esta função de teste dev {!../../docs_src/async_tests/test_main.py!} ``` -/// tip | "Dica" +/// tip | Dica Note que a função de teste é `async def` agora, no lugar de apenas `def` como quando estávamos utilizando o `TestClient` anteriormente. @@ -84,13 +84,13 @@ response = client.get('/') ...que nós utilizamos para fazer as nossas requisições utilizando o `TestClient`. -/// tip | "Dica" +/// tip | Dica Note que nós estamos utilizando async/await com o novo `AsyncClient` - a requisição é assíncrona. /// -/// warning | "Aviso" +/// warning | Aviso Se a sua aplicação depende dos eventos de vida útil (*lifespan*), o `AsyncClient` não acionará estes eventos. Para garantir que eles são acionados, utilize o `LifespanManager` do florimondmanca/asgi-lifespan. @@ -100,7 +100,7 @@ Se a sua aplicação depende dos eventos de vida útil (*lifespan*), o `AsyncCli Como a função de teste agora é assíncrona, você pode chamar (e `esperar`) outras funções `async` além de enviar requisições para a sua aplicação FastAPI em seus testes, exatamente como você as chamaria em qualquer outro lugar do seu código. -/// tip | "Dica" +/// tip | Dica Se você se deparar com um `RuntimeError: Task attached to a different loop` ao integrar funções assíncronas em seus testes (e.g. ao utilizar o MotorClient do MongoDB) Lembre-se de instanciar objetos que precisam de um loop de eventos (*event loop*) apenas em funções assíncronas, e.g. um *"callback"* `'@app.on_event("startup")`. diff --git a/docs/pt/docs/advanced/behind-a-proxy.md b/docs/pt/docs/advanced/behind-a-proxy.md index 12fd83f3d..6837c9542 100644 --- a/docs/pt/docs/advanced/behind-a-proxy.md +++ b/docs/pt/docs/advanced/behind-a-proxy.md @@ -41,7 +41,7 @@ browser --> proxy proxy --> server ``` -/// tip | "Dica" +/// tip | Dica O IP `0.0.0.0` é comumente usado para significar que o programa escuta em todos os IPs disponíveis naquela máquina/servidor. @@ -82,7 +82,7 @@ $ fastapi run main.py --root-path /api/v1 Se você usar Hypercorn, ele também tem a opção `--root-path`. -/// note | "Detalhes Técnicos" +/// note | Detalhes Técnicos A especificação ASGI define um `root_path` para esse caso de uso. @@ -172,7 +172,7 @@ Então, crie um arquivo `traefik.toml` com: Isso diz ao Traefik para escutar na porta 9999 e usar outro arquivo `routes.toml`. -/// tip | "Dica" +/// tip | Dica Estamos usando a porta 9999 em vez da porta padrão HTTP 80 para que você não precise executá-lo com privilégios de administrador (`sudo`). @@ -242,7 +242,7 @@ Agora, se você for ao URL com a porta para o Uvicorn: -/// tip | "Dica" +/// tip | Dica A interface de documentação interagirá com o servidor que você selecionar. diff --git a/docs/pt/docs/advanced/events.md b/docs/pt/docs/advanced/events.md index 02f5b6d2b..783dbfc83 100644 --- a/docs/pt/docs/advanced/events.md +++ b/docs/pt/docs/advanced/events.md @@ -39,7 +39,7 @@ Aqui nós estamos simulando a *inicialização* custosa do carregamento do model E então, logo após o `yield`, descarregaremos o modelo. Esse código será executado **após** a aplicação **terminar de lidar com as requisições**, pouco antes do *encerramento*. Isso poderia, por exemplo, liberar recursos como memória ou GPU. -/// tip | "Dica" +/// tip | Dica O `shutdown` aconteceria quando você estivesse **encerrando** a aplicação. @@ -95,7 +95,7 @@ O parâmetro `lifespan` da aplicação `FastAPI` usa um **Gerenciador de Context ## Eventos alternativos (deprecados) -/// warning | "Aviso" +/// warning | Aviso A maneira recomendada para lidar com a *inicialização* e o *encerramento* é usando o parâmetro `lifespan` da aplicação `FastAPI` como descrito acima. @@ -133,13 +133,13 @@ Para adicionar uma função que deve ser executada quando a aplicação estiver Aqui, a função de manipulação de evento `shutdown` irá escrever uma linha de texto `"Application shutdown"` no arquivo `log.txt`. -/// info | "Informação" +/// info | Informação Na função `open()`, o `mode="a"` significa "acrescentar", então, a linha irá ser adicionada depois de qualquer coisa que esteja naquele arquivo, sem sobrescrever o conteúdo anterior. /// -/// tip | "Dica" +/// tip | Dica Perceba que nesse caso nós estamos usando a função padrão do Python `open()` que interage com um arquivo. @@ -165,7 +165,7 @@ Só um detalhe técnico para nerds curiosos. 🤓 Por baixo, na especificação técnica ASGI, essa é a parte do Protocolo Lifespan, e define eventos chamados `startup` e `shutdown`. -/// info | "Informação" +/// info | Informação Você pode ler mais sobre o manipulador `lifespan` do Starlette na Documentação do Lifespan Starlette. diff --git a/docs/pt/docs/advanced/index.md b/docs/pt/docs/advanced/index.md index 2569fc914..22ba2bf4a 100644 --- a/docs/pt/docs/advanced/index.md +++ b/docs/pt/docs/advanced/index.md @@ -6,7 +6,7 @@ O [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_bla Na próxima seção você verá outras opções, configurações, e recursos adicionais. -/// tip | "Dica" +/// tip | Dica As próximas seções **não são necessáriamente "avançadas"** diff --git a/docs/pt/docs/advanced/openapi-webhooks.md b/docs/pt/docs/advanced/openapi-webhooks.md index 5a0226c74..344fe6371 100644 --- a/docs/pt/docs/advanced/openapi-webhooks.md +++ b/docs/pt/docs/advanced/openapi-webhooks.md @@ -22,7 +22,7 @@ Com o **FastAPI**, utilizando o OpenAPI, você pode definir os nomes destes webh Isto pode facilitar bastante para os seus usuários **implementarem as APIs deles** para receber as requisições dos seus **webhooks**, eles podem inclusive ser capazes de gerar parte do código da API deles. -/// info | "Informação" +/// info | Informação Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do FastAPI a partir da versão `0.99.0`. @@ -38,7 +38,7 @@ Quando você cria uma aplicação com o **FastAPI**, existe um atributo chamado Os webhooks que você define aparecerão no esquema do **OpenAPI** e na **página de documentação** gerada automaticamente. -/// info | "Informação" +/// info | Informação O objeto `app.webhooks` é na verdade apenas um `APIRouter`, o mesmo tipo que você utilizaria ao estruturar a sua aplicação com diversos arquivos. diff --git a/docs/pt/docs/advanced/response-cookies.md b/docs/pt/docs/advanced/response-cookies.md index d0821b5b2..cd8f39db3 100644 --- a/docs/pt/docs/advanced/response-cookies.md +++ b/docs/pt/docs/advanced/response-cookies.md @@ -42,7 +42,7 @@ E também que você não esteja enviando nenhum dado que deveria ter sido filtra ### Mais informações -/// note | "Detalhes Técnicos" +/// note | Detalhes Técnicos Você também poderia usar `from starlette.responses import Response` ou `from starlette.responses import JSONResponse`. diff --git a/docs/pt/docs/advanced/response-headers.md b/docs/pt/docs/advanced/response-headers.md index d1958e46b..98a7e0b6d 100644 --- a/docs/pt/docs/advanced/response-headers.md +++ b/docs/pt/docs/advanced/response-headers.md @@ -28,7 +28,7 @@ Crie uma resposta conforme descrito em [Retornar uma resposta diretamente](respo {!../../docs_src/response_headers/tutorial001.py!} ``` -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Você também pode usar `from starlette.responses import Response` ou `from starlette.responses import JSONResponse`. diff --git a/docs/pt/docs/advanced/security/http-basic-auth.md b/docs/pt/docs/advanced/security/http-basic-auth.md index 26983a103..28c718f64 100644 --- a/docs/pt/docs/advanced/security/http-basic-auth.md +++ b/docs/pt/docs/advanced/security/http-basic-auth.md @@ -38,7 +38,7 @@ Então, quando você digitar o usuário e senha, o navegador os envia automatica //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Prefira utilizar a versão `Annotated` se possível. @@ -86,7 +86,7 @@ Então nós podemos utilizar o `secrets.compare_digest()` para garantir que o `c //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Prefira utilizar a versão `Annotated` se possível. @@ -179,7 +179,7 @@ Após detectar que as credenciais estão incorretas, retorne um `HTTPException` //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Prefira utilizar a versão `Annotated` se possível. diff --git a/docs/pt/docs/advanced/security/index.md b/docs/pt/docs/advanced/security/index.md index ae63f1c96..6c7becb67 100644 --- a/docs/pt/docs/advanced/security/index.md +++ b/docs/pt/docs/advanced/security/index.md @@ -4,7 +4,7 @@ Existem algumas funcionalidades adicionais para lidar com segurança além das cobertas em [Tutorial - Guia de Usuário: Segurança](../../tutorial/security/index.md){.internal-link target=_blank}. -/// tip | "Dica" +/// tip | Dica As próximas seções **não são necessariamente "avançadas"**. diff --git a/docs/pt/docs/advanced/security/oauth2-scopes.md b/docs/pt/docs/advanced/security/oauth2-scopes.md index fa4594c89..49fb75944 100644 --- a/docs/pt/docs/advanced/security/oauth2-scopes.md +++ b/docs/pt/docs/advanced/security/oauth2-scopes.md @@ -10,7 +10,7 @@ Toda vez que você "se autentica com" Facebook, Google, GitHub, Microsoft, Twitt Nesta seção, você verá como gerenciar a autenticação e autorização com os mesmos escopos do OAuth2 em sua aplicação **FastAPI**. -/// warning | "Aviso" +/// warning | Aviso Isso é uma seção mais ou menos avançada. Se você está apenas começando, você pode pular. @@ -308,7 +308,7 @@ E a função de dependência `get_current_active_user` também pode declarar sub Neste caso, ele requer o escopo `me` (poderia requerer mais de um escopo). -/// note | "Nota" +/// note | Nota Você não necessariamente precisa adicionar diferentes escopos em diferentes lugares. @@ -771,7 +771,7 @@ O mais comum é o fluxo implícito. O mais seguro é o fluxo de código, mas ele é mais complexo para implementar, pois ele necessita mais passos. Como ele é mais complexo, muitos provedores terminam sugerindo o fluxo implícito. -/// note | "Nota" +/// note | Nota É comum que cada provedor de autenticação nomeie os seus fluxos de forma diferente, para torná-lo parte de sua marca. diff --git a/docs/pt/docs/advanced/templates.md b/docs/pt/docs/advanced/templates.md index 88a5b940e..2314fed91 100644 --- a/docs/pt/docs/advanced/templates.md +++ b/docs/pt/docs/advanced/templates.md @@ -37,13 +37,13 @@ Além disso, em versões anteriores, o objeto `request` era passado como parte d /// -/// tip | "Dica" +/// tip | Dica Ao declarar `response_class=HTMLResponse`, a documentação entenderá que a resposta será HTML. /// -/// note | "Detalhes Técnicos" +/// note | Detalhes Técnicos Você também poderia usar `from starlette.templating import Jinja2Templates`. diff --git a/docs/pt/docs/advanced/testing-dependencies.md b/docs/pt/docs/advanced/testing-dependencies.md index f978350a5..94594e7e9 100644 --- a/docs/pt/docs/advanced/testing-dependencies.md +++ b/docs/pt/docs/advanced/testing-dependencies.md @@ -54,7 +54,7 @@ E então o **FastAPI** chamará a sobreposição no lugar da dependência origin //// tab | Python 3.10+ non-Annotated -/// tip | "Dica" +/// tip | Dica Prefira utilizar a versão `Annotated` se possível. @@ -68,7 +68,7 @@ Prefira utilizar a versão `Annotated` se possível. //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Prefira utilizar a versão `Annotated` se possível. @@ -80,7 +80,7 @@ Prefira utilizar a versão `Annotated` se possível. //// -/// tip | "Dica" +/// tip | Dica Você pode definir uma sobreposição de dependência para uma dependência que é utilizada em qualquer lugar da sua aplicação **FastAPI**. @@ -96,7 +96,7 @@ E então você pode redefinir as suas sobreposições (removê-las) definindo o app.dependency_overrides = {} ``` -/// tip | "Dica" +/// tip | Dica Se você quer sobrepor uma dependência apenas para alguns testes, você pode definir a sobreposição no início do testes (dentro da função de teste) e reiniciá-la ao final (no final da função de teste). diff --git a/docs/pt/docs/advanced/testing-websockets.md b/docs/pt/docs/advanced/testing-websockets.md index daa610df6..99e1a6db4 100644 --- a/docs/pt/docs/advanced/testing-websockets.md +++ b/docs/pt/docs/advanced/testing-websockets.md @@ -8,7 +8,7 @@ Para isso, você utiliza o `TestClient` dentro de uma instrução `with`, conect {!../../docs_src/app_testing/tutorial002.py!} ``` -/// note | "Nota" +/// note | Nota Para mais detalhes, confira a documentação do Starlette para testar WebSockets. diff --git a/docs/pt/docs/advanced/using-request-directly.md b/docs/pt/docs/advanced/using-request-directly.md index c2114c214..df7e01833 100644 --- a/docs/pt/docs/advanced/using-request-directly.md +++ b/docs/pt/docs/advanced/using-request-directly.md @@ -35,7 +35,7 @@ Para isso você precisa acessar a requisição diretamente. Ao declarar o parâmetro com o tipo sendo um `Request` em sua *função de operação de rota*, o **FastAPI** saberá como passar o `Request` neste parâmetro. -/// tip | "Dica" +/// tip | Dica Note que neste caso, nós estamos declarando o parâmetro da rota ao lado do parâmetro da requisição. @@ -49,7 +49,7 @@ Do mesmo jeito, você pode declarar qualquer outro parâmetro normalmente, e al Você pode ler mais sobre os detalhes do objeto `Request` no site da documentação oficial do Starlette.. -/// note | "Detalhes Técnicos" +/// note | Detalhes Técnicos Você também pode utilizar `from starlette.requests import Request`. diff --git a/docs/pt/docs/alternatives.md b/docs/pt/docs/alternatives.md index 2a2632bbc..29c9693bb 100644 --- a/docs/pt/docs/alternatives.md +++ b/docs/pt/docs/alternatives.md @@ -30,13 +30,13 @@ Ele é utilizado por muitas companhias incluindo Mozilla, Red Hat e Eventbrite. Ele foi um dos primeiros exemplos de **documentação automática de API**, e essa foi especificamente uma das primeiras idéias que inspirou "a busca por" **FastAPI**. -/// note | "Nota" +/// note | Nota Django REST Framework foi criado por Tom Christie. O mesmo criador de Starlette e Uvicorn, nos quais **FastAPI** é baseado. /// -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Ter uma documentação automática da API em interface web. @@ -56,7 +56,7 @@ Esse desacoplamento de partes, e sendo um "microframework" que pode ser extendid Dada a simplicidade do Flask, parecia uma ótima opção para construção de APIs. A próxima coisa a procurar era um "Django REST Framework" para Flask. -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Ser um microframework. Fazer ele fácil para misturar e combinar com ferramentas e partes necessárias. @@ -98,7 +98,7 @@ def read_url(): Veja as similaridades em `requests.get(...)` e `@app.get(...)`. -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para * Ter uma API simples e intuitiva. * Utilizar nomes de métodos HTTP (operações) diretamente, de um jeito direto e intuitivo. @@ -118,7 +118,7 @@ Em algum ponto, Swagger foi dado para a Fundação Linux, e foi renomeado OpenAP Isso acontece porquê quando alguém fala sobre a versão 2.0 é comum dizer "Swagger", e para a versão 3+, "OpenAPI". -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Adotar e usar um padrão aberto para especificações API, ao invés de algum esquema customizado. @@ -147,7 +147,7 @@ Esses recursos são o que Marshmallow foi construído para fornecer. Ele é uma Mas ele foi criado antes da existência do _type hints_ do Python. Então, para definir todo o _schema_ você precisa utilizar específicas ferramentas e classes fornecidas pelo Marshmallow. -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Usar código para definir "schemas" que forneçam, automaticamente, tipos de dados e validação. @@ -169,7 +169,7 @@ Webargs foi criado pelos mesmos desenvolvedores do Marshmallow. /// -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Ter validação automática de dados vindos de requisições. @@ -199,7 +199,7 @@ APISpec foi criado pelos mesmos desenvolvedores do Marshmallow. /// -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Dar suporte a padrões abertos para APIs, OpenAPI. @@ -231,7 +231,7 @@ Flask-apispec foi criado pelos mesmos desenvolvedores do Marshmallow. /// -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Gerar _schema_ OpenAPI automaticamente, a partir do mesmo código que define serialização e validação. @@ -251,7 +251,7 @@ Mas como os dados TypeScript não são preservados após a compilação para o J Ele também não controla modelos aninhados muito bem. Então, se o corpo JSON na requisição for um objeto JSON que contém campos internos que contém objetos JSON aninhados, ele não consegue ser validado e documentado apropriadamente. -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Usar tipos Python para ter um ótimo suporte do editor. @@ -263,7 +263,7 @@ Ter um sistema de injeção de dependência poderoso. Achar um jeito de minimiza Ele foi um dos primeiros frameworks Python extremamente rápido baseado em `asyncio`. Ele foi feito para ser muito similar ao Flask. -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Ele utiliza `uvloop` ao invés do '_loop_' `asyncio` padrão do Python. É isso que deixa ele tão rápido. @@ -271,7 +271,7 @@ Ele claramente inspirou Uvicorn e Starlette, que são atualmente mais rápidos q /// -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Achar um jeito de ter uma performance insana. @@ -289,7 +289,7 @@ Ele é projetado para ter funções que recebem dois parâmetros, uma "requisiç Então, validação de dados, serialização e documentação tem que ser feitos no código, não automaticamente. Ou eles terão que ser implementados como um framework acima do Falcon, como o Hug. Essa mesma distinção acontece em outros frameworks que são inspirados pelo design do Falcon, tendo um objeto de requisição e um objeto de resposta como parâmetros. -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Achar jeitos de conseguir melhor performance. @@ -315,7 +315,7 @@ O sistema de injeção de dependência exige pré-registro das dependências e a Rotas são declaradas em um único lugar, usando funções declaradas em outros lugares (ao invés de usar decoradores que possam ser colocados diretamente acima da função que controla o _endpoint_). Isso é mais perto de como o Django faz isso do que como Flask (e Starlette) faz. Ele separa no código coisas que são relativamente amarradas. -/// check | "**FastAPI** inspirado para" +/// check | **FastAPI** inspirado para Definir validações extras para tipos de dados usando valores "padrão" de atributos dos modelos. Isso melhora o suporte do editor, e não estava disponível no Pydantic antes. @@ -343,7 +343,7 @@ Hug foi criado por Timothy Crosley, o mesmo criador do -/// note | "Nota" +/// note | Nota O comando `uvicorn main:app` refere-se a: @@ -143,7 +143,7 @@ from main import app Cada programa de servidor ASGI alternativo teria um comando semelhante, você pode ler mais na documentação respectiva. -/// warning | "Aviso" +/// warning | Aviso Uvicorn e outros servidores suportam a opção `--reload` que é útil durante o desenvolvimento. diff --git a/docs/pt/docs/deployment/server-workers.md b/docs/pt/docs/deployment/server-workers.md index 0d6cd5b39..63eda56b4 100644 --- a/docs/pt/docs/deployment/server-workers.md +++ b/docs/pt/docs/deployment/server-workers.md @@ -17,7 +17,7 @@ Como você viu no capítulo anterior sobre [Conceitos de implantação](concepts Aqui mostrarei como usar o **Uvicorn** com **processos de trabalho** usando o comando `fastapi` ou o comando `uvicorn` diretamente. -/// info | "Informação" +/// info | Informação Se você estiver usando contêineres, por exemplo com Docker ou Kubernetes, falarei mais sobre isso no próximo capítulo: [FastAPI em contêineres - Docker](docker.md){.internal-link target=_blank}. diff --git a/docs/pt/docs/deployment/versions.md b/docs/pt/docs/deployment/versions.md index 79243a014..323ddbd45 100644 --- a/docs/pt/docs/deployment/versions.md +++ b/docs/pt/docs/deployment/versions.md @@ -42,7 +42,7 @@ Seguindo as convenções de controle de versão semântica, qualquer versão aba FastAPI também segue a convenção de que qualquer alteração de versão "PATCH" é para correção de bugs e alterações não significativas. -/// tip | "Dica" +/// tip | Dica O "PATCH" é o último número, por exemplo, em `0.2.3`, a versão PATCH é `3`. @@ -56,7 +56,7 @@ fastapi>=0.45.0,<0.46.0 Mudanças significativas e novos recursos são adicionados em versões "MINOR". -/// tip | "Dica" +/// tip | Dica O "MINOR" é o número que está no meio, por exemplo, em `0.2.3`, a versão MINOR é `2`. diff --git a/docs/pt/docs/environment-variables.md b/docs/pt/docs/environment-variables.md index 360d1c496..432f78af0 100644 --- a/docs/pt/docs/environment-variables.md +++ b/docs/pt/docs/environment-variables.md @@ -1,6 +1,6 @@ # Variáveis de Ambiente -/// tip | "Dica" +/// tip | Dica Se você já sabe o que são "variáveis de ambiente" e como usá-las, pode pular esta seção. @@ -63,7 +63,7 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -/// tip | "Dica" +/// tip | Dica O segundo argumento para `os.getenv()` é o valor padrão a ser retornado. @@ -151,7 +151,7 @@ Hello World from Python -/// tip | "Dica" +/// tip | Dica Você pode ler mais sobre isso em The Twelve-Factor App: Config. diff --git a/docs/pt/docs/help-fastapi.md b/docs/pt/docs/help-fastapi.md index 61eeac0dc..3d6e1f9d2 100644 --- a/docs/pt/docs/help-fastapi.md +++ b/docs/pt/docs/help-fastapi.md @@ -109,7 +109,7 @@ Assim podendo tentar ajudar a resolver essas questões. Entre no 👥 server de conversa do Discord 👥 e conheça novas pessoas da comunidade do FastAPI. -/// tip | "Dica" +/// tip | Dica Para perguntas, pergunte nas questões do GitHub, lá tem um chance maior de você ser ajudado sobre o FastAPI [FastAPI Experts](fastapi-people.md#especialistas){.internal-link target=_blank}. diff --git a/docs/pt/docs/how-to/graphql.md b/docs/pt/docs/how-to/graphql.md index 2cfd790c5..250135e23 100644 --- a/docs/pt/docs/how-to/graphql.md +++ b/docs/pt/docs/how-to/graphql.md @@ -4,7 +4,7 @@ Como o **FastAPI** é baseado no padrão **ASGI**, é muito fácil integrar qual Você pode combinar *operações de rota* normais do FastAPI com GraphQL na mesma aplicação. -/// tip | "Dica" +/// tip | Dica **GraphQL** resolve alguns casos de uso muito específicos. @@ -49,7 +49,7 @@ Versões anteriores do Starlette incluiam uma classe `GraphQLApp` para integrar Ela foi descontinuada do Starlette, mas se você tem código que a utilizava, você pode facilmente **migrar** para starlette-graphene3, que cobre o mesmo caso de uso e tem uma **interface quase idêntica**. -/// tip | "Dica" +/// tip | Dica Se você precisa de GraphQL, eu ainda recomendaria que você desse uma olhada no Strawberry, pois ele é baseado em type annotations em vez de classes e tipos personalizados. diff --git a/docs/pt/docs/tutorial/bigger-applications.md b/docs/pt/docs/tutorial/bigger-applications.md index fcc30961f..a094005fd 100644 --- a/docs/pt/docs/tutorial/bigger-applications.md +++ b/docs/pt/docs/tutorial/bigger-applications.md @@ -4,7 +4,7 @@ Se você está construindo uma aplicação ou uma API web, é raro que você pos **FastAPI** oferece uma ferramenta conveniente para estruturar sua aplicação, mantendo toda a flexibilidade. -/// info | "Informação" +/// info | Informação Se você vem do Flask, isso seria o equivalente aos Blueprints do Flask. @@ -29,7 +29,7 @@ Digamos que você tenha uma estrutura de arquivos como esta: │   └── admin.py ``` -/// tip | "Dica" +/// tip | Dica Existem vários arquivos `__init__.py` presentes em cada diretório ou subdiretório. @@ -105,7 +105,7 @@ Todas as mesmas opções são suportadas. Todos os mesmos `parameters`, `responses`, `dependencies`, `tags`, etc. -/// tip | "Dica" +/// tip | Dica Neste exemplo, a variável é chamada de `router`, mas você pode nomeá-la como quiser. @@ -139,7 +139,7 @@ Agora usaremos uma dependência simples para ler um cabeçalho `X-Token` persona //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Prefira usar a versão `Annotated` se possível. @@ -151,7 +151,7 @@ Prefira usar a versão `Annotated` se possível. //// -/// tip | "Dica" +/// tip | Dica Estamos usando um cabeçalho inventado para simplificar este exemplo. @@ -201,7 +201,7 @@ Também podemos adicionar uma lista de `tags` e `responses` extras que serão ap E podemos adicionar uma lista de `dependencies` que serão adicionadas a todas as *operações de rota* no roteador e serão executadas/resolvidas para cada solicitação feita a elas. -/// tip | "Dica" +/// tip | Dica Observe que, assim como [dependências em *decoradores de operação de rota*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, nenhum valor será passado para sua *função de operação de rota*. @@ -222,7 +222,7 @@ O resultado final é que os caminhos dos itens agora são: * As dependências do roteador são executadas primeiro, depois as [`dependencies` no decorador](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} e, em seguida, as dependências de parâmetros normais. * Você também pode adicionar [dependências de `Segurança` com `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}. -/// tip | "Dica" +/// tip | Dica Ter `dependências` no `APIRouter` pode ser usado, por exemplo, para exigir autenticação para um grupo inteiro de *operações de rota*. Mesmo que as dependências não sejam adicionadas individualmente a cada uma delas. @@ -248,7 +248,7 @@ Então usamos uma importação relativa com `..` para as dependências: #### Como funcionam as importações relativas -/// tip | "Dica" +/// tip | Dica Se você sabe perfeitamente como funcionam as importações, continue para a próxima seção abaixo. @@ -319,7 +319,7 @@ Mas ainda podemos adicionar _mais_ `tags` que serão aplicadas a uma *operação {!../../docs_src/bigger_applications/app/routers/items.py!} ``` -/// tip | "Dica" +/// tip | Dica Esta última operação de caminho terá a combinação de tags: `["items", "custom"]`. @@ -381,7 +381,7 @@ Também poderíamos importá-los como: from app.routers import items, users ``` -/// info | "Informação" +/// info | Informação A primeira versão é uma "importação relativa": @@ -428,7 +428,7 @@ Agora, vamos incluir os `roteadores` dos submódulos `usuários` e `itens`: {!../../docs_src/bigger_applications/app/main.py!} ``` -/// info | "Informação" +/// info | Informação `users.router` contém o `APIRouter` dentro do arquivo `app/routers/users.py`. @@ -440,7 +440,7 @@ Com `app.include_router()` podemos adicionar cada `APIRouter` ao aplicativo prin Ele incluirá todas as rotas daquele roteador como parte dele. -/// note | "Detalhe Técnico" +/// note | Detalhe Técnico Na verdade, ele criará internamente uma *operação de rota* para cada *operação de rota* que foi declarada no `APIRouter`. @@ -503,7 +503,7 @@ Aqui fazemos isso... só para mostrar que podemos 🤷: e funcionará corretamente, junto com todas as outras *operações de rota* adicionadas com `app.include_router()`. -/// info | "Detalhes Técnicos" +/// info | Detalhes Técnicos **Observação**: este é um detalhe muito técnico que você provavelmente pode **simplesmente pular**. diff --git a/docs/pt/docs/tutorial/body-fields.md b/docs/pt/docs/tutorial/body-fields.md index ab9377fdb..ac0b85ab5 100644 --- a/docs/pt/docs/tutorial/body-fields.md +++ b/docs/pt/docs/tutorial/body-fields.md @@ -10,7 +10,7 @@ Primeiro, você tem que importá-lo: {!../../docs_src/body_fields/tutorial001.py!} ``` -/// warning | "Aviso" +/// warning | Aviso Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como todo o resto (`Query`, `Path`, `Body`, etc). @@ -26,7 +26,7 @@ Você pode então utilizar `Field` com atributos do modelo: `Field` funciona da mesma forma que `Query`, `Path` e `Body`, ele possui todos os mesmos parâmetros, etc. -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Na realidade, `Query`, `Path` e outros que você verá em seguida, criam objetos de subclasses de uma classe `Param` comum, que é ela mesma uma subclasse da classe `FieldInfo` do Pydantic. @@ -38,7 +38,7 @@ Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse /// -/// tip | "Dica" +/// tip | Dica Note como cada atributo do modelo com um tipo, valor padrão e `Field` possuem a mesma estrutura que parâmetros de *funções de operações de rota*, com `Field` ao invés de `Path`, `Query` e `Body`. diff --git a/docs/pt/docs/tutorial/body-multiple-params.md b/docs/pt/docs/tutorial/body-multiple-params.md index 400813a7b..ad4931b11 100644 --- a/docs/pt/docs/tutorial/body-multiple-params.md +++ b/docs/pt/docs/tutorial/body-multiple-params.md @@ -24,7 +24,7 @@ E você também pode declarar parâmetros de corpo como opcionais, definindo o v //// -/// note | "Nota" +/// note | Nota Repare que, neste caso, o `item` que seria capturado a partir do corpo é opcional. Visto que ele possui `None` como valor padrão. @@ -80,7 +80,7 @@ Então, ele usará o nome dos parâmetros como chaves (nome dos campos) no corpo } ``` -/// note | "Nota" +/// note | Nota Repare que mesmo que o `item` esteja declarado da mesma maneira que antes, agora é esperado que ele esteja dentro do corpo com uma chave `item`. @@ -170,7 +170,7 @@ Por exemplo: //// -/// info | "Informação" +/// info | Informação `Body` também possui todas as validações adicionais e metadados de parâmetros como em `Query`,`Path` e outras que você verá depois. diff --git a/docs/pt/docs/tutorial/body-nested-models.md b/docs/pt/docs/tutorial/body-nested-models.md index 3aa79d563..bbe72a744 100644 --- a/docs/pt/docs/tutorial/body-nested-models.md +++ b/docs/pt/docs/tutorial/body-nested-models.md @@ -165,7 +165,7 @@ Isso vai esperar(converter, validar, documentar, etc) um corpo JSON tal qual: } ``` -/// info | "informação" +/// info | informação Note como o campo `images` agora tem uma lista de objetos de image. @@ -179,7 +179,7 @@ Você pode definir modelos profundamente aninhados de forma arbitrária: {!../../docs_src/body_nested_models/tutorial007.py!} ``` -/// info | "informação" +/// info | informação Note como `Offer` tem uma lista de `Item`s, que por sua vez possui opcionalmente uma lista `Image`s @@ -232,7 +232,7 @@ Neste caso, você aceitaria qualquer `dict`, desde que tenha chaves` int` com va {!../../docs_src/body_nested_models/tutorial009.py!} ``` -/// tip | "Dica" +/// tip | Dica Leve em condideração que o JSON só suporta `str` como chaves. diff --git a/docs/pt/docs/tutorial/body.md b/docs/pt/docs/tutorial/body.md index 429e4fd5a..f3a1fda75 100644 --- a/docs/pt/docs/tutorial/body.md +++ b/docs/pt/docs/tutorial/body.md @@ -8,7 +8,7 @@ Sua API quase sempre irá enviar um corpo na **resposta**. Mas os clientes não Para declarar um corpo da **requisição**, você utiliza os modelos do Pydantic com todos os seus poderes e benefícios. -/// info | "Informação" +/// info | Informação Para enviar dados, você deve usar utilizar um dos métodos: `POST` (Mais comum), `PUT`, `DELETE` ou `PATCH`. @@ -113,7 +113,7 @@ Mas você terá o mesmo suporte do editor no -/// tip | "Dica" +/// tip | Dica Se você utiliza o PyCharm como editor, você pode utilizar o Plugin do Pydantic para o PyCharm . @@ -161,7 +161,7 @@ Os parâmetros da função serão reconhecidos conforme abaixo: * Se o parâmetro é de um **tipo único** (como `int`, `float`, `str`, `bool`, etc) será interpretado como um parâmetro de **consulta**. * Se o parâmetro é declarado como um **modelo Pydantic**, será interpretado como o **corpo** da requisição. -/// note | "Observação" +/// note | Observação O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. diff --git a/docs/pt/docs/tutorial/cors.md b/docs/pt/docs/tutorial/cors.md index 16c4e9bf5..326101bd2 100644 --- a/docs/pt/docs/tutorial/cors.md +++ b/docs/pt/docs/tutorial/cors.md @@ -78,7 +78,7 @@ Qualquer solicitação com um cabeçalho `Origin`. Neste caso, o middleware pass Para mais informações CORS, acesse Mozilla CORS documentation. -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Você também pode usar `from starlette.middleware.cors import CORSMiddleware`. diff --git a/docs/pt/docs/tutorial/debugging.md b/docs/pt/docs/tutorial/debugging.md index 6bac7eb85..fca162988 100644 --- a/docs/pt/docs/tutorial/debugging.md +++ b/docs/pt/docs/tutorial/debugging.md @@ -74,7 +74,7 @@ Então, a linha: não será executada. -/// info | "Informação" +/// info | Informação Para mais informações, consulte a documentação oficial do Python. diff --git a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md index 179bfefb5..fcf71d08c 100644 --- a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md @@ -32,7 +32,7 @@ No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injet //// tab | Python 3.10+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -46,7 +46,7 @@ Utilize a versão com `Annotated` se possível. //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -145,7 +145,7 @@ Então, podemos mudar o "injetável" na dependência `common_parameters` acima p //// tab | Python 3.10+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -159,7 +159,7 @@ Utilize a versão com `Annotated` se possível. //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -199,7 +199,7 @@ Observe o método `__init__` usado para criar uma instância da classe: //// tab | Python 3.10+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -213,7 +213,7 @@ Utilize a versão com `Annotated` se possível. //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -253,7 +253,7 @@ Utilize a versão com `Annotated` se possível. //// tab | Python 3.10+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -267,7 +267,7 @@ Utilize a versão com `Annotated` se possível. //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -319,7 +319,7 @@ Agora você pode declarar sua dependência utilizando essa classe. //// tab | Python 3.10+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -333,7 +333,7 @@ Utilize a versão com `Annotated` se possível. //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -361,7 +361,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -397,7 +397,7 @@ commons: Annotated[CommonQueryParams, ... //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -423,7 +423,7 @@ commons: Annotated[Any, Depends(CommonQueryParams)] //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -463,7 +463,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.10+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -477,7 +477,7 @@ Utilize a versão com `Annotated` se possível. //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -507,7 +507,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -535,7 +535,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -559,7 +559,7 @@ commons: Annotated[CommonQueryParams, Depends()] //// tab | Python 3.8 non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -601,7 +601,7 @@ O mesmo exemplo ficaria então dessa forma: //// tab | Python 3.10+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -615,7 +615,7 @@ Utilize a versão com `Annotated` se possível. //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível. @@ -629,7 +629,7 @@ Utilize a versão com `Annotated` se possível. ...e o **FastAPI** saberá o que fazer. -/// tip | "Dica" +/// tip | Dica Se isso parece mais confuso do que útil, não utilize, você não *precisa* disso. diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 7d7086945..89c34855e 100644 --- a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -32,7 +32,7 @@ Ele deve ser uma lista de `Depends()`: //// tab | Python 3.8 non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível @@ -46,7 +46,7 @@ Utilize a versão com `Annotated` se possível Essas dependências serão executadas/resolvidas da mesma forma que dependências comuns. Mas o valor delas (se existir algum) não será passado para a sua *função de operação de rota*. -/// tip | "Dica" +/// tip | Dica Alguns editores de texto checam parâmetros de funções não utilizados, e os mostram como erros. @@ -56,7 +56,7 @@ Isso também pode ser útil para evitar confundir novos desenvolvedores que ao v /// -/// info | "Informação" +/// info | Informação Neste exemplo utilizamos cabeçalhos personalizados inventados `X-Keys` e `X-Token`. @@ -90,7 +90,7 @@ Dependências podem declarar requisitos de requisições (como cabeçalhos) ou o //// tab | Python 3.8 non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível @@ -124,7 +124,7 @@ Essas dependências podem levantar exceções, da mesma forma que dependências //// tab | Python 3.8 non-Annotated -/// tip | "Dica" +/// tip | Dica Utilize a versão com `Annotated` se possível @@ -160,7 +160,7 @@ Então, você pode reutilizar uma dependência comum (que retorna um valor) que //// tab | Python 3.8 non-Annotated -/// tip | "Dica" +/// tip | Dica diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md index d90bebe39..90c1e02e0 100644 --- a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,13 +4,13 @@ O FastAPI possui suporte para dependências que realizam . @@ -43,7 +43,7 @@ Mas se você tiver cabeçalhos personalizados desejando que um cliente em um nav /// -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Você também pode usar `from starlette.requests import Request`. diff --git a/docs/pt/docs/tutorial/path-operation-configuration.md b/docs/pt/docs/tutorial/path-operation-configuration.md index 48753d725..5f3cc82fb 100644 --- a/docs/pt/docs/tutorial/path-operation-configuration.md +++ b/docs/pt/docs/tutorial/path-operation-configuration.md @@ -2,7 +2,7 @@ Existem vários parâmetros que você pode passar para o seu *decorador de operação de rota* para configurá-lo. -/// warning | "Aviso" +/// warning | Aviso Observe que esses parâmetros são passados diretamente para o *decorador de operação de rota*, não para a sua *função de operação de rota*. @@ -42,7 +42,7 @@ Mas se você não se lembrar o que cada código numérico significa, pode usar a Esse código de status será usado na resposta e será adicionado ao esquema OpenAPI. -/// note | "Detalhes Técnicos" +/// note | Detalhes Técnicos Você também poderia usar `from starlette import status`. @@ -185,7 +185,7 @@ Você pode especificar a descrição da resposta com o parâmetro `response_desc //// -/// info | "Informação" +/// info | Informação Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral. diff --git a/docs/pt/docs/tutorial/path-params-numeric-validations.md b/docs/pt/docs/tutorial/path-params-numeric-validations.md index 28c55482f..3361f86c5 100644 --- a/docs/pt/docs/tutorial/path-params-numeric-validations.md +++ b/docs/pt/docs/tutorial/path-params-numeric-validations.md @@ -44,7 +44,7 @@ Por exemplo para declarar um valor de metadado `title` para o parâmetro de rota //// -/// note | "Nota" +/// note | Nota Um parâmetro de rota é sempre obrigatório, como se fizesse parte da rota. @@ -132,7 +132,7 @@ E você também pode declarar validações numéricas: * `lt`: menor que (`l`ess `t`han) * `le`: menor que ou igual (`l`ess than or `e`qual) -/// info | "Informação" +/// info | Informação `Query`, `Path` e outras classes que você verá a frente são subclasses de uma classe comum `Param`. @@ -140,7 +140,7 @@ Todas elas compartilham os mesmos parâmetros para validação adicional e metad /// -/// note | "Detalhes Técnicos" +/// note | Detalhes Técnicos Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções. diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md index a68354a1b..64f8a0253 100644 --- a/docs/pt/docs/tutorial/path-params.md +++ b/docs/pt/docs/tutorial/path-params.md @@ -24,7 +24,7 @@ Você pode declarar o tipo de um parâmetro na função usando as anotações pa Nesse caso, `item_id` está sendo declarado como um `int`. -/// check | "Verifique" +/// check | Verifique @@ -40,7 +40,7 @@ Se você rodar esse exemplo e abrir o seu navegador em http://127.0.0.1:8000/items/4.2 -/// check | "Verifique" +/// check | Verifique @@ -91,7 +91,7 @@ Quando você abrir o seu navegador em -/// check | "Verifique" +/// check | Verifique @@ -151,13 +151,13 @@ Assim, crie atributos de classe com valores fixos, que serão os valores válido {!../../docs_src/path_params/tutorial005.py!} ``` -/// info | "informação" +/// info | informação Enumerations (ou enums) estão disponíveis no Python desde a versão 3.4. /// -/// tip | "Dica" +/// tip | Dica @@ -199,7 +199,7 @@ Você pode ter o valor exato de enumerate (um `str` nesse caso) usando `model_na {!../../docs_src/path_params/tutorial005.py!} ``` -/// tip | "Dica" +/// tip | Dica @@ -258,7 +258,7 @@ Então, você poderia usar ele com: {!../../docs_src/path_params/tutorial004.py!} ``` -/// tip | "Dica" +/// tip | Dica diff --git a/docs/pt/docs/tutorial/query-params-str-validations.md b/docs/pt/docs/tutorial/query-params-str-validations.md index e6dcf748e..2fa0eeba0 100644 --- a/docs/pt/docs/tutorial/query-params-str-validations.md +++ b/docs/pt/docs/tutorial/query-params-str-validations.md @@ -10,7 +10,7 @@ Vamos utilizar essa aplicação como exemplo: O parâmetro de consulta `q` é do tipo `Union[str, None]`, o que significa que é do tipo `str` mas que também pode ser `None`, e de fato, o valor padrão é `None`, então o FastAPI saberá que não é obrigatório. -/// note | "Observação" +/// note | Observação O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. @@ -54,7 +54,7 @@ q: Union[str, None] = None Mas o declara explicitamente como um parâmetro de consulta. -/// info | "Informação" +/// info | Informação Tenha em mente que o FastAPI se preocupa com a parte: @@ -118,7 +118,7 @@ Vamos dizer que você queira que o parâmetro de consulta `q` tenha um `min_leng {!../../docs_src/query_params_str_validations/tutorial005.py!} ``` -/// note | "Observação" +/// note | Observação O parâmetro torna-se opcional quando possui um valor padrão. @@ -150,7 +150,7 @@ Então, quando você precisa declarar um parâmetro obrigatório utilizando o `Q {!../../docs_src/query_params_str_validations/tutorial006.py!} ``` -/// info | "Informação" +/// info | Informação Se você nunca viu os `...` antes: é um valor único especial, faz parte do Python e é chamado "Ellipsis". @@ -187,7 +187,7 @@ Assim, a resposta para essa URL seria: } ``` -/// tip | "Dica" +/// tip | Dica Para declarar um parâmetro de consulta com o tipo `list`, como no exemplo acima, você precisa usar explicitamente o `Query`, caso contrário será interpretado como um corpo da requisição. @@ -230,7 +230,7 @@ Você também pode utilizar o tipo `list` diretamente em vez de `List[str]`: {!../../docs_src/query_params_str_validations/tutorial013.py!} ``` -/// note | "Observação" +/// note | Observação Tenha em mente que neste caso, o FastAPI não irá validar os conteúdos da lista. @@ -244,7 +244,7 @@ Você pode adicionar mais informações sobre o parâmetro. Essa informações serão inclusas no esquema do OpenAPI e utilizado pela documentação interativa e ferramentas externas. -/// note | "Observação" +/// note | Observação Tenha em mente que cada ferramenta oferece diferentes níveis de suporte ao OpenAPI. diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md index 6e6699cd5..89b951de6 100644 --- a/docs/pt/docs/tutorial/query-params.md +++ b/docs/pt/docs/tutorial/query-params.md @@ -81,7 +81,7 @@ Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo Nesse caso, o parâmetro da função `q` será opcional, e `None` será o padrão. -/// check | "Verificar" +/// check | Verificar Você também pode notar que o **FastAPI** é esperto o suficiente para perceber que o parâmetro da rota `item_id` é um parâmetro da rota, e `q` não é, portanto, `q` é o parâmetro de consulta. @@ -239,7 +239,7 @@ Nesse caso, existem 3 parâmetros de consulta: * `skip`, um `int` com o valor padrão `0`. * `limit`, um `int` opcional. -/// tip | "Dica" +/// tip | Dica Você também poderia usar `Enum` da mesma forma que com [Path Parameters](path-params.md#valores-predefinidos){.internal-link target=_blank}. diff --git a/docs/pt/docs/tutorial/request-files.md b/docs/pt/docs/tutorial/request-files.md index d230f1feb..c22c1c513 100644 --- a/docs/pt/docs/tutorial/request-files.md +++ b/docs/pt/docs/tutorial/request-files.md @@ -103,7 +103,7 @@ Quando você usa os métodos `async`, o **FastAPI** executa os métodos de arqui /// -/// note | "Detalhes Técnicos do Starlette" +/// note | Detalhes Técnicos do Starlette O `UploadFile` do ***FastAPI** herda diretamente do `UploadFile` do **Starlette** , mas adiciona algumas partes necessárias para torná-lo compatível com o **Pydantic** e as outras partes do FastAPI. @@ -115,7 +115,7 @@ O jeito que os formulários HTML (`
`) enviam os dados para o servid **FastAPI** se certificará de ler esses dados do lugar certo, ao invés de JSON. -/// note | "Detalhes Técnicos" +/// note | Detalhes Técnicos Dados de formulários normalmente são codificados usando o "media type" (tipo de mídia) `application/x-www-form-urlencoded` quando não incluem arquivos. @@ -157,7 +157,7 @@ Para usar isso, declare uma lista de `bytes` ou `UploadFile`: Você receberá, tal como declarado, uma `list` de `bytes` ou `UploadFile`. -/// note | "Detalhes Técnicos" +/// note | Detalhes Técnicos Você pode também pode usar `from starlette.responses import HTMLResponse`. diff --git a/docs/pt/docs/tutorial/request-form-models.md b/docs/pt/docs/tutorial/request-form-models.md index 837e24c34..7128a0ae2 100644 --- a/docs/pt/docs/tutorial/request-form-models.md +++ b/docs/pt/docs/tutorial/request-form-models.md @@ -2,7 +2,7 @@ Você pode utilizar **Modelos Pydantic** para declarar **campos de formulários** no FastAPI. -/// info | "Informação" +/// info | Informação Para utilizar formulários, instale primeiramente o `python-multipart`. @@ -14,7 +14,7 @@ $ pip install python-multipart /// -/// note | "Nota" +/// note | Nota Isto é suportado desde a versão `0.113.0` do FastAPI. 🤓 @@ -42,7 +42,7 @@ Você precisa apenas declarar um **modelo Pydantic** com os campos que deseja re //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Prefira utilizar a versão `Annotated` se possível. @@ -68,7 +68,7 @@ Você pode verificar na UI de documentação em `/docs`: Em alguns casos de uso especiais (provavelmente não muito comum), você pode desejar **restringir** os campos do formulário para aceitar apenas os declarados no modelo Pydantic. E **proibir** qualquer campo **extra**. -/// note | "Nota" +/// note | Nota Isso é suportado deste a versão `0.114.0` do FastAPI. 🤓 diff --git a/docs/pt/docs/tutorial/request-forms-and-files.md b/docs/pt/docs/tutorial/request-forms-and-files.md index 29488b4f2..77c099eb3 100644 --- a/docs/pt/docs/tutorial/request-forms-and-files.md +++ b/docs/pt/docs/tutorial/request-forms-and-files.md @@ -2,7 +2,7 @@ Você pode definir arquivos e campos de formulário ao mesmo tempo usando `File` e `Form`. -/// info | "Informação" +/// info | Informação Para receber arquivos carregados e/ou dados de formulário, primeiro instale `python-multipart`. @@ -28,7 +28,7 @@ Os arquivos e campos de formulário serão carregados como dados de formulário E você pode declarar alguns dos arquivos como `bytes` e alguns como `UploadFile`. -/// warning | "Aviso" +/// warning | Aviso Você pode declarar vários parâmetros `File` e `Form` em uma *operação de caminho*, mas não é possível declarar campos `Body` para receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`. diff --git a/docs/pt/docs/tutorial/request-forms.md b/docs/pt/docs/tutorial/request-forms.md index 1e2faf269..367fca072 100644 --- a/docs/pt/docs/tutorial/request-forms.md +++ b/docs/pt/docs/tutorial/request-forms.md @@ -2,7 +2,7 @@ Quando você precisar receber campos de formulário ao invés de JSON, você pode usar `Form`. -/// info | "Informação" +/// info | Informação Para usar formulários, primeiro instale `python-multipart`. @@ -32,13 +32,13 @@ A spec exige que os campos sejam exatamente Com `Form` você pode declarar os mesmos metadados e validação que com `Body` (e `Query`, `Path`, `Cookie`). -/// info | "Informação" +/// info | Informação `Form` é uma classe que herda diretamente de `Body`. /// -/// tip | "Dica" +/// tip | Dica Para declarar corpos de formulário, você precisa usar `Form` explicitamente, porque sem ele os parâmetros seriam interpretados como parâmetros de consulta ou parâmetros de corpo (JSON). @@ -50,7 +50,7 @@ A forma como os formulários HTML (`
`) enviam os dados para o servi O **FastAPI** fará a leitura desses dados no lugar certo em vez de JSON. -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Os dados dos formulários são normalmente codificados usando o "tipo de mídia" `application/x-www-form-urlencoded`. @@ -60,7 +60,7 @@ Se você quiser ler mais sobre essas codificações e campos de formulário, vá /// -/// warning | "Aviso" +/// warning | Aviso Você pode declarar vários parâmetros `Form` em uma *operação de caminho*, mas não pode declarar campos `Body` que espera receber como JSON, pois a solicitação terá o corpo codificado usando `application/x-www- form-urlencoded` em vez de `application/json`. diff --git a/docs/pt/docs/tutorial/response-status-code.md b/docs/pt/docs/tutorial/response-status-code.md index bc4a2cd34..2c8924925 100644 --- a/docs/pt/docs/tutorial/response-status-code.md +++ b/docs/pt/docs/tutorial/response-status-code.md @@ -12,7 +12,7 @@ Da mesma forma que você pode especificar um modelo de resposta, você também p {!../../docs_src/response_status_code/tutorial001.py!} ``` -/// note | "Nota" +/// note | Nota Observe que `status_code` é um parâmetro do método "decorador" (get, post, etc). Não da sua função de *operação de caminho*, como todos os parâmetros e corpo. @@ -20,7 +20,7 @@ Observe que `status_code` é um parâmetro do método "decorador" (get, post, et O parâmetro `status_code` recebe um número com o código de status HTTP. -/// info | "Informação" +/// info | Informação `status_code` também pode receber um `IntEnum`, como o do Python `http.HTTPStatus`. @@ -33,7 +33,7 @@ Dessa forma: -/// note | "Nota" +/// note | Nota Alguns códigos de resposta (consulte a próxima seção) indicam que a resposta não possui um corpo. @@ -43,7 +43,7 @@ O FastAPI sabe disso e produzirá documentos OpenAPI informando que não há cor ## Sobre os códigos de status HTTP -/// note | "Nota" +/// note | Nota Se você já sabe o que são códigos de status HTTP, pule para a próxima seção. @@ -67,7 +67,7 @@ Resumidamente: * Para erros genéricos do cliente, você pode usar apenas `400`. * `500` e acima são para erros do servidor. Você quase nunca os usa diretamente. Quando algo der errado em alguma parte do código do seu aplicativo ou servidor, ele retornará automaticamente um desses códigos de status. -/// tip | "Dica" +/// tip | Dica Para saber mais sobre cada código de status e qual código serve para quê, verifique o MDN documentação sobre códigos de status HTTP. @@ -95,7 +95,7 @@ Eles são apenas uma conveniência, eles possuem o mesmo número, mas dessa form -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Você também pode usar `from starlette import status`. diff --git a/docs/pt/docs/tutorial/schema-extra-example.md b/docs/pt/docs/tutorial/schema-extra-example.md index 2d78e4ef1..dd95d4c7d 100644 --- a/docs/pt/docs/tutorial/schema-extra-example.md +++ b/docs/pt/docs/tutorial/schema-extra-example.md @@ -14,7 +14,7 @@ Você pode declarar um `example` para um modelo Pydantic usando `Config` e `sche Essas informações extras serão adicionadas como se encontram no **JSON Schema** de resposta desse modelo e serão usadas na documentação da API. -/// tip | "Dica" +/// tip | Dica Você pode usar a mesma técnica para estender o JSON Schema e adicionar suas próprias informações extras de forma personalizada. @@ -32,7 +32,7 @@ Você pode usar isso para adicionar um `example` para cada campo: {!../../docs_src/schema_extra_example/tutorial002.py!} ``` -/// warning | "Atenção" +/// warning | Atenção Lembre-se de que esses argumentos extras passados ​​não adicionarão nenhuma validação, apenas informações extras, para fins de documentação. @@ -91,7 +91,7 @@ Com `examples` adicionado a `Body()`, os `/docs` vão ficar assim: ## Detalhes técnicos -/// warning | "Atenção" +/// warning | Atenção Esses são detalhes muito técnicos sobre os padrões **JSON Schema** e **OpenAPI**. diff --git a/docs/pt/docs/tutorial/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md index 9fb94fe67..02871c90a 100644 --- a/docs/pt/docs/tutorial/security/first-steps.md +++ b/docs/pt/docs/tutorial/security/first-steps.md @@ -25,7 +25,7 @@ Copie o exemplo em um arquivo `main.py`: ## Execute-o -/// info | "informação" +/// info | informação @@ -57,7 +57,7 @@ Você verá algo deste tipo: -/// check | "Botão de Autorizar!" +/// check | Botão de Autorizar! @@ -71,7 +71,7 @@ E se você clicar, você terá um pequeno formulário de autorização para digi -/// note | "Nota" +/// note | Nota @@ -119,7 +119,7 @@ Então, vamos rever de um ponto de vista simplificado: Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um token **Bearer**. Fazemos isso usando a classe `OAuth2PasswordBearer`. -/// info | "informação" +/// info | informação @@ -139,7 +139,7 @@ Quando nós criamos uma instância da classe `OAuth2PasswordBearer`, nós passam {!../../docs_src/security/tutorial001.py!} ``` -/// tip | "Dica" +/// tip | Dica @@ -155,7 +155,7 @@ Esse parâmetro não cria um endpoint / *path operation*, mas declara que a URL Em breve também criaremos o atual path operation. -/// info | "informação" +/// info | informação @@ -187,7 +187,7 @@ Esse dependência vai fornecer uma `str` que é atribuído ao parâmetro `token A **FastAPI** saberá que pode usar essa dependência para definir um "esquema de segurança" no esquema da OpenAPI (e na documentação da API automática). -/// info | "Detalhes técnicos" +/// info | Detalhes técnicos diff --git a/docs/pt/docs/tutorial/security/index.md b/docs/pt/docs/tutorial/security/index.md index 2f23aa47e..b4440ec04 100644 --- a/docs/pt/docs/tutorial/security/index.md +++ b/docs/pt/docs/tutorial/security/index.md @@ -32,7 +32,7 @@ Não é muito popular ou usado nos dias atuais. OAuth2 não especifica como criptografar a comunicação, ele espera que você tenha sua aplicação em um servidor HTTPS. -/// tip | "Dica" +/// tip | Dica Na seção sobre **deployment** você irá ver como configurar HTTPS de modo gratuito, usando Traefik e Let’s Encrypt. @@ -89,7 +89,7 @@ OpenAPI define os seguintes esquemas de segurança: * Essa descoberta automática é o que é definido na especificação OpenID Connect. -/// tip | "Dica" +/// tip | Dica Integração com outros provedores de autenticação/autorização como Google, Facebook, Twitter, GitHub, etc. é bem possível e relativamente fácil. diff --git a/docs/pt/docs/tutorial/static-files.md b/docs/pt/docs/tutorial/static-files.md index 901fca1d2..aba4b8221 100644 --- a/docs/pt/docs/tutorial/static-files.md +++ b/docs/pt/docs/tutorial/static-files.md @@ -11,7 +11,7 @@ Você pode servir arquivos estáticos automaticamente de um diretório usando `S {!../../docs_src/static_files/tutorial001.py!} ``` -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Você também pode usar `from starlette.staticfiles import StaticFiles`. diff --git a/docs/pt/docs/tutorial/testing.md b/docs/pt/docs/tutorial/testing.md index 4e28a43c0..4f8eaa299 100644 --- a/docs/pt/docs/tutorial/testing.md +++ b/docs/pt/docs/tutorial/testing.md @@ -8,7 +8,7 @@ Com ele, você pode usar o `httpx`. @@ -34,7 +34,7 @@ Escreva instruções `assert` simples com as expressões Python padrão que voc {!../../docs_src/app_testing/tutorial001.py!} ``` -/// tip | "Dica" +/// tip | Dica Observe que as funções de teste são `def` normais, não `async def`. @@ -44,7 +44,7 @@ Isso permite que você use `pytest` diretamente sem complicações. /// -/// note | "Detalhes técnicos" +/// note | Detalhes técnicos Você também pode usar `from starlette.testclient import TestClient`. @@ -52,7 +52,7 @@ Você também pode usar `from starlette.testclient import TestClient`. /// -/// tip | "Dica" +/// tip | Dica Se você quiser chamar funções `async` em seus testes além de enviar solicitações ao seu aplicativo FastAPI (por exemplo, funções de banco de dados assíncronas), dê uma olhada em [Testes assíncronos](../advanced/async-tests.md){.internal-link target=_blank} no tutorial avançado. @@ -152,7 +152,7 @@ Ambas as *operações de rotas* requerem um cabeçalho `X-Token`. //// tab | Python 3.10+ non-Annotated -/// tip | "Dica" +/// tip | Dica Prefira usar a versão `Annotated` se possível. @@ -166,7 +166,7 @@ Prefira usar a versão `Annotated` se possível. //// tab | Python 3.8+ non-Annotated -/// tip | "Dica" +/// tip | Dica Prefira usar a versão `Annotated` se possível. @@ -200,7 +200,7 @@ Por exemplo: Para mais informações sobre como passar dados para o backend (usando `httpx` ou `TestClient`), consulte a documentação do HTTPX. -/// info | "Informação" +/// info | Informação Observe que o `TestClient` recebe dados que podem ser convertidos para JSON, não para modelos Pydantic. diff --git a/docs/pt/docs/virtual-environments.md b/docs/pt/docs/virtual-environments.md index 863c8d65e..5fc1a8866 100644 --- a/docs/pt/docs/virtual-environments.md +++ b/docs/pt/docs/virtual-environments.md @@ -2,13 +2,13 @@ Ao trabalhar em projetos Python, você provavelmente deve usar um **ambiente virtual** (ou um mecanismo similar) para isolar os pacotes que você instala para cada projeto. -/// info | "Informação" +/// info | Informação Se você já sabe sobre ambientes virtuais, como criá-los e usá-los, talvez seja melhor pular esta seção. 🤓 /// -/// tip | "Dica" +/// tip | Dica Um **ambiente virtual** é diferente de uma **variável de ambiente**. @@ -18,7 +18,7 @@ Um **ambiente virtual** é um diretório com alguns arquivos. /// -/// info | "Informação" +/// info | Informação Esta página lhe ensinará como usar **ambientes virtuais** e como eles funcionam. @@ -55,7 +55,7 @@ $ cd awesome-project Ao começar a trabalhar em um projeto Python **pela primeira vez**, crie um ambiente virtual **dentro do seu projeto**. -/// tip | "Dica" +/// tip | Dica Você só precisa fazer isso **uma vez por projeto**, não toda vez que trabalhar. @@ -96,7 +96,7 @@ $ uv venv -/// tip | "Dica" +/// tip | Dica Por padrão, `uv` criará um ambiente virtual em um diretório chamado `.venv`. @@ -118,7 +118,7 @@ Você pode criar o ambiente virtual em um diretório diferente, mas há uma conv Ative o novo ambiente virtual para que qualquer comando Python que você executar ou pacote que você instalar o utilize. -/// tip | "Dica" +/// tip | Dica Faça isso **toda vez** que iniciar uma **nova sessão de terminal** para trabalhar no projeto. @@ -162,7 +162,7 @@ $ source .venv/Scripts/activate //// -/// tip | "Dica" +/// tip | Dica Toda vez que você instalar um **novo pacote** naquele ambiente, **ative** o ambiente novamente. @@ -174,7 +174,7 @@ Isso garante que, se você usar um **programa de terminal (`uv`, você o usará para instalar coisas em vez do `pip`, então não precisará atualizar o `pip`. 😎 @@ -224,7 +224,7 @@ Se você estiver usando `pip` para instalar pacotes (ele vem por padrão com o P Muitos erros exóticos durante a instalação de um pacote são resolvidos apenas atualizando o `pip` primeiro. -/// tip | "Dica" +/// tip | Dica Normalmente, você faria isso **uma vez**, logo após criar o ambiente virtual. @@ -246,13 +246,13 @@ $ python -m pip install --upgrade pip Se você estiver usando **Git** (você deveria), adicione um arquivo `.gitignore` para excluir tudo em seu `.venv` do Git. -/// tip | "Dica" +/// tip | Dica Se você usou `uv` para criar o ambiente virtual, ele já fez isso para você, você pode pular esta etapa. 😎 /// -/// tip | "Dica" +/// tip | Dica Faça isso **uma vez**, logo após criar o ambiente virtual. @@ -286,7 +286,7 @@ Esse comando criará um arquivo `.gitignore` com o conteúdo: Após ativar o ambiente, você pode instalar pacotes nele. -/// tip | "Dica" +/// tip | Dica Faça isso **uma vez** ao instalar ou atualizar os pacotes que seu projeto precisa. @@ -298,7 +298,7 @@ Se precisar atualizar uma versão ou adicionar um novo pacote, você **fará iss Se estiver com pressa e não quiser usar um arquivo para declarar os requisitos de pacote do seu projeto, você pode instalá-los diretamente. -/// tip | "Dica" +/// tip | Dica É uma (muito) boa ideia colocar os pacotes e versões que seu programa precisa em um arquivo (por exemplo `requirements.txt` ou `pyproject.toml`). @@ -399,7 +399,7 @@ Por exemplo: * VS Code * PyCharm -/// tip | "Dica" +/// tip | Dica Normalmente, você só precisa fazer isso **uma vez**, ao criar o ambiente virtual. @@ -425,7 +425,7 @@ Agora você está pronto para começar a trabalhar no seu projeto. -/// tip | "Dica" +/// tip | Dica Você quer entender o que é tudo isso acima? @@ -516,7 +516,7 @@ flowchart LR end ``` -/// tip | "Dica" +/// tip | Dica É muito comum em pacotes Python tentar ao máximo **evitar alterações drásticas** em **novas versões**, mas é melhor prevenir do que remediar e instalar versões mais recentes intencionalmente e, quando possível, executar os testes para verificar se tudo está funcionando corretamente. @@ -623,7 +623,7 @@ Esse comando criará ou modificará algumas [variáveis ​​de ambiente](envir Uma dessas variáveis ​​é a variável `PATH`. -/// tip | "Dica" +/// tip | Dica Você pode aprender mais sobre a variável de ambiente `PATH` na seção [Variáveis ​​de ambiente](environment-variables.md#path-environment-variable){.internal-link target=_blank}. @@ -756,7 +756,7 @@ A parte mais importante é que quando você chama ``python`, esse é exatamente Assim, você pode confirmar se está no ambiente virtual correto. -/// tip | "Dica" +/// tip | Dica É fácil ativar um ambiente virtual, obter um Python e então **ir para outro projeto**. diff --git a/docs/ru/docs/alternatives.md b/docs/ru/docs/alternatives.md index f83024ad9..3c5147e79 100644 --- a/docs/ru/docs/alternatives.md +++ b/docs/ru/docs/alternatives.md @@ -33,14 +33,14 @@ DRF использовался многими компаниями, включа Это был один из первых примеров **автоматического документирования API** и это была одна из первых идей, вдохновивших на создание **FastAPI**. -/// note | "Заметка" +/// note | Заметка Django REST Framework был создан Tom Christie. Он же создал Starlette и Uvicorn, на которых основан **FastAPI**. /// -/// check | "Идея для **FastAPI**" +/// check | Идея для **FastAPI** Должно быть автоматическое создание документации API с пользовательским веб-интерфейсом. @@ -62,7 +62,7 @@ Flask часто используется и для приложений, кот Простота Flask, показалась мне подходящей для создания API. Но ещё нужно было найти "Django REST Framework" для Flask. -/// check | "Идеи для **FastAPI**" +/// check | Идеи для **FastAPI** Это будет микрофреймворк. К нему легко будет добавить необходимые инструменты и части. @@ -108,7 +108,7 @@ def read_url(): Глядите, как похоже `requests.get(...)` и `@app.get(...)`. -/// check | "Идеи для **FastAPI**" +/// check | Идеи для **FastAPI** * Должен быть простой и понятный API. * Нужно использовать названия HTTP-методов (операций) для упрощения понимания происходящего. @@ -129,7 +129,7 @@ def read_url(): Вот почему, когда говорят о версии 2.0, обычно говорят "Swagger", а для версии 3+ "OpenAPI". -/// check | "Идеи для **FastAPI**" +/// check | Идеи для **FastAPI** Использовать открытые стандарты для спецификаций API вместо самодельных схем. @@ -165,7 +165,7 @@ def read_url(): Итак, чтобы определить каждую схему, Вам нужно использовать определенные утилиты и классы, предоставляемые Marshmallow. -/// check | "Идея для **FastAPI**" +/// check | Идея для **FastAPI** Использовать код программы для автоматического создания "схем", определяющих типы данных и их проверку. @@ -181,13 +181,13 @@ Webargs - это инструмент, который был создан для Это превосходный инструмент и я тоже часто пользовался им до **FastAPI**. -/// info | "Информация" +/// info | Информация Webargs бы создан разработчиками Marshmallow. /// -/// check | "Идея для **FastAPI**" +/// check | Идея для **FastAPI** Должна быть автоматическая проверка входных данных. @@ -212,13 +212,13 @@ Marshmallow и Webargs осуществляют проверку, анализ Редактор кода не особо может помочь в такой парадигме. А изменив какие-то параметры или схемы для Marshmallow можно забыть отредактировать докстринг с YAML и сгенерированная схема становится недействительной. -/// info | "Информация" +/// info | Информация APISpec тоже был создан авторами Marshmallow. /// -/// check | "Идея для **FastAPI**" +/// check | Идея для **FastAPI** Необходима поддержка открытого стандарта для API - OpenAPI. @@ -246,13 +246,13 @@ APISpec тоже был создан авторами Marshmallow. Эти генераторы проектов также стали основой для [Генераторов проектов с **FastAPI**](project-generation.md){.internal-link target=_blank}. -/// info | "Информация" +/// info | Информация Как ни странно, но Flask-apispec тоже создан авторами Marshmallow. /// -/// check | "Идея для **FastAPI**" +/// check | Идея для **FastAPI** Схема OpenAPI должна создаваться автоматически и использовать тот же код, который осуществляет сериализацию и проверку данных. @@ -276,7 +276,7 @@ APISpec тоже был создан авторами Marshmallow. Кроме того, он не очень хорошо справляется с вложенными моделями. Если в запросе имеется объект JSON, внутренние поля которого, в свою очередь, являются вложенными объектами JSON, это не может быть должным образом задокументировано и проверено. -/// check | "Идеи для **FastAPI** " +/// check | Идеи для **FastAPI** Нужно использовать подсказки типов, чтоб воспользоваться поддержкой редактора кода. @@ -289,7 +289,7 @@ APISpec тоже был создан авторами Marshmallow. Sanic был одним из первых чрезвычайно быстрых Python-фреймворков основанных на `asyncio`. Он был сделан очень похожим на Flask. -/// note | "Технические детали" +/// note | Технические детали В нём использован `uvloop` вместо стандартного цикла событий `asyncio`, что и сделало его таким быстрым. @@ -297,7 +297,7 @@ Sanic был одним из первых чрезвычайно быстрых /// -/// check | "Идеи для **FastAPI**" +/// check | Идеи для **FastAPI** Должна быть сумасшедшая производительность. @@ -318,7 +318,7 @@ Falcon - ещё один высокопроизводительный Python-ф Либо эти функции должны быть встроены во фреймворк, сконструированный поверх Falcon, как в Hug. Такая же особенность присутствует и в других фреймворках, вдохновлённых идеей Falcon, использовать только один объект запроса и один объект ответа. -/// check | "Идея для **FastAPI**" +/// check | Идея для **FastAPI** Найдите способы добиться отличной производительности. @@ -348,7 +348,7 @@ Molten мне попался на начальной стадии написан Это больше похоже на Django, чем на Flask и Starlette. Он разделяет в коде вещи, которые довольно тесно связаны. -/// check | "Идея для **FastAPI**" +/// check | Идея для **FastAPI** Определить дополнительные проверки типов данных, используя значения атрибутов модели "по умолчанию". Это улучшает помощь редактора и раньше это не было доступно в Pydantic. @@ -374,13 +374,13 @@ Hug был одним из первых фреймворков, реализов Поскольку он основан на WSGI, старом стандарте для синхронных веб-фреймворков, он не может работать с веб-сокетами и другими модными штуками, но всё равно обладает высокой производительностью. -/// info | "Информация" +/// info | Информация Hug создан Timothy Crosley, автором `isort`, отличного инструмента для автоматической сортировки импортов в Python-файлах. /// -/// check | "Идеи для **FastAPI**" +/// check | Идеи для **FastAPI** Hug повлиял на создание некоторых частей APIStar и был одним из инструментов, которые я счел наиболее многообещающими, наряду с APIStar. @@ -418,7 +418,7 @@ Hug вдохновил **FastAPI** объявить параметр `ответ Ныне APIStar - это набор инструментов для проверки спецификаций OpenAPI. -/// info | "Информация" +/// info | Информация APIStar был создан Tom Christie. Тот самый парень, который создал: @@ -428,7 +428,7 @@ APIStar был создан Tom Christie. Тот самый парень, кот /// -/// check | "Идеи для **FastAPI**" +/// check | Идеи для **FastAPI** Воплощение. @@ -452,7 +452,7 @@ Pydantic - это библиотека для валидации данных, Его можно сравнить с Marshmallow, хотя в бенчмарках Pydantic быстрее, чем Marshmallow. И он основан на тех же подсказках типов, которые отлично поддерживаются редакторами кода. -/// check | "**FastAPI** использует Pydantic" +/// check | **FastAPI** использует Pydantic Для проверки данных, сериализации данных и автоматической документации моделей (на основе JSON Schema). @@ -488,7 +488,7 @@ Starlette обеспечивает весь функционал микрофр **FastAPI** добавляет эти функции используя подсказки типов Python и Pydantic. Ещё **FastAPI** добавляет систему внедрения зависимостей, утилиты безопасности, генерацию схемы OpenAPI и т.д. -/// note | "Технические детали" +/// note | Технические детали ASGI - это новый "стандарт" разработанный участниками команды Django. Он пока что не является "стандартом в Python" (то есть принятым PEP), но процесс принятия запущен. @@ -498,7 +498,7 @@ ASGI - это новый "стандарт" разработанный учас /// -/// check | "**FastAPI** использует Starlette" +/// check | **FastAPI** использует Starlette В качестве ядра веб-сервиса для обработки запросов, добавив некоторые функции сверху. @@ -518,7 +518,7 @@ Uvicorn является сервером, а не фреймворком. Он рекомендуется в качестве сервера для Starlette и **FastAPI**. -/// check | "**FastAPI** рекомендует его" +/// check | **FastAPI** рекомендует его Как основной сервер для запуска приложения **FastAPI**. diff --git a/docs/ru/docs/contributing.md b/docs/ru/docs/contributing.md index c4370f9bb..67034ad03 100644 --- a/docs/ru/docs/contributing.md +++ b/docs/ru/docs/contributing.md @@ -106,7 +106,7 @@ $ python -m pip install --upgrade pip -/// tip | "Подсказка" +/// tip | Подсказка Каждый раз, перед установкой новой библиотеки в виртуальное окружение при помощи `pip`, не забудьте активировать это виртуальное окружение. @@ -162,7 +162,7 @@ $ bash scripts/format.sh Также существуют дополнительные инструменты/скрипты для работы с переводами в `./scripts/docs.py`. -/// tip | "Подсказка" +/// tip | Подсказка Нет необходимости заглядывать в `./scripts/docs.py`, просто используйте это в командной строке. @@ -254,7 +254,7 @@ $ uvicorn tutorial001:app --reload * Проверьте существующие пул-реквесты для Вашего языка. Добавьте отзывы с просьбой внести изменения, если они необходимы, или одобрите их. -/// tip | "Подсказка" +/// tip | Подсказка Вы можете добавлять комментарии с предложениями по изменению в существующие пул-реквесты. @@ -282,7 +282,7 @@ $ uvicorn tutorial001:app --reload Кодом испанского языка является `es`. А значит директория для переводов на испанский язык: `docs/es/`. -/// tip | "Подсказка" +/// tip | Подсказка Главный ("официальный") язык - английский, директория для него `docs/en/`. @@ -325,7 +325,7 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -/// tip | "Подсказка" +/// tip | Подсказка Заметьте, что в пути файла мы изменили только код языка с `en` на `es`. @@ -400,7 +400,7 @@ Updating en После чего Вы можете проверить в своем редакторе кода, что появился новый каталог `docs/ht/`. -/// tip | "Подсказка" +/// tip | Подсказка Создайте первый пул-реквест, который будет содержать только пустую директорию для нового языка, прежде чем добавлять переводы. diff --git a/docs/ru/docs/deployment/concepts.md b/docs/ru/docs/deployment/concepts.md index c41025790..7cdc29526 100644 --- a/docs/ru/docs/deployment/concepts.md +++ b/docs/ru/docs/deployment/concepts.md @@ -151,7 +151,7 @@ Для случаев, когда ошибки приводят к сбою в запущенном **процессе**, Вам понадобится добавить компонент, который **перезапустит** процесс хотя бы пару раз... -/// tip | "Заметка" +/// tip | Заметка ... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания. @@ -241,7 +241,7 @@ * **Облачные сервисы**, которые позаботятся обо всём за Вас * Возможно, что облачный сервис умеет **управлять запуском дополнительных экземпляров приложения**. Вероятно, он потребует, чтоб вы указали - какой **процесс** или **образ** следует клонировать. Скорее всего, вы укажете **один процесс Uvicorn** и облачный сервис будет запускать его копии при необходимости. -/// tip | "Заметка" +/// tip | Заметка Если вы не знаете, что такое **контейнеры**, Docker или Kubernetes, не переживайте. @@ -263,7 +263,7 @@ Безусловно, возможны случаи, когда нет проблем при выполнении предварительной подготовки параллельно или несколько раз. Тогда Вам повезло, работать с ними намного проще. -/// tip | "Заметка" +/// tip | Заметка Имейте в виду, что в некоторых случаях запуск вашего приложения **может не требовать каких-либо предварительных шагов вовсе**. @@ -281,7 +281,7 @@ * Bash-скрипт, выполняющий предварительные шаги, а затем запускающий приложение. * При этом Вам всё ещё нужно найти способ - как запускать/перезапускать *такой* bash-скрипт, обнаруживать ошибки и т.п. -/// tip | "Заметка" +/// tip | Заметка Я приведу Вам больше конкретных примеров работы с контейнерами в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}. diff --git a/docs/ru/docs/deployment/docker.md b/docs/ru/docs/deployment/docker.md index 9eef5c4d2..31da01b78 100644 --- a/docs/ru/docs/deployment/docker.md +++ b/docs/ru/docs/deployment/docker.md @@ -4,7 +4,7 @@ Использование контейнеров на основе Linux имеет ряд преимуществ, включая **безопасность**, **воспроизводимость**, **простоту** и прочие. -/// tip | "Подсказка" +/// tip | Подсказка Торопитесь или уже знакомы с этой технологией? Перепрыгните на раздел [Создать Docker-образ для FastAPI 👇](#docker-fastapi) @@ -135,7 +135,7 @@ Successfully installed fastapi pydantic uvicorn -/// info | "Информация" +/// info | Информация Существуют и другие инструменты управления зависимостями. @@ -231,7 +231,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Так как команда выполняется внутри директории `/code`, в которую мы поместили папку `./app` с приложением, то **Uvicorn** сможет найти и **импортировать** объект `app` из файла `app.main`. -/// tip | "Подсказка" +/// tip | Подсказка Если ткнёте на кружок с плюсом, то увидите пояснения. 👆 @@ -306,7 +306,7 @@ $ docker build -t myimage . -/// tip | "Подсказка" +/// tip | Подсказка Обратите внимание, что в конце написана точка - `.`, это то же самое что и `./`, тем самым мы указываем Docker директорию, из которой нужно выполнять сборку образа контейнера. @@ -410,7 +410,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Это может быть другой контейнер, в котором есть, например, Traefik, работающий с **HTTPS** и **самостоятельно** обновляющий **сертификаты**. -/// tip | "Подсказка" +/// tip | Подсказка Traefik совместим с Docker, Kubernetes и им подобными инструментами. Он очень прост в установке и настройке использования HTTPS для Ваших контейнеров. @@ -442,7 +442,7 @@ Traefik совместим с Docker, Kubernetes и им подобными ин Поскольку этот компонент **принимает запросы** и равномерно **распределяет** их между компонентами, его также называют **балансировщиком нагрузки**. -/// tip | "Подсказка" +/// tip | Подсказка **Прокси-сервер завершения работы TLS** одновременно может быть **балансировщиком нагрузки**. @@ -525,7 +525,7 @@ Traefik совместим с Docker, Kubernetes и им подобными ин Когда вы запускаете **множество контейнеров**, в каждом из которых работает **только один процесс** (например, в кластере **Kubernetes**), может возникнуть необходимость иметь **отдельный контейнер**, который осуществит **предварительные шаги перед запуском** остальных контейнеров (например, применяет миграции к базе данных). -/// info | "Информация" +/// info | Информация При использовании Kubernetes, это может быть Инициализирующий контейнер. @@ -545,7 +545,7 @@ Traefik совместим с Docker, Kubernetes и им подобными ин * tiangolo/uvicorn-gunicorn-fastapi. -/// warning | "Предупреждение" +/// warning | Предупреждение Скорее всего у вас **нет необходимости** в использовании этого образа или подобного ему и лучше создать свой образ с нуля как описано тут: [Создать Docker-образ для FastAPI](#docker-fastapi). @@ -557,7 +557,7 @@ Traefik совместим с Docker, Kubernetes и им подобными ин Он также поддерживает прохождение **Подготовительных шагов при запуске контейнеров** при помощи скрипта. -/// tip | "Подсказка" +/// tip | Подсказка Для просмотра всех возможных настроек перейдите на страницу этого Docker-образа: tiangolo/uvicorn-gunicorn-fastapi. @@ -689,7 +689,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. Запустите `uvicorn`, указав ему использовать объект `app`, расположенный в `app.main`. -/// tip | "Подсказка" +/// tip | Подсказка Если ткнёте на кружок с плюсом, то увидите объяснения, что происходит в этой строке. diff --git a/docs/ru/docs/deployment/https.md b/docs/ru/docs/deployment/https.md index 3d487c465..85c4cce60 100644 --- a/docs/ru/docs/deployment/https.md +++ b/docs/ru/docs/deployment/https.md @@ -4,7 +4,7 @@ Но всё несколько сложнее. -/// tip | "Заметка" +/// tip | Заметка Если вы торопитесь или вам не интересно, можете перейти на следующую страницу этого пошагового руководства по размещению приложений на серверах с использованием различных технологий. @@ -78,7 +78,7 @@ Обычно эту запись достаточно указать один раз, при первоначальной настройке всего сервера. -/// tip | "Заметка" +/// tip | Заметка Уровни протоколов, работающих с именами доменов, намного ниже HTTPS, но об этом следует упомянуть здесь, так как всё зависит от доменов и IP-адресов. @@ -128,7 +128,7 @@ DNS-сервера присылают браузеру определённый Таким образом, **HTTPS** это тот же **HTTP**, но внутри **безопасного TLS-соединения** вместо чистого (незашифрованного) TCP-соединения. -/// tip | "Заметка" +/// tip | Заметка Обратите внимание, что шифрование происходит на **уровне TCP**, а не на более высоком уровне HTTP. diff --git a/docs/ru/docs/deployment/manually.md b/docs/ru/docs/deployment/manually.md index 78363cef8..9b1d32be8 100644 --- a/docs/ru/docs/deployment/manually.md +++ b/docs/ru/docs/deployment/manually.md @@ -39,7 +39,7 @@ $ pip install "uvicorn[standard]" -/// tip | "Подсказка" +/// tip | Подсказка С опцией `standard`, Uvicorn будет устанавливаться и использоваться с некоторыми дополнительными рекомендованными зависимостями. @@ -99,7 +99,7 @@ Running on 0.0.0.0:8080 over http (CTRL + C to quit) //// -/// warning | "Предупреждение" +/// warning | Предупреждение Не забудьте удалить опцию `--reload`, если ранее пользовались ею. diff --git a/docs/ru/docs/deployment/versions.md b/docs/ru/docs/deployment/versions.md index 17b6446d9..e8db30ce8 100644 --- a/docs/ru/docs/deployment/versions.md +++ b/docs/ru/docs/deployment/versions.md @@ -42,7 +42,7 @@ fastapi>=0.45.0,<0.46.0 FastAPI следует соглашению в том, что любые изменения "ПАТЧ"-версии предназначены для исправления багов и внесения обратно совместимых изменений. -/// tip | "Подсказка" +/// tip | Подсказка "ПАТЧ" - это последнее число. Например, в `0.2.3`, ПАТЧ-версия - это `3`. @@ -56,7 +56,7 @@ fastapi>=0.45.0,<0.46.0 Обратно несовместимые изменения и новые функции добавляются в "МИНОРНЫЕ" версии. -/// tip | "Подсказка" +/// tip | Подсказка "МИНОРНАЯ" версия - это число в середине. Например, в `0.2.3` МИНОРНАЯ версия - это `2`. diff --git a/docs/ru/docs/features.md b/docs/ru/docs/features.md index 31f245e7a..77d6b936a 100644 --- a/docs/ru/docs/features.md +++ b/docs/ru/docs/features.md @@ -66,7 +66,7 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -/// info | "Информация" +/// info | Информация `**second_user_data` означает: diff --git a/docs/ru/docs/help-fastapi.md b/docs/ru/docs/help-fastapi.md index fa8200817..474b3d689 100644 --- a/docs/ru/docs/help-fastapi.md +++ b/docs/ru/docs/help-fastapi.md @@ -162,7 +162,7 @@ * Затем, используя **комментарий**, сообщите, что Вы сделали проверку, тогда я буду знать, что Вы действительно проверили код. -/// info | "Информация" +/// info | Информация К сожалению, я не могу так просто доверять пул-реквестам, у которых уже есть несколько одобрений. @@ -221,7 +221,7 @@ Подключайтесь к 👥 чату в Discord 👥 и общайтесь с другими участниками сообщества FastAPI. -/// tip | "Подсказка" +/// tip | Подсказка Вопросы по проблемам с фреймворком лучше задавать в GitHub issues, так больше шансов, что Вы получите помощь от [Экспертов FastAPI](fastapi-people.md#_3){.internal-link target=_blank}. diff --git a/docs/ru/docs/tutorial/body-fields.md b/docs/ru/docs/tutorial/body-fields.md index f3b2c6113..0c4cbb09c 100644 --- a/docs/ru/docs/tutorial/body-fields.md +++ b/docs/ru/docs/tutorial/body-fields.md @@ -22,7 +22,7 @@ //// -/// warning | "Внимание" +/// warning | Внимание Обратите внимание, что функция `Field` импортируется непосредственно из `pydantic`, а не из `fastapi`, как все остальные функции (`Query`, `Path`, `Body` и т.д.). @@ -50,7 +50,7 @@ Функция `Field` работает так же, как `Query`, `Path` и `Body`, у неё такие же параметры и т.д. -/// note | "Технические детали" +/// note | Технические детали На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic. @@ -62,7 +62,7 @@ /// -/// tip | "Подсказка" +/// tip | Подсказка Обратите внимание, что каждый атрибут модели с типом, значением по умолчанию и `Field` имеет ту же структуру, что и параметр *функции обработки пути* с `Field` вместо `Path`, `Query` и `Body`. @@ -75,7 +75,7 @@ Вы узнаете больше о добавлении дополнительной информации позже в документации, когда будете изучать, как задавать примеры принимаемых данных. -/// warning | "Внимание" +/// warning | Внимание Дополнительные ключи, переданные в функцию `Field`, также будут присутствовать в сгенерированной OpenAPI схеме вашего приложения. Поскольку эти ключи не являются обязательной частью спецификации OpenAPI, некоторые инструменты OpenAPI, например, [валидатор OpenAPI](https://validator.swagger.io/), могут не работать с вашей сгенерированной схемой. diff --git a/docs/ru/docs/tutorial/body-multiple-params.md b/docs/ru/docs/tutorial/body-multiple-params.md index 53965f0ec..594e1dbca 100644 --- a/docs/ru/docs/tutorial/body-multiple-params.md +++ b/docs/ru/docs/tutorial/body-multiple-params.md @@ -34,7 +34,7 @@ //// tab | Python 3.10+ non-Annotated -/// tip | "Заметка" +/// tip | Заметка Рекомендуется использовать `Annotated` версию, если это возможно. @@ -48,7 +48,7 @@ //// tab | Python 3.8+ non-Annotated -/// tip | "Заметка" +/// tip | Заметка Рекомендуется использовать версию с `Annotated`, если это возможно. @@ -60,7 +60,7 @@ //// -/// note | "Заметка" +/// note | Заметка Заметьте, что в данном случае параметр `item`, который будет взят из тела запроса, необязателен. Так как было установлено значение `None` по умолчанию. @@ -116,7 +116,7 @@ } ``` -/// note | "Внимание" +/// note | Внимание Обратите внимание, что хотя параметр `item` был объявлен таким же способом, как и раньше, теперь предпологается, что он находится внутри тела с ключом `item`. @@ -162,7 +162,7 @@ //// tab | Python 3.10+ non-Annotated -/// tip | "Заметка" +/// tip | Заметка Рекомендуется использовать `Annotated` версию, если это возможно. @@ -176,7 +176,7 @@ //// tab | Python 3.8+ non-Annotated -/// tip | "Заметка" +/// tip | Заметка Рекомендуется использовать `Annotated` версию, если это возможно. @@ -252,7 +252,7 @@ q: str | None = None //// tab | Python 3.10+ non-Annotated -/// tip | "Заметка" +/// tip | Заметка Рекомендуется использовать `Annotated` версию, если это возможно. @@ -266,7 +266,7 @@ q: str | None = None //// tab | Python 3.8+ non-Annotated -/// tip | "Заметка" +/// tip | Заметка Рекомендуется использовать `Annotated` версию, если это возможно. @@ -278,7 +278,7 @@ q: str | None = None //// -/// info | "Информация" +/// info | Информация `Body` также имеет все те же дополнительные параметры валидации и метаданных, как у `Query`,`Path` и других, которые вы увидите позже. @@ -324,7 +324,7 @@ item: Item = Body(embed=True) //// tab | Python 3.10+ non-Annotated -/// tip | "Заметка" +/// tip | Заметка Рекомендуется использовать `Annotated` версию, если это возможно. @@ -338,7 +338,7 @@ item: Item = Body(embed=True) //// tab | Python 3.8+ non-Annotated -/// tip | "Заметка" +/// tip | Заметка Рекомендуется использовать `Annotated` версию, если это возможно. diff --git a/docs/ru/docs/tutorial/body-nested-models.md b/docs/ru/docs/tutorial/body-nested-models.md index 780946725..9abd4f432 100644 --- a/docs/ru/docs/tutorial/body-nested-models.md +++ b/docs/ru/docs/tutorial/body-nested-models.md @@ -304,7 +304,7 @@ my_list: List[str] } ``` -/// info | "Информация" +/// info | Информация Заметьте, что теперь у ключа `images` есть список объектов изображений. @@ -338,7 +338,7 @@ my_list: List[str] //// -/// info | "Информация" +/// info | Информация Заметьте, что у объекта `Offer` есть список объектов `Item`, которые, в свою очередь, могут содержать необязательный список объектов `Image` @@ -420,7 +420,7 @@ images: list[Image] //// -/// tip | "Совет" +/// tip | Совет Имейте в виду, что JSON поддерживает только ключи типа `str`. diff --git a/docs/ru/docs/tutorial/body-updates.md b/docs/ru/docs/tutorial/body-updates.md index 3ecfe52f4..c80952f70 100644 --- a/docs/ru/docs/tutorial/body-updates.md +++ b/docs/ru/docs/tutorial/body-updates.md @@ -54,7 +54,7 @@ Это означает, что можно передавать только те данные, которые необходимо обновить, оставляя остальные нетронутыми. -/// note | "Технические детали" +/// note | Технические детали `PATCH` менее распространен и известен, чем `PUT`. @@ -167,7 +167,7 @@ //// -/// tip | "Подсказка" +/// tip | Подсказка Эту же технику можно использовать и для операции HTTP `PUT`. @@ -175,7 +175,7 @@ /// -/// note | "Технические детали" +/// note | Технические детали Обратите внимание, что входная модель по-прежнему валидируется. diff --git a/docs/ru/docs/tutorial/body.md b/docs/ru/docs/tutorial/body.md index 91b169d07..62927f0d1 100644 --- a/docs/ru/docs/tutorial/body.md +++ b/docs/ru/docs/tutorial/body.md @@ -8,7 +8,7 @@ Чтобы объявить тело **запроса**, необходимо использовать модели Pydantic, со всей их мощью и преимуществами. -/// info | "Информация" +/// info | Информация Чтобы отправить данные, необходимо использовать один из методов: `POST` (обычно), `PUT`, `DELETE` или `PATCH`. @@ -113,7 +113,7 @@ -/// tip | "Подсказка" +/// tip | Подсказка Если вы используете PyCharm в качестве редактора, то вам стоит попробовать плагин Pydantic PyCharm Plugin. @@ -161,7 +161,7 @@ * Если аннотация типа параметра содержит **примитивный тип** (`int`, `float`, `str`, `bool` и т.п.), он будет интерпретирован как параметр **запроса**. * Если аннотация типа параметра представляет собой **модель Pydantic**, он будет интерпретирован как параметр **тела запроса**. -/// note | "Заметка" +/// note | Заметка FastAPI понимает, что значение параметра `q` не является обязательным, потому что имеет значение по умолчанию `= None`. diff --git a/docs/ru/docs/tutorial/cookie-params.md b/docs/ru/docs/tutorial/cookie-params.md index 2a73a5918..88533f7f8 100644 --- a/docs/ru/docs/tutorial/cookie-params.md +++ b/docs/ru/docs/tutorial/cookie-params.md @@ -44,7 +44,7 @@ //// -/// note | "Технические детали" +/// note | Технические детали `Cookie` - это класс, родственный `Path` и `Query`. Он также наследуется от общего класса `Param`. @@ -52,7 +52,7 @@ /// -/// info | "Дополнительная информация" +/// info | Дополнительная информация Для объявления cookies, вам нужно использовать `Cookie`, иначе параметры будут интерпретированы как параметры запроса. diff --git a/docs/ru/docs/tutorial/cors.md b/docs/ru/docs/tutorial/cors.md index 8d415a2c1..622cd5a98 100644 --- a/docs/ru/docs/tutorial/cors.md +++ b/docs/ru/docs/tutorial/cors.md @@ -78,7 +78,7 @@ Для получения более подробной информации о CORS, обратитесь к Документации CORS от Mozilla. -/// note | "Технические детали" +/// note | Технические детали Вы также можете использовать `from starlette.middleware.cors import CORSMiddleware`. diff --git a/docs/ru/docs/tutorial/debugging.md b/docs/ru/docs/tutorial/debugging.md index 606a32bfc..0feeaa20c 100644 --- a/docs/ru/docs/tutorial/debugging.md +++ b/docs/ru/docs/tutorial/debugging.md @@ -74,7 +74,7 @@ from myapp import app не будет выполнена. -/// info | "Информация" +/// info | Информация Для получения дополнительной информации, ознакомьтесь с официальной документацией Python. diff --git a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md index 161101bb3..486ff9ea9 100644 --- a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md @@ -32,7 +32,7 @@ //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -46,7 +46,7 @@ //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -143,7 +143,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -157,7 +157,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -197,7 +197,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -211,7 +211,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -251,7 +251,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -265,7 +265,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -317,7 +317,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -331,7 +331,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -351,7 +351,7 @@ fluffy = Cat(name="Mr Fluffy") //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -395,7 +395,7 @@ commons: Annotated[CommonQueryParams, ... //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -421,7 +421,7 @@ commons: Annotated[Any, Depends(CommonQueryParams)] //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -461,7 +461,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -475,7 +475,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -497,7 +497,7 @@ commons = Depends(CommonQueryParams) //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -532,7 +532,7 @@ commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -556,7 +556,7 @@ commons: Annotated[CommonQueryParams, Depends()] //// tab | Python 3.6 без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -598,7 +598,7 @@ commons: CommonQueryParams = Depends() //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -612,7 +612,7 @@ commons: CommonQueryParams = Depends() //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -626,7 +626,7 @@ commons: CommonQueryParams = Depends() ...и **FastAPI** будет знать, что делать. -/// tip | "Подсказка" +/// tip | Подсказка Если это покажется вам более запутанным, чем полезным, не обращайте внимания, это вам не *нужно*. diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md index 99a86e999..83f8ec0d2 100644 --- a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,13 +4,13 @@ FastAPI поддерживает зависимости, которые выпо Для этого используйте `yield` вместо `return`, а дополнительный код напишите после него. -/// tip | "Подсказка" +/// tip | Подсказка Обязательно используйте `yield` один-единственный раз. /// -/// note | "Технические детали" +/// note | Технические детали Любая функция, с которой может работать: @@ -45,7 +45,7 @@ FastAPI поддерживает зависимости, которые выпо {!../../docs_src/dependencies/tutorial007.py!} ``` -/// tip | "Подсказка" +/// tip | Подсказка Можно использовать как `async` так и обычные функции. @@ -93,7 +93,7 @@ FastAPI поддерживает зависимости, которые выпо //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -129,7 +129,7 @@ FastAPI поддерживает зависимости, которые выпо //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -149,7 +149,7 @@ FastAPI поддерживает зависимости, которые выпо **FastAPI** проследит за тем, чтобы все выполнялось в правильном порядке. -/// note | "Технические детали" +/// note | Технические детали Это работает благодаря Контекстным менеджерам в Python. @@ -177,7 +177,7 @@ FastAPI поддерживает зависимости, которые выпо Если у вас есть пользовательские исключения, которые вы хотите обрабатывать *до* возврата ответа и, возможно, модифицировать ответ, даже вызывая `HTTPException`, создайте [Cобственный обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. -/// tip | "Подсказка" +/// tip | Подсказка Вы все еще можете вызывать исключения, включая `HTTPException`, *до* `yield`. Но не после. @@ -225,7 +225,7 @@ participant tasks as Background tasks end ``` -/// info | "Дополнительная информация" +/// info | Дополнительная информация Клиенту будет отправлен только **один ответ**. Это может быть один из ответов об ошибке или это будет ответ от *операции пути*. @@ -233,7 +233,7 @@ participant tasks as Background tasks /// -/// tip | "Подсказка" +/// tip | Подсказка На этой диаграмме показано "HttpException", но вы также можете вызвать любое другое исключение, для которого вы создаете [Пользовательский обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. @@ -243,7 +243,7 @@ participant tasks as Background tasks ## Зависимости с `yield`, `HTTPException` и фоновыми задачами -/// warning | "Внимание" +/// warning | Внимание Скорее всего, вам не нужны эти технические подробности, вы можете пропустить этот раздел и продолжить ниже. @@ -257,7 +257,7 @@ participant tasks as Background tasks Тем не менее, поскольку это означало бы ожидание ответа в сети, а также ненужное удержание ресурса в зависимости от доходности (например, соединение с базой данных), это было изменено в FastAPI 0.106.0. -/// tip | "Подсказка" +/// tip | Подсказка Кроме того, фоновая задача обычно представляет собой независимый набор логики, который должен обрабатываться отдельно, со своими собственными ресурсами (например, собственным подключением к базе данных). Таким образом, вы, вероятно, получите более чистый код. @@ -290,7 +290,7 @@ with open("./somefile.txt") as f: ### Использование менеджеров контекста в зависимостях с помощью `yield` -/// warning | "Внимание" +/// warning | Внимание Это более или менее "продвинутая" идея. @@ -307,7 +307,7 @@ with open("./somefile.txt") as f: {!../../docs_src/dependencies/tutorial010.py!} ``` -/// tip | "Подсказка" +/// tip | Подсказка Другой способ создания контекстного менеджера - с помощью: diff --git a/docs/ru/docs/tutorial/dependencies/global-dependencies.md b/docs/ru/docs/tutorial/dependencies/global-dependencies.md index 7dbd50ae1..a4dfeb8ac 100644 --- a/docs/ru/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/global-dependencies.md @@ -24,7 +24,7 @@ //// tab | Python 3.8 non-Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать 'Annotated' версию, если это возможно. diff --git a/docs/ru/docs/tutorial/dependencies/index.md b/docs/ru/docs/tutorial/dependencies/index.md index fcd9f46dc..b6cf7c780 100644 --- a/docs/ru/docs/tutorial/dependencies/index.md +++ b/docs/ru/docs/tutorial/dependencies/index.md @@ -55,7 +55,7 @@ //// tab | Python 3.10+ non-Annotated -/// tip | "Подсказка" +/// tip | Подсказка Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. @@ -69,7 +69,7 @@ //// tab | Python 3.8+ non-Annotated -/// tip | "Подсказка" +/// tip | Подсказка Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. @@ -99,7 +99,7 @@ И в конце она возвращает `dict`, содержащий эти значения. -/// info | "Информация" +/// info | Информация **FastAPI** добавил поддержку для `Annotated` (и начал её рекомендовать) в версии 0.95.0. @@ -137,7 +137,7 @@ //// tab | Python 3.10+ non-Annotated -/// tip | "Подсказка" +/// tip | Подсказка Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. @@ -151,7 +151,7 @@ //// tab | Python 3.8+ non-Annotated -/// tip | "Подсказка" +/// tip | Подсказка Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. @@ -193,7 +193,7 @@ //// tab | Python 3.10+ non-Annotated -/// tip | "Подсказка" +/// tip | Подсказка Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. @@ -207,7 +207,7 @@ //// tab | Python 3.8+ non-Annotated -/// tip | "Подсказка" +/// tip | Подсказка Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. @@ -225,7 +225,7 @@ И потом функция берёт параметры так же, как *функция обработки пути*. -/// tip | "Подсказка" +/// tip | Подсказка В следующей главе вы увидите, какие другие вещи, помимо функций, можно использовать в качестве зависимостей. @@ -250,7 +250,7 @@ common_parameters --> read_users Таким образом, вы пишете общий код один раз, и **FastAPI** позаботится о его вызове для ваших *операций с путями*. -/// check | "Проверка" +/// check | Проверка Обратите внимание, что вы не создаёте специальный класс и не передаёте его куда-то в **FastAPI** для регистрации, или что-то в этом роде. @@ -294,7 +294,7 @@ commons: Annotated[dict, Depends(common_parameters)] //// -/// tip | "Подсказка" +/// tip | Подсказка Это стандартный синтаксис python и называется "type alias", это не особенность **FastAPI**. @@ -316,7 +316,7 @@ commons: Annotated[dict, Depends(common_parameters)] Это всё не важно. **FastAPI** знает, что нужно сделать. 😎 -/// note | "Информация" +/// note | Информация Если вам эта тема не знакома, прочтите [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} раздел о `async` и `await` в документации. diff --git a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md index ae0fd0824..0e8cb20e7 100644 --- a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md @@ -36,7 +36,7 @@ //// tab | Python 3.10 без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -50,7 +50,7 @@ //// tab | Python 3.6 без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -96,7 +96,7 @@ //// tab | Python 3.10 без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -110,7 +110,7 @@ //// tab | Python 3.6 без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -159,7 +159,7 @@ //// tab | Python 3.10 без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -173,7 +173,7 @@ //// tab | Python 3.6 без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -185,7 +185,7 @@ //// -/// info | "Дополнительная информация" +/// info | Дополнительная информация Обратите внимание, что мы объявляем только одну зависимость в *функции операции пути* - `query_or_cookie_extractor`. @@ -223,7 +223,7 @@ async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_ca //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -244,7 +244,7 @@ async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False Но, тем не менее, эта система очень мощная и позволяет вам объявлять вложенные графы (деревья) зависимостей сколь угодно глубоко. -/// tip | "Подсказка" +/// tip | Подсказка Все это может показаться не столь полезным на этих простых примерах. diff --git a/docs/ru/docs/tutorial/encoder.md b/docs/ru/docs/tutorial/encoder.md index c9900cb2c..523644ac8 100644 --- a/docs/ru/docs/tutorial/encoder.md +++ b/docs/ru/docs/tutorial/encoder.md @@ -42,7 +42,7 @@ Функция не возвращает большой `str`, содержащий данные в формате JSON (в виде строки). Она возвращает стандартную структуру данных Python (например, `dict`) со значениями и подзначениями, которые совместимы с JSON. -/// note | "Технические детали" +/// note | Технические детали `jsonable_encoder` фактически используется **FastAPI** внутри системы для преобразования данных. Однако он полезен и во многих других сценариях. diff --git a/docs/ru/docs/tutorial/extra-models.md b/docs/ru/docs/tutorial/extra-models.md index e7ff3f40f..241f70779 100644 --- a/docs/ru/docs/tutorial/extra-models.md +++ b/docs/ru/docs/tutorial/extra-models.md @@ -8,7 +8,7 @@ * **Модель для вывода** не должна содержать пароль. * **Модель для базы данных**, возможно, должна содержать хэшированный пароль. -/// danger | "Внимание" +/// danger | Внимание Никогда не храните пароли пользователей в чистом виде. Всегда храните "безопасный хэш", который вы затем сможете проверить. @@ -146,7 +146,7 @@ UserInDB( ) ``` -/// warning | "Предупреждение" +/// warning | Предупреждение Цель использованных в примере вспомогательных функций - не более чем демонстрация возможных операций с данными, но, конечно, они не обеспечивают настоящую безопасность. @@ -192,7 +192,7 @@ UserInDB( Для этого используйте стандартные аннотации типов в Python `typing.Union`: -/// note | "Примечание" +/// note | Примечание При объявлении `Union`, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`. diff --git a/docs/ru/docs/tutorial/first-steps.md b/docs/ru/docs/tutorial/first-steps.md index b1de217cd..309f26c4f 100644 --- a/docs/ru/docs/tutorial/first-steps.md +++ b/docs/ru/docs/tutorial/first-steps.md @@ -24,7 +24,7 @@ $ uvicorn main:app --reload -/// note | "Технические детали" +/// note | Технические детали Команда `uvicorn main:app` обращается к: @@ -139,7 +139,7 @@ OpenAPI описывает схему API. Эта схема содержит о `FastAPI` это класс в Python, который предоставляет всю функциональность для API. -/// note | "Технические детали" +/// note | Технические детали `FastAPI` это класс, который наследуется непосредственно от `Starlette`. @@ -205,7 +205,7 @@ https://example.com/items/foo /items/foo ``` -/// info | "Дополнительная иформация" +/// info | Дополнительная иформация Термин "path" также часто называется "endpoint" или "route". @@ -259,7 +259,7 @@ https://example.com/items/foo * путь `/` * использующих get операцию -/// info | "`@decorator` Дополнительная информация" +/// info | `@decorator` Дополнительная информация Синтаксис `@something` в Python называется "декоратор". @@ -286,7 +286,7 @@ https://example.com/items/foo * `@app.patch()` * `@app.trace()` -/// tip | "Подсказка" +/// tip | Подсказка Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению. @@ -324,7 +324,7 @@ https://example.com/items/foo {!../../docs_src/first_steps/tutorial003.py!} ``` -/// note | "Технические детали" +/// note | Технические детали Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#_1){.internal-link target=_blank}. diff --git a/docs/ru/docs/tutorial/handling-errors.md b/docs/ru/docs/tutorial/handling-errors.md index e7bfb85aa..a06644376 100644 --- a/docs/ru/docs/tutorial/handling-errors.md +++ b/docs/ru/docs/tutorial/handling-errors.md @@ -63,7 +63,7 @@ } ``` -/// tip | "Подсказка" +/// tip | Подсказка При вызове `HTTPException` в качестве параметра `detail` можно передавать любое значение, которое может быть преобразовано в JSON, а не только `str`. @@ -109,7 +109,7 @@ {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -/// note | "Технические детали" +/// note | Технические детали Также можно использовать `from starlette.requests import Request` и `from starlette.responses import JSONResponse`. @@ -166,7 +166,7 @@ path -> item_id #### `RequestValidationError` или `ValidationError` -/// warning | "Внимание" +/// warning | Внимание Это технические детали, которые можно пропустить, если они не важны для вас сейчас. @@ -192,7 +192,7 @@ path -> item_id {!../../docs_src/handling_errors/tutorial004.py!} ``` -/// note | "Технические детали" +/// note | Технические детали Можно также использовать `from starlette.responses import PlainTextResponse`. diff --git a/docs/ru/docs/tutorial/header-params.md b/docs/ru/docs/tutorial/header-params.md index 18e1e60d0..904709b04 100644 --- a/docs/ru/docs/tutorial/header-params.md +++ b/docs/ru/docs/tutorial/header-params.md @@ -32,7 +32,7 @@ //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -46,7 +46,7 @@ //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -90,7 +90,7 @@ //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -104,7 +104,7 @@ //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -116,7 +116,7 @@ //// -/// note | "Технические детали" +/// note | Технические детали `Header` - это "родственный" класс `Path`, `Query` и `Cookie`. Он также наследуется от того же общего класса `Param`. @@ -124,7 +124,7 @@ /// -/// info | "Дополнительная информация" +/// info | Дополнительная информация Чтобы объявить заголовки, важно использовать `Header`, иначе параметры интерпретируются как query-параметры. @@ -172,7 +172,7 @@ //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -186,7 +186,7 @@ //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -198,7 +198,7 @@ //// -/// warning | "Внимание" +/// warning | Внимание Прежде чем установить для `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы запрещают использование заголовков с подчеркиванием. @@ -240,7 +240,7 @@ //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -254,7 +254,7 @@ //// tab | Python 3.9+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -268,7 +268,7 @@ //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. diff --git a/docs/ru/docs/tutorial/index.md b/docs/ru/docs/tutorial/index.md index 4cf45c0ed..ddca2fbb1 100644 --- a/docs/ru/docs/tutorial/index.md +++ b/docs/ru/docs/tutorial/index.md @@ -52,7 +52,7 @@ $ pip install "fastapi[all]" ...это также включает `uvicorn`, который вы можете использовать в качестве сервера, который запускает ваш код. -/// note | "Технические детали" +/// note | Технические детали Вы также можете установить его по частям. diff --git a/docs/ru/docs/tutorial/metadata.md b/docs/ru/docs/tutorial/metadata.md index 246458f42..ae739a043 100644 --- a/docs/ru/docs/tutorial/metadata.md +++ b/docs/ru/docs/tutorial/metadata.md @@ -21,7 +21,7 @@ {!../../docs_src/metadata/tutorial001.py!} ``` -/// tip | "Подсказка" +/// tip | Подсказка Вы можете использовать Markdown в поле `description`, и оно будет отображено в выводе. @@ -57,7 +57,7 @@ Помните, что вы можете использовать Markdown внутри описания, к примеру "login" будет отображен жирным шрифтом (**login**) и "fancy" будет отображаться курсивом (_fancy_). -/// tip | "Подсказка" +/// tip | Подсказка Вам необязательно добавлять метаданные для всех используемых тегов @@ -70,7 +70,7 @@ {!../../docs_src/metadata/tutorial004.py!} ``` -/// info | "Дополнительная информация" +/// info | Дополнительная информация Узнайте больше о тегах в [Конфигурации операции пути](path-operation-configuration.md#_3){.internal-link target=_blank}. diff --git a/docs/ru/docs/tutorial/path-operation-configuration.md b/docs/ru/docs/tutorial/path-operation-configuration.md index 5f3855af2..ac12b7084 100644 --- a/docs/ru/docs/tutorial/path-operation-configuration.md +++ b/docs/ru/docs/tutorial/path-operation-configuration.md @@ -2,7 +2,7 @@ Существует несколько параметров, которые вы можете передать вашему *декоратору операций пути* для его настройки. -/// warning | "Внимание" +/// warning | Внимание Помните, что эти параметры передаются непосредственно *декоратору операций пути*, а не вашей *функции-обработчику операций пути*. @@ -42,7 +42,7 @@ Этот код состояния будет использован в ответе и будет добавлен в схему OpenAPI. -/// note | "Технические детали" +/// note | Технические детали Вы также можете использовать `from starlette import status`. @@ -184,13 +184,13 @@ //// -/// info | "Дополнительная информация" +/// info | Дополнительная информация Помните, что `response_description` относится конкретно к ответу, а `description` относится к *операции пути* в целом. /// -/// check | "Технические детали" +/// check | Технические детали OpenAPI указывает, что каждой *операции пути* необходимо описание ответа. diff --git a/docs/ru/docs/tutorial/path-params-numeric-validations.md b/docs/ru/docs/tutorial/path-params-numeric-validations.md index bf42ec725..ed19576a2 100644 --- a/docs/ru/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ru/docs/tutorial/path-params-numeric-validations.md @@ -32,7 +32,7 @@ //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -46,7 +46,7 @@ //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -58,7 +58,7 @@ //// -/// info | "Информация" +/// info | Информация Поддержка `Annotated` была добавлена в FastAPI начиная с версии 0.95.0 (и с этой версии рекомендуется использовать этот подход). @@ -100,7 +100,7 @@ //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -114,7 +114,7 @@ //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -126,7 +126,7 @@ //// -/// note | "Примечание" +/// note | Примечание Path-параметр всегда является обязательным, поскольку он составляет часть пути. @@ -138,7 +138,7 @@ Path-параметр всегда является обязательным, п ## Задайте нужный вам порядок параметров -/// tip | "Подсказка" +/// tip | Подсказка Это не имеет большого значения, если вы используете `Annotated`. @@ -160,7 +160,7 @@ Path-параметр всегда является обязательным, п //// tab | Python 3.8 без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -192,7 +192,7 @@ Path-параметр всегда является обязательным, п ## Задайте нужный вам порядок параметров, полезные приёмы -/// tip | "Подсказка" +/// tip | Подсказка Это не имеет большого значения, если вы используете `Annotated`. @@ -261,7 +261,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -298,7 +298,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -338,7 +338,7 @@ Python не будет ничего делать с `*`, но он будет з //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -361,7 +361,7 @@ Python не будет ничего делать с `*`, но он будет з * `lt`: меньше (`l`ess `t`han) * `le`: меньше или равно (`l`ess than or `e`qual) -/// info | "Информация" +/// info | Информация `Query`, `Path` и другие классы, которые мы разберём позже, являются наследниками общего класса `Param`. @@ -369,7 +369,7 @@ Python не будет ничего делать с `*`, но он будет з /// -/// note | "Технические детали" +/// note | Технические детали `Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов. diff --git a/docs/ru/docs/tutorial/path-params.md b/docs/ru/docs/tutorial/path-params.md index d1d76cf7b..ba23ba5ea 100644 --- a/docs/ru/docs/tutorial/path-params.md +++ b/docs/ru/docs/tutorial/path-params.md @@ -24,7 +24,7 @@ Здесь, `item_id` объявлен типом `int`. -/// check | "Заметка" +/// check | Заметка Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.). @@ -38,7 +38,7 @@ {"item_id":3} ``` -/// check | "Заметка" +/// check | Заметка Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`. @@ -69,7 +69,7 @@ Та же ошибка возникнет, если вместо `int` передать `float` , например: http://127.0.0.1:8000/items/4.2 -/// check | "Заметка" +/// check | Заметка **FastAPI** обеспечивает проверку типов, используя всё те же определения типов. @@ -85,7 +85,7 @@ -/// check | "Заметка" +/// check | Заметка Ещё раз, просто используя определения типов, **FastAPI** обеспечивает автоматическую интерактивную документацию (с интеграцией Swagger UI). @@ -152,13 +152,13 @@ {!../../docs_src/path_params/tutorial005.py!} ``` -/// info | "Дополнительная информация" +/// info | Дополнительная информация Перечисления (enum) доступны в Python начиная с версии 3.4. /// -/// tip | "Подсказка" +/// tip | Подсказка Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия моделей машинного обучения. @@ -198,7 +198,7 @@ {!../../docs_src/path_params/tutorial005.py!} ``` -/// tip | "Подсказка" +/// tip | Подсказка Значение `"lenet"` также можно получить с помощью `ModelName.lenet.value`. @@ -254,7 +254,7 @@ OpenAPI не поддерживает способов объявления *п {!../../docs_src/path_params/tutorial004.py!} ``` -/// tip | "Подсказка" +/// tip | Подсказка Возможно, вам понадобится, чтобы параметр содержал `/home/johndoe/myfile.txt` с ведущим слэшем (`/`). diff --git a/docs/ru/docs/tutorial/query-params-str-validations.md b/docs/ru/docs/tutorial/query-params-str-validations.md index 0054af6ed..f76570ce8 100644 --- a/docs/ru/docs/tutorial/query-params-str-validations.md +++ b/docs/ru/docs/tutorial/query-params-str-validations.md @@ -22,7 +22,7 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | None` в Python 3.10). Это означает, что входной параметр будет типа `str`, но может быть и `None`. Ещё параметр имеет значение по умолчанию `None`, из-за чего FastAPI определит параметр как необязательный. -/// note | "Технические детали" +/// note | Технические детали FastAPI определит параметр `q` как необязательный, потому что его значение по умолчанию `= None`. @@ -143,7 +143,7 @@ q: Annotated[Union[str, None]] = None В предыдущих версиях FastAPI (ниже 0.95.0) необходимо было использовать `Query` как значение по умолчанию для query-параметра. Так было вместо размещения его в `Annotated`, так что велика вероятность, что вам встретится такой код. Сейчас объясню. -/// tip | "Подсказка" +/// tip | Подсказка При написании нового кода и везде где это возможно, используйте `Annotated`, как было описано ранее. У этого способа есть несколько преимуществ (о них дальше) и никаких недостатков. 🍰 @@ -195,7 +195,7 @@ q: str | None = None Но он явно объявляет его как query-параметр. -/// info | "Дополнительная информация" +/// info | Дополнительная информация Запомните, важной частью объявления параметра как необязательного является: @@ -291,7 +291,7 @@ q: str = Query(default="rick") //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -305,7 +305,7 @@ q: str = Query(default="rick") //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -347,7 +347,7 @@ q: str = Query(default="rick") //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -361,7 +361,7 @@ q: str = Query(default="rick") //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -407,7 +407,7 @@ q: str = Query(default="rick") //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -419,7 +419,7 @@ q: str = Query(default="rick") //// -/// note | "Технические детали" +/// note | Технические детали Наличие значения по умолчанию делает параметр необязательным. @@ -477,7 +477,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -487,7 +487,7 @@ q: Union[str, None] = Query(default=None, min_length=3) {!> ../../docs_src/query_params_str_validations/tutorial006.py!} ``` -/// tip | "Подсказка" +/// tip | Подсказка Обратите внимание, что даже когда `Query()` используется как значение по умолчанию для параметра функции, мы не передаём `default=None` в `Query()`. @@ -519,7 +519,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -531,7 +531,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// -/// info | "Дополнительная информация" +/// info | Дополнительная информация Если вы ранее не сталкивались с `...`: это специальное значение, часть языка Python и называется "Ellipsis". @@ -573,7 +573,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -587,7 +587,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -599,7 +599,7 @@ q: Union[str, None] = Query(default=None, min_length=3) //// -/// tip | "Подсказка" +/// tip | Подсказка Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел Обязательные Опциональные поля. @@ -627,7 +627,7 @@ Pydantic, мощь которого используется в FastAPI для //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -639,7 +639,7 @@ Pydantic, мощь которого используется в FastAPI для //// -/// tip | "Подсказка" +/// tip | Подсказка Запомните, когда вам необходимо объявить query-параметр обязательным, вы можете просто не указывать параметр `default`. Таким образом, вам редко придётся использовать `...` или `Required`. @@ -677,7 +677,7 @@ Pydantic, мощь которого используется в FastAPI для //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -691,7 +691,7 @@ Pydantic, мощь которого используется в FastAPI для //// tab | Python 3.9+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -705,7 +705,7 @@ Pydantic, мощь которого используется в FastAPI для //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -736,7 +736,7 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -/// tip | "Подсказка" +/// tip | Подсказка Чтобы объявить query-параметр типом `list`, как в примере выше, вам нужно явно использовать `Query`, иначе он будет интерпретирован как тело запроса. @@ -768,7 +768,7 @@ http://localhost:8000/items/?q=foo&q=bar //// tab | Python 3.9+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -782,7 +782,7 @@ http://localhost:8000/items/?q=foo&q=bar //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -833,7 +833,7 @@ http://localhost:8000/items/ //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -845,7 +845,7 @@ http://localhost:8000/items/ //// -/// note | "Технические детали" +/// note | Технические детали Запомните, что в таком случае, FastAPI не будет проверять содержимое списка. @@ -859,7 +859,7 @@ http://localhost:8000/items/ Указанная информация будет включена в генерируемую OpenAPI документацию и использована в пользовательском интерфейсе и внешних инструментах. -/// note | "Технические детали" +/// note | Технические детали Имейте в виду, что разные инструменты могут иметь разные уровни поддержки OpenAPI. @@ -895,7 +895,7 @@ http://localhost:8000/items/ //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -909,7 +909,7 @@ http://localhost:8000/items/ //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -949,7 +949,7 @@ http://localhost:8000/items/ //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -963,7 +963,7 @@ http://localhost:8000/items/ //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -1019,7 +1019,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -1033,7 +1033,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -1079,7 +1079,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -1093,7 +1093,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -1139,7 +1139,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. @@ -1153,7 +1153,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать версию с `Annotated` если возможно. diff --git a/docs/ru/docs/tutorial/query-params.md b/docs/ru/docs/tutorial/query-params.md index edf06746b..2c697224c 100644 --- a/docs/ru/docs/tutorial/query-params.md +++ b/docs/ru/docs/tutorial/query-params.md @@ -81,7 +81,7 @@ http://127.0.0.1:8000/items/?skip=20 В этом случае, параметр `q` будет не обязательным и будет иметь значение `None` по умолчанию. -/// check | "Важно" +/// check | Важно Также обратите внимание, что **FastAPI** достаточно умён чтобы заметить, что параметр `item_id` является path-параметром, а `q` нет, поэтому, это параметр запроса. @@ -240,7 +240,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`, типа `int` и со значением по умолчанию `0`. * `limit`, необязательный `int`. -/// tip | "Подсказка" +/// tip | Подсказка Вы можете использовать класс `Enum` также, как ранее применяли его с [Path-параметрами](path-params.md#_7){.internal-link target=_blank}. diff --git a/docs/ru/docs/tutorial/request-files.md b/docs/ru/docs/tutorial/request-files.md index 34b9c94fa..836d6efed 100644 --- a/docs/ru/docs/tutorial/request-files.md +++ b/docs/ru/docs/tutorial/request-files.md @@ -2,7 +2,7 @@ Используя класс `File`, мы можем позволить клиентам загружать файлы. -/// info | "Дополнительная информация" +/// info | Дополнительная информация Чтобы получать загруженные файлы, сначала установите `python-multipart`. @@ -34,7 +34,7 @@ //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -68,7 +68,7 @@ //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -80,7 +80,7 @@ //// -/// info | "Дополнительная информация" +/// info | Дополнительная информация `File` - это класс, который наследуется непосредственно от `Form`. @@ -88,7 +88,7 @@ /// -/// tip | "Подсказка" +/// tip | Подсказка Для объявления тела файла необходимо использовать `File`, поскольку в противном случае параметры будут интерпретироваться как параметры запроса или параметры тела (JSON). @@ -124,7 +124,7 @@ //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -177,13 +177,13 @@ contents = await myfile.read() contents = myfile.file.read() ``` -/// note | "Технические детали `async`" +/// note | Технические детали `async` При использовании методов `async` **FastAPI** запускает файловые методы в пуле потоков и ожидает их. /// -/// note | "Технические детали Starlette" +/// note | Технические детали Starlette **FastAPI** наследует `UploadFile` непосредственно из **Starlette**, но добавляет некоторые детали для совместимости с **Pydantic** и другими частями FastAPI. @@ -195,7 +195,7 @@ contents = myfile.file.read() **FastAPI** позаботится о том, чтобы считать эти данные из нужного места, а не из JSON. -/// note | "Технические детали" +/// note | Технические детали Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы. @@ -205,7 +205,7 @@ contents = myfile.file.read() /// -/// warning | "Внимание" +/// warning | Внимание В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`. @@ -243,7 +243,7 @@ contents = myfile.file.read() //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -257,7 +257,7 @@ contents = myfile.file.read() //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -291,7 +291,7 @@ contents = myfile.file.read() //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -329,7 +329,7 @@ contents = myfile.file.read() //// tab | Python 3.9+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -343,7 +343,7 @@ contents = myfile.file.read() //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -357,7 +357,7 @@ contents = myfile.file.read() Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`. -/// note | "Technical Details" +/// note | Technical Details Можно также использовать `from starlette.responses import HTMLResponse`. @@ -387,7 +387,7 @@ contents = myfile.file.read() //// tab | Python 3.9+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -401,7 +401,7 @@ contents = myfile.file.read() //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. diff --git a/docs/ru/docs/tutorial/request-forms-and-files.md b/docs/ru/docs/tutorial/request-forms-and-files.md index 9b449bcd9..fd98ec953 100644 --- a/docs/ru/docs/tutorial/request-forms-and-files.md +++ b/docs/ru/docs/tutorial/request-forms-and-files.md @@ -2,7 +2,7 @@ Вы можете определять файлы и поля формы одновременно, используя `File` и `Form`. -/// info | "Дополнительная информация" +/// info | Дополнительная информация Чтобы получать загруженные файлы и/или данные форм, сначала установите `python-multipart`. @@ -30,7 +30,7 @@ //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -64,7 +64,7 @@ //// tab | Python 3.6+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -80,7 +80,7 @@ Вы можете объявить некоторые файлы как `bytes`, а некоторые - как `UploadFile`. -/// warning | "Внимание" +/// warning | Внимание Вы можете объявить несколько параметров `File` и `Form` в операции *path*, но вы не можете также объявить поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с помощью `multipart/form-data` вместо `application/json`. diff --git a/docs/ru/docs/tutorial/request-forms.md b/docs/ru/docs/tutorial/request-forms.md index 93b44437b..cd17613de 100644 --- a/docs/ru/docs/tutorial/request-forms.md +++ b/docs/ru/docs/tutorial/request-forms.md @@ -2,7 +2,7 @@ Когда вам нужно получить поля формы вместо JSON, вы можете использовать `Form`. -/// info | "Дополнительная информация" +/// info | Дополнительная информация Чтобы использовать формы, сначала установите `python-multipart`. @@ -32,7 +32,7 @@ //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать 'Annotated' версию, если это возможно. @@ -66,7 +66,7 @@ //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Рекомендуется использовать 'Annotated' версию, если это возможно. @@ -84,13 +84,13 @@ Вы можете настроить `Form` точно так же, как настраиваете и `Body` ( `Query`, `Path`, `Cookie`), включая валидации, примеры, псевдонимы (например, `user-name` вместо `username`) и т.д. -/// info | "Дополнительная информация" +/// info | Дополнительная информация `Form` - это класс, который наследуется непосредственно от `Body`. /// -/// tip | "Подсказка" +/// tip | Подсказка Вам необходимо явно указывать параметр `Form` при объявлении каждого поля, иначе поля будут интерпретироваться как параметры запроса или параметры тела (JSON). @@ -102,7 +102,7 @@ **FastAPI** гарантирует правильное чтение этих данных из соответствующего места, а не из JSON. -/// note | "Технические детали" +/// note | Технические детали Данные из форм обычно кодируются с использованием "типа медиа" `application/x-www-form-urlencoded`. @@ -112,7 +112,7 @@ /// -/// warning | "Предупреждение" +/// warning | Предупреждение Вы можете объявлять несколько параметров `Form` в *операции пути*, но вы не можете одновременно с этим объявлять поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с использованием `application/x-www-form-urlencoded`, а не `application/json`. diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md index 363e64676..c55be38ef 100644 --- a/docs/ru/docs/tutorial/response-model.md +++ b/docs/ru/docs/tutorial/response-model.md @@ -83,7 +83,7 @@ FastAPI будет использовать этот возвращаемый т //// -/// note | "Технические детали" +/// note | Технические детали Помните, что параметр `response_model` является параметром именно декоратора http-методов (`get`, `post`, и т.п.). Не следует его указывать для *функций операций пути*, как вы бы поступили с другими параметрами или с телом запроса. @@ -93,7 +93,7 @@ FastAPI будет использовать этот возвращаемый т FastAPI будет использовать значение `response_model` для того, чтобы автоматически генерировать документацию, производить валидацию и т.п. А также для **конвертации и фильтрации выходных данных** в объявленный тип. -/// tip | "Подсказка" +/// tip | Подсказка Если вы используете анализаторы типов со строгой проверкой (например, mypy), можно указать `Any` в качестве типа возвращаемого значения функции. @@ -129,7 +129,7 @@ FastAPI будет использовать значение `response_model` д //// -/// info | "Информация" +/// info | Информация Чтобы использовать `EmailStr`, прежде необходимо установить `email-validator`. Используйте `pip install email-validator` @@ -161,7 +161,7 @@ FastAPI будет использовать значение `response_model` д Но что если мы захотим использовать эту модель для какой-либо другой *операции пути*? Мы можем, сами того не желая, отправить пароль любому другому пользователю. -/// danger | "Осторожно" +/// danger | Осторожно Никогда не храните пароли пользователей в открытом виде, а также никогда не возвращайте их в ответе, как в примере выше. В противном случае - убедитесь, что вы хорошо продумали и учли все возможные риски такого подхода и вам известно, что вы делаете. @@ -444,13 +444,13 @@ FastAPI совместно с Pydantic выполнит некоторую ма } ``` -/// info | "Информация" +/// info | Информация "Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic с параметром `exclude_unset`, чтобы достичь такого эффекта. /// -/// info | "Информация" +/// info | Информация Вы также можете использовать: @@ -494,7 +494,7 @@ FastAPI достаточно умен (на самом деле, это засл И поэтому, они также будут включены в JSON ответа. -/// tip | "Подсказка" +/// tip | Подсказка Значением по умолчанию может быть что угодно, не только `None`. @@ -510,7 +510,7 @@ FastAPI достаточно умен (на самом деле, это засл Это можно использовать как быстрый способ исключить данные из ответа, не создавая отдельную модель Pydantic. -/// tip | "Подсказка" +/// tip | Подсказка Но по-прежнему рекомендуется следовать изложенным выше советам и использовать несколько моделей вместо данных параметров. @@ -536,7 +536,7 @@ FastAPI достаточно умен (на самом деле, это засл //// -/// tip | "Подсказка" +/// tip | Подсказка При помощи кода `{"name","description"}` создается объект множества (`set`) с двумя строковыми значениями. diff --git a/docs/ru/docs/tutorial/response-status-code.md b/docs/ru/docs/tutorial/response-status-code.md index 48808bea7..f08b15379 100644 --- a/docs/ru/docs/tutorial/response-status-code.md +++ b/docs/ru/docs/tutorial/response-status-code.md @@ -12,7 +12,7 @@ {!../../docs_src/response_status_code/tutorial001.py!} ``` -/// note | "Примечание" +/// note | Примечание Обратите внимание, что `status_code` является атрибутом метода-декоратора (`get`, `post` и т.д.), а не *функции-обработчика пути* в отличие от всех остальных параметров и тела запроса. @@ -20,7 +20,7 @@ Параметр `status_code` принимает число, обозначающее HTTP код статуса ответа. -/// info | "Информация" +/// info | Информация В качестве значения параметра `status_code` также может использоваться `IntEnum`, например, из библиотеки `http.HTTPStatus` в Python. @@ -33,7 +33,7 @@ -/// note | "Примечание" +/// note | Примечание Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела. @@ -43,7 +43,7 @@ FastAPI знает об этом и создаст документацию Open ## Об HTTP кодах статуса ответа -/// note | "Примечание" +/// note | Примечание Если вы уже знаете, что представляют собой HTTP коды статуса ответа, можете перейти к следующему разделу. @@ -66,7 +66,7 @@ FastAPI знает об этом и создаст документацию Open * Для общих ошибок со стороны клиента можно просто использовать код `400`. * `5XX` – статус-коды, сообщающие о серверной ошибке. Они почти никогда не используются разработчиками напрямую. Когда что-то идет не так в какой-то части кода вашего приложения или на сервере, он автоматически вернёт один из 5XX кодов. -/// tip | "Подсказка" +/// tip | Подсказка Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с документацией MDN об HTTP кодах статуса ответа. @@ -94,7 +94,7 @@ FastAPI знает об этом и создаст документацию Open -/// note | "Технические детали" +/// note | Технические детали Вы также можете использовать `from starlette import status` вместо `from fastapi import status`. diff --git a/docs/ru/docs/tutorial/security/first-steps.md b/docs/ru/docs/tutorial/security/first-steps.md index c98ce2c60..484dfceff 100644 --- a/docs/ru/docs/tutorial/security/first-steps.md +++ b/docs/ru/docs/tutorial/security/first-steps.md @@ -38,7 +38,7 @@ //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -52,7 +52,7 @@ ## Запуск -/// info | "Дополнительная информация" +/// info | Дополнительная информация Вначале, установите библиотеку `python-multipart`. @@ -82,7 +82,7 @@ $ uvicorn main:app --reload -/// check | "Кнопка авторизации!" +/// check | Кнопка авторизации! У вас уже появилась новая кнопка "Authorize". @@ -94,7 +94,7 @@ $ uvicorn main:app --reload -/// note | "Технические детали" +/// note | Технические детали Неважно, что вы введете в форму, она пока не будет работать. Но мы к этому еще придем. @@ -140,7 +140,7 @@ OAuth2 был разработан для того, чтобы бэкэнд ил В данном примере мы будем использовать **OAuth2**, с аутентификацией по паролю, используя токен **Bearer**. Для этого мы используем класс `OAuth2PasswordBearer`. -/// info | "Дополнительная информация" +/// info | Дополнительная информация Токен "bearer" - не единственный вариант, но для нашего случая он является наилучшим. @@ -170,7 +170,7 @@ OAuth2 был разработан для того, чтобы бэкэнд ил //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -182,7 +182,7 @@ OAuth2 был разработан для того, чтобы бэкэнд ил //// -/// tip | "Подсказка" +/// tip | Подсказка Здесь `tokenUrl="token"` ссылается на относительный URL `token`, который мы еще не создали. Поскольку это относительный URL, он эквивалентен `./token`. @@ -196,7 +196,7 @@ OAuth2 был разработан для того, чтобы бэкэнд ил Вскоре мы создадим и саму операцию пути. -/// info | "Дополнительная информация" +/// info | Дополнительная информация Если вы очень строгий "питонист", то вам может не понравиться стиль названия параметра `tokenUrl` вместо `token_url`. @@ -236,7 +236,7 @@ oauth2_scheme(some, parameters) //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка Предпочтительнее использовать версию с аннотацией, если это возможно. @@ -252,7 +252,7 @@ oauth2_scheme(some, parameters) **FastAPI** будет знать, что он может использовать эту зависимость для определения "схемы безопасности" в схеме OpenAPI (и автоматической документации по API). -/// info | "Технические детали" +/// info | Технические детали **FastAPI** будет знать, что он может использовать класс `OAuth2PasswordBearer` (объявленный в зависимости) для определения схемы безопасности в OpenAPI, поскольку он наследуется от `fastapi.security.oauth2.OAuth2`, который, в свою очередь, наследуется от `fastapi.security.base.SecurityBase`. diff --git a/docs/ru/docs/tutorial/security/index.md b/docs/ru/docs/tutorial/security/index.md index bd512fde3..e4969c4cf 100644 --- a/docs/ru/docs/tutorial/security/index.md +++ b/docs/ru/docs/tutorial/security/index.md @@ -32,7 +32,7 @@ OAuth2 включает в себя способы аутентификации OAuth2 не указывает, как шифровать сообщение, он ожидает, что ваше приложение будет обслуживаться по протоколу HTTPS. -/// tip | "Подсказка" +/// tip | Подсказка В разделе **Развертывание** вы увидите [как настроить протокол HTTPS бесплатно, используя Traefik и Let's Encrypt.](https://fastapi.tiangolo.com/ru/deployment/https/) @@ -89,7 +89,7 @@ OpenAPI может использовать следующие схемы авт * Это автоматическое обнаружение определено в спецификации OpenID Connect. -/// tip | "Подсказка" +/// tip | Подсказка Интеграция сторонних сервисов для аутентификации/авторизации таких как Google, Facebook, Twitter, GitHub и т.д. осуществляется достаточно легко. diff --git a/docs/ru/docs/tutorial/static-files.md b/docs/ru/docs/tutorial/static-files.md index 4734554f3..0287fb017 100644 --- a/docs/ru/docs/tutorial/static-files.md +++ b/docs/ru/docs/tutorial/static-files.md @@ -11,7 +11,7 @@ {!../../docs_src/static_files/tutorial001.py!} ``` -/// note | "Технические детали" +/// note | Технические детали Вы также можете использовать `from starlette.staticfiles import StaticFiles`. diff --git a/docs/ru/docs/tutorial/testing.md b/docs/ru/docs/tutorial/testing.md index ae045bbbe..0485ef801 100644 --- a/docs/ru/docs/tutorial/testing.md +++ b/docs/ru/docs/tutorial/testing.md @@ -8,7 +8,7 @@ ## Использование класса `TestClient` -/// info | "Информация" +/// info | Информация Для использования класса `TestClient` необходимо установить библиотеку `httpx`. @@ -30,7 +30,7 @@ {!../../docs_src/app_testing/tutorial001.py!} ``` -/// tip | "Подсказка" +/// tip | Подсказка Обратите внимание, что тестирующая функция является обычной `def`, а не асинхронной `async def`. @@ -40,7 +40,7 @@ /// -/// note | "Технические детали" +/// note | Технические детали Также можно написать `from starlette.testclient import TestClient`. @@ -48,7 +48,7 @@ /// -/// tip | "Подсказка" +/// tip | Подсказка Если для тестирования Вам, помимо запросов к приложению FastAPI, необходимо вызывать асинхронные функции (например, для подключения к базе данных с помощью асинхронного драйвера), то ознакомьтесь со страницей [Асинхронное тестирование](../advanced/async-tests.md){.internal-link target=_blank} в расширенном руководстве. @@ -148,7 +148,7 @@ //// tab | Python 3.10+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка По возможности используйте версию с `Annotated`. @@ -162,7 +162,7 @@ //// tab | Python 3.8+ без Annotated -/// tip | "Подсказка" +/// tip | Подсказка По возможности используйте версию с `Annotated`. @@ -196,7 +196,7 @@ Для получения дополнительной информации о передаче данных на бэкенд с помощью `httpx` или `TestClient` ознакомьтесь с документацией HTTPX. -/// info | "Информация" +/// info | Информация Обратите внимание, что `TestClient` принимает данные, которые можно конвертировать в JSON, но не модели Pydantic. diff --git a/docs/tr/docs/advanced/index.md b/docs/tr/docs/advanced/index.md index 6c057162e..836e63c8a 100644 --- a/docs/tr/docs/advanced/index.md +++ b/docs/tr/docs/advanced/index.md @@ -6,7 +6,7 @@ İlerleyen bölümlerde diğer seçenekler, konfigürasyonlar ve ek özellikleri göreceğiz. -/// tip | "İpucu" +/// tip | İpucu Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**. diff --git a/docs/tr/docs/advanced/security/index.md b/docs/tr/docs/advanced/security/index.md index 227674bd4..709f74c72 100644 --- a/docs/tr/docs/advanced/security/index.md +++ b/docs/tr/docs/advanced/security/index.md @@ -4,7 +4,7 @@ [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank} sayfasında ele alınanların dışında güvenlikle ilgili bazı ek özellikler vardır. -/// tip | "İpucu" +/// tip | İpucu Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**. diff --git a/docs/tr/docs/advanced/testing-websockets.md b/docs/tr/docs/advanced/testing-websockets.md index aa8a040d0..12b6ab60f 100644 --- a/docs/tr/docs/advanced/testing-websockets.md +++ b/docs/tr/docs/advanced/testing-websockets.md @@ -8,7 +8,7 @@ Bu işlem için, `TestClient`'ı bir `with` ifadesinde kullanarak WebSocket'e ba {!../../docs_src/app_testing/tutorial002.py!} ``` -/// note | "Not" +/// note | Not Daha fazla detay için Starlette'in Websockets'i Test Etmek dokümantasyonunu inceleyin. diff --git a/docs/tr/docs/alternatives.md b/docs/tr/docs/alternatives.md index 286b7897a..c98b966b5 100644 --- a/docs/tr/docs/alternatives.md +++ b/docs/tr/docs/alternatives.md @@ -30,13 +30,13 @@ Django REST framework'ü, Django'nun API kabiliyetlerini arttırmak için arka p **Otomatik API dökümantasyonu**nun ilk örneklerinden biri olduğu için, **FastAPI** arayışına ilham veren ilk fikirlerden biri oldu. -/// note | "Not" +/// note | Not Django REST Framework'ü, aynı zamanda **FastAPI**'ın dayandığı Starlette ve Uvicorn'un da yaratıcısı olan Tom Christie tarafından geliştirildi. /// -/// check | "**FastAPI**'a nasıl ilham verdi?" +/// check | **FastAPI**'a nasıl ilham verdi? Kullanıcılar için otomatik API dökümantasyonu sunan bir web arayüzüne sahip olmalı. @@ -56,7 +56,7 @@ Uygulama parçalarının böyle ayrılıyor oluşu ve istenilen özelliklerle ge Flask'ın basitliği göz önünde bulundurulduğu zaman, API geliştirmek için iyi bir seçim gibi görünüyordu. Sıradaki şey ise Flask için bir "Django REST Framework"! -/// check | "**FastAPI**'a nasıl ilham verdi?" +/// check | **FastAPI**'a nasıl ilham verdi? Gereken araçları ve parçaları birleştirip eşleştirmeyi kolaylaştıracak bir mikro framework olmalı. @@ -98,7 +98,7 @@ def read_url(): `requests.get(...)` ile `@app.get(...)` arasındaki benzerliklere bakın. -/// check | "**FastAPI**'a nasıl ilham verdi?" +/// check | **FastAPI**'a nasıl ilham verdi? * Basit ve sezgisel bir API'ya sahip olmalı. * HTTP metot isimlerini (işlemlerini) anlaşılır olacak bir şekilde, direkt kullanmalı. @@ -118,7 +118,7 @@ Swagger bir noktada Linux Foundation'a verildi ve adı OpenAPI olarak değiştir İşte bu yüzden versiyon 2.0 hakkında konuşurken "Swagger", versiyon 3 ve üzeri için ise "OpenAPI" adını kullanmak daha yaygın. -/// check | "**FastAPI**'a nasıl ilham verdi?" +/// check | **FastAPI**'a nasıl ilham verdi? API spesifikasyonları için özel bir şema yerine bir açık standart benimseyip kullanmalı. @@ -147,7 +147,7 @@ Marshmallow bu özellikleri sağlamak için geliştirilmişti. Benim de geçmiş Ama... Python'un tip belirteçleri gelmeden önce oluşturulmuştu. Yani her şemayı tanımlamak için Marshmallow'un sunduğu spesifik araçları ve sınıfları kullanmanız gerekiyordu. -/// check | "**FastAPI**'a nasıl ilham verdi?" +/// check | **FastAPI**'a nasıl ilham verdi? Kod kullanarak otomatik olarak veri tipini ve veri doğrulamayı belirten "şemalar" tanımlamalı. @@ -163,13 +163,13 @@ Veri doğrulama için arka planda Marshmallow kullanıyor, hatta aynı geliştir Webargs da harika bir araç ve onu da geçmişte henüz **FastAPI** yokken çok kullandım. -/// info | "Bilgi" +/// info | Bilgi Webargs aynı Marshmallow geliştirileri tarafından oluşturuldu. /// -/// check | "**FastAPI**'a nasıl ilham verdi?" +/// check | **FastAPI**'a nasıl ilham verdi? Gelen istek verisi için otomatik veri doğrulamaya sahip olmalı. @@ -191,13 +191,13 @@ Fakat sonrasında yine mikro sözdizimi problemiyle karşılaşıyoruz. Python m Editör bu konuda pek yardımcı olamaz. Üstelik eğer parametreleri ya da Marshmallow şemalarını değiştirip YAML kodunu güncellemeyi unutursak artık döküman geçerliliğini yitiriyor. -/// info | "Bilgi" +/// info | Bilgi APISpec de aynı Marshmallow geliştiricileri tarafından oluşturuldu. /// -/// check | "**FastAPI**'a nasıl ilham verdi?" +/// check | **FastAPI**'a nasıl ilham verdi? API'lar için açık standart desteği olmalı (OpenAPI gibi). @@ -223,13 +223,13 @@ Bunu kullanmak, bir kaç `uvloop` kullanıldı. Hızının asıl kaynağı buydu. @@ -269,7 +269,7 @@ Uvicorn ve Starlette'e ilham kaynağı olduğu oldukça açık, şu anda ikisi d /// -/// check | "**FastAPI**'a nasıl ilham oldu?" +/// check | **FastAPI**'a nasıl ilham oldu? Uçuk performans sağlayacak bir yol bulmalı. @@ -285,7 +285,7 @@ Falcon ise bir diğer yüksek performanslı Python framework'ü. Minimal olacak Yani veri doğrulama, veri dönüştürme ve dökümantasyonun hepsi kodda yer almalı, otomatik halledemiyoruz. Ya da Falcon üzerine bir framework olarak uygulanmaları gerekiyor, aynı Hug'da olduğu gibi. Bu ayrım Falcon'un tasarımından esinlenen, istek ve cevap objelerini parametre olarak işleyen diğer kütüphanelerde de yer alıyor. -/// check | "**FastAPI**'a nasıl ilham oldu?" +/// check | **FastAPI**'a nasıl ilham oldu? Harika bir performans'a sahip olmanın yollarını bulmalı. @@ -311,7 +311,7 @@ Biraz daha detaylı ayarlamalara gerek duyuyor. Ayrıca Yol'lar fonksiyonun üstünde endpoint'i işleyen dekoratörler yerine farklı yerlerde tanımlanan fonksiyonlarla belirlenir. Bu Flask (ve Starlette) yerine daha çok Django'nun yaklaşımına daha yakın bir metot. Bu, kodda nispeten birbiriyle sıkı ilişkili olan şeyleri ayırmaya sebep oluyor. -/// check | "**FastAPI**'a nasıl ilham oldu?" +/// check | **FastAPI**'a nasıl ilham oldu? Model özelliklerinin "standart" değerlerini kullanarak veri tipleri için ekstra veri doğrulama koşulları tanımlamalı. Bu editör desteğini geliştiriyor ve daha önceden Pydantic'te yoktu. @@ -333,13 +333,13 @@ Ayrıca ilginç ve çok rastlanmayan bir özelliği vardı: aynı framework'ü k Senkron çalışan Python web framework'lerinin standardına (WSGI) dayandığından dolayı Websocket'leri ve diğer şeyleri işleyemiyor, ancak yine de yüksek performansa sahip. -/// info | "Bilgi" +/// info | Bilgi Hug, Python dosyalarında bulunan dahil etme satırlarını otomatik olarak sıralayan harika bir araç olan `isort`'un geliştiricisi Timothy Crosley tarafından geliştirildi. /// -/// check | "**FastAPI**'a nasıl ilham oldu?" +/// check | **FastAPI**'a nasıl ilham oldu? Hug, APIStar'ın çeşitli kısımlarında esin kaynağı oldu ve APIStar'la birlikte en umut verici bulduğum araçlardan biriydi. @@ -373,7 +373,7 @@ Geliştiricinin Starlette'e odaklanması gerekince proje de artık bir API web f Artık APIStar, OpenAPI özelliklerini doğrulamak için bir dizi araç sunan bir proje haline geldi. -/// info | "Bilgi" +/// info | Bilgi APIStar, aşağıdaki projeleri de üreten Tom Christie tarafından geliştirildi: @@ -383,7 +383,7 @@ APIStar, aşağıdaki projeleri de üreten Tom Christie tarafından geliştirild /// -/// check | "**FastAPI**'a nasıl ilham oldu?" +/// check | **FastAPI**'a nasıl ilham oldu? Var oldu. @@ -407,7 +407,7 @@ Tip belirteçleri kullanıyor olması onu aşırı sezgisel yapıyor. Marshmallow ile karşılaştırılabilir. Ancak karşılaştırmalarda Marshmallowdan daha hızlı görünüyor. Aynı Python tip belirteçlerine dayanıyor ve editör desteği de harika. -/// check | "**FastAPI** nerede kullanıyor?" +/// check | **FastAPI** nerede kullanıyor? Bütün veri doğrulama, veri dönüştürme ve JSON Şemasına bağlı otomatik model dökümantasyonunu halletmek için! @@ -442,7 +442,7 @@ Ancak otomatik veri doğrulama, veri dönüştürme ve dökümantasyon sağlamyo Bu, **FastAPI**'ın onun üzerine tamamen Python tip belirteçlerine bağlı olarak eklediği (Pydantic ile) ana şeylerden biri. **FastAPI** bunun yanında artı olarak bağımlılık enjeksiyonu sistemi, güvenlik araçları, OpenAPI şema üretimi ve benzeri özellikler de ekliyor. -/// note | "Teknik Detaylar" +/// note | Teknik Detaylar ASGI, Django'nun ana ekibi tarafından geliştirilen yeni bir "standart". Bir "Python standardı" (PEP) olma sürecinde fakat henüz bir standart değil. @@ -450,7 +450,7 @@ Bununla birlikte, halihazırda birçok araç tarafından bir "standart" olarak k /// -/// check | "**FastAPI** nerede kullanıyor?" +/// check | **FastAPI** nerede kullanıyor? Tüm temel web kısımlarında üzerine özellikler eklenerek kullanılmakta. @@ -468,7 +468,7 @@ Bir web framework'ünden ziyade bir sunucudur, yani yollara bağlı yönlendirme Starlette ve **FastAPI** için tavsiye edilen sunucu Uvicorndur. -/// check | "**FastAPI** neden tavsiye ediyor?" +/// check | **FastAPI** neden tavsiye ediyor? **FastAPI** uygulamalarını çalıştırmak için ana web sunucusu Uvicorn! diff --git a/docs/tr/docs/async.md b/docs/tr/docs/async.md index 0d463a2f0..558a79cb7 100644 --- a/docs/tr/docs/async.md +++ b/docs/tr/docs/async.md @@ -21,7 +21,7 @@ async def read_results(): return results ``` -/// note | "Not" +/// note | Not Sadece `async def` ile tanımlanan fonksiyonlar içinde `await` kullanabilirsiniz. diff --git a/docs/tr/docs/how-to/index.md b/docs/tr/docs/how-to/index.md index 798adca61..26dd9026c 100644 --- a/docs/tr/docs/how-to/index.md +++ b/docs/tr/docs/how-to/index.md @@ -6,7 +6,7 @@ Bu fikirlerin büyük bir kısmı aşağı yukarı **bağımsız** olacaktır, Projeniz için ilginç ve yararlı görünen bir şey varsa devam edin ve inceleyin, aksi halde bunları atlayabilirsiniz. -/// tip | "İpucu" +/// tip | İpucu **FastAPI**'ı düzgün (ve önerilen) şekilde öğrenmek istiyorsanız [Öğretici - Kullanıcı Rehberi](../tutorial/index.md){.internal-link target=_blank}'ni bölüm bölüm okuyun. diff --git a/docs/tr/docs/python-types.md b/docs/tr/docs/python-types.md index 9584a5732..308dfa6fb 100644 --- a/docs/tr/docs/python-types.md +++ b/docs/tr/docs/python-types.md @@ -12,7 +12,7 @@ Bu pythonda tip belirteçleri için **hızlı bir başlangıç / bilgi tazeleme **FastAPI** kullanmayacak olsanız bile tür belirteçleri hakkında bilgi edinmenizde fayda var. -/// note | "Not" +/// note | Not Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, sonraki bölüme geçin. @@ -175,7 +175,7 @@ Liste, bazı dahili tipleri içeren bir tür olduğundan, bunları köşeli para {!../../docs_src/python_types/tutorial006.py!} ``` -/// tip | "Ipucu" +/// tip | Ipucu Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir. diff --git a/docs/tr/docs/tutorial/cookie-params.md b/docs/tr/docs/tutorial/cookie-params.md index 895cf9b03..56bcc0c86 100644 --- a/docs/tr/docs/tutorial/cookie-params.md +++ b/docs/tr/docs/tutorial/cookie-params.md @@ -32,7 +32,7 @@ //// tab | Python 3.10+ non-Annotated -/// tip | "İpucu" +/// tip | İpucu Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. @@ -46,7 +46,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. //// tab | Python 3.8+ non-Annotated -/// tip | "İpucu" +/// tip | İpucu Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. @@ -90,7 +90,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. //// tab | Python 3.10+ non-Annotated -/// tip | "İpucu" +/// tip | İpucu Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. @@ -104,7 +104,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. //// tab | Python 3.8+ non-Annotated -/// tip | "İpucu" +/// tip | İpucu Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. @@ -116,7 +116,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. //// -/// note | "Teknik Detaylar" +/// note | Teknik Detaylar `Cookie` sınıfı `Path` ve `Query` sınıflarının kardeşidir. Diğerleri gibi `Param` sınıfını miras alan bir sınıftır. @@ -124,7 +124,7 @@ Ancak `fastapi`'dan projenize dahil ettiğiniz `Query`, `Path`, `Cookie` ve diğ /// -/// info | "Bilgi" +/// info | Bilgi Çerez tanımlamak için `Cookie` sınıfını kullanmanız gerekmektedir, aksi taktirde parametreler sorgu parametreleri olarak yorumlanır. diff --git a/docs/tr/docs/tutorial/first-steps.md b/docs/tr/docs/tutorial/first-steps.md index 335fcaece..da9057204 100644 --- a/docs/tr/docs/tutorial/first-steps.md +++ b/docs/tr/docs/tutorial/first-steps.md @@ -24,7 +24,7 @@ $ uvicorn main:app --reload -/// note | "Not" +/// note | Not `uvicorn main:app` komutunu şu şekilde açıklayabiliriz: @@ -139,7 +139,7 @@ Ayrıca, API'ınızla iletişim kuracak önyüz, mobil veya IoT uygulamaları gi `FastAPI`, API'niz için tüm işlevselliği sağlayan bir Python sınıfıdır. -/// note | "Teknik Detaylar" +/// note | Teknik Detaylar `FastAPI` doğrudan `Starlette`'i miras alan bir sınıftır. @@ -205,7 +205,7 @@ https://example.com/items/foo /items/foo ``` -/// info | "Bilgi" +/// info | Bilgi "Yol" genellikle "endpoint" veya "route" olarak adlandırılır. @@ -259,7 +259,7 @@ Biz de onları "**operasyonlar**" olarak adlandıracağız. * get operasyonu ile * `/` yoluna gelen istekler -/// info | "`@decorator` Bilgisi" +/// info | `@decorator` Bilgisi Python'da `@something` sözdizimi "dekoratör" olarak adlandırılır. @@ -286,7 +286,7 @@ Daha az kullanılanları da kullanabilirsiniz: * `@app.patch()` * `@app.trace()` -/// tip | "İpucu" +/// tip | İpucu Her işlemi (HTTP metod) istediğiniz gibi kullanmakta özgürsünüz. @@ -324,7 +324,7 @@ Bu fonksiyonu `async def` yerine normal bir fonksiyon olarak da tanımlayabilirs {!../../docs_src/first_steps/tutorial003.py!} ``` -/// note | "Not" +/// note | Not Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurry){.internal-link target=_blank} sayfasını kontrol edebilirsiniz. diff --git a/docs/tr/docs/tutorial/path-params.md b/docs/tr/docs/tutorial/path-params.md index 9017d99ab..c883c2f9f 100644 --- a/docs/tr/docs/tutorial/path-params.md +++ b/docs/tr/docs/tutorial/path-params.md @@ -24,7 +24,7 @@ Standart Python tip belirteçlerini kullanarak yol parametresinin tipini fonksiy Bu durumda, `item_id` bir `int` olarak tanımlanacaktır. -/// check | "Ek bilgi" +/// check | Ek bilgi Bu sayede, fonksiyon içerisinde hata denetimi, kod tamamlama gibi konularda editör desteğine kavuşacaksınız. @@ -38,7 +38,7 @@ Eğer bu örneği çalıştırıp tarayıcınızda http://127.0.0.1:8000/items/4.2 sayfasında olduğu gibi `int` yerine `float` bir değer verseydik de ortaya çıkardı. -/// check | "Ek bilgi" +/// check | Ek bilgi Böylece, aynı Python tip tanımlaması ile birlikte, **FastAPI** veri doğrulama özelliği sağlar. @@ -87,7 +87,7 @@ Ayrıca, tarayıcınızı -/// check | "Ek bilgi" +/// check | Ek bilgi Üstelik, sadece aynı Python tip tanımlaması ile, **FastAPI** size otomatik ve interaktif (Swagger UI ile entegre) bir dokümantasyon sağlar. @@ -153,13 +153,13 @@ Sonrasında, sınıf içerisinde, mevcut ve geçerli değerler olacak olan sabit {!../../docs_src/path_params/tutorial005.py!} ``` -/// info | "Bilgi" +/// info | Bilgi 3.4 sürümünden beri enumerationlar (ya da enumlar) Python'da mevcuttur. /// -/// tip | "İpucu" +/// tip | İpucu Merak ediyorsanız söyleyeyim, "AlexNet", "ResNet" ve "LeNet" isimleri Makine Öğrenmesi modellerini temsil eder. @@ -199,7 +199,7 @@ Parametreyi, yarattığınız enum olan `ModelName` içerisindeki *enumeration {!../../docs_src/path_params/tutorial005.py!} ``` -/// tip | "İpucu" +/// tip | İpucu `"lenet"` değerine `ModelName.lenet.value` tanımı ile de ulaşabilirsiniz. @@ -256,7 +256,7 @@ Böylece şunun gibi bir kullanım yapabilirsiniz: {!../../docs_src/path_params/tutorial004.py!} ``` -/// tip | "İpucu" +/// tip | İpucu Parametrenin başında `/home/johndoe/myfile.txt` yolunda olduğu gibi (`/`) işareti ile birlikte kullanmanız gerektiği durumlar olabilir. diff --git a/docs/tr/docs/tutorial/query-params.md b/docs/tr/docs/tutorial/query-params.md index 886f5783f..b31d13be4 100644 --- a/docs/tr/docs/tutorial/query-params.md +++ b/docs/tr/docs/tutorial/query-params.md @@ -81,7 +81,7 @@ Aynı şekilde, varsayılan değerlerini `None` olarak atayarak isteğe bağlı Bu durumda, `q` fonksiyon parametresi isteğe bağlı olacak ve varsayılan değer olarak `None` alacaktır. -/// check | "Ek bilgi" +/// check | Ek bilgi Ayrıca, dikkatinizi çekerim ki; **FastAPI**, `item_id` parametresinin bir yol parametresi olduğunu ve `q` parametresinin yol değil bir sorgu parametresi olduğunu fark edecek kadar beceriklidir. @@ -242,7 +242,7 @@ Bu durumda, 3 tane sorgu parametresi var olacaktır: * `skip`, varsayılan değeri `0` olan bir `int`. * `limit`, isteğe bağlı bir `int`. -/// tip | "İpucu" +/// tip | İpucu Ayrıca, [Yol Parametrelerinde](path-params.md#on-tanml-degerler){.internal-link target=_blank} de kullanıldığı şekilde `Enum` sınıfından faydalanabilirsiniz. diff --git a/docs/tr/docs/tutorial/request-forms.md b/docs/tr/docs/tutorial/request-forms.md index 19b6150ff..4ed8ac021 100644 --- a/docs/tr/docs/tutorial/request-forms.md +++ b/docs/tr/docs/tutorial/request-forms.md @@ -2,7 +2,7 @@ İstek gövdesinde JSON verisi yerine form alanlarını karşılamanız gerketiğinde `Form` sınıfını kullanabilirsiniz. -/// info | "Bilgi" +/// info | Bilgi Formları kullanmak için öncelikle `python-multipart` paketini indirmeniz gerekmektedir. @@ -84,13 +84,13 @@ Bu spesifikasyon form alanlar `Form` sınıfıyla tanımlama yaparken `Body`, `Query`, `Path` ve `Cookie` sınıflarında kullandığınız aynı validasyon, örnekler, isimlendirme (örneğin `username` yerine `user-name` kullanımı) ve daha fazla konfigurasyonu kullanabilirsiniz. -/// info | "Bilgi" +/// info | Bilgi `Form` doğrudan `Body` sınıfını miras alan bir sınıftır. /// -/// tip | "İpucu" +/// tip | İpucu Form gövdelerini tanımlamak için `Form` sınıfını kullanmanız gerekir; çünkü bu olmadan parametreler sorgu parametreleri veya gövde (JSON) parametreleri olarak yorumlanır. @@ -102,7 +102,7 @@ HTML formlarının (`
`) verileri sunucuya gönderirken JSON'dan far **FastAPI** bu verilerin JSON yerine doğru şekilde okunmasını sağlayacaktır. -/// note | "Teknik Detaylar" +/// note | Teknik Detaylar Form verileri normalde `application/x-www-form-urlencoded` medya tipiyle kodlanır. @@ -112,7 +112,7 @@ Form kodlama türleri ve form alanları hakkında daha fazla bilgi edinmek istiy /// -/// warning | "Uyarı" +/// warning | Uyarı *Yol operasyonları* içerisinde birden fazla `Form` parametresi tanımlayabilirsiniz ancak bunlarla birlikte JSON verisi kabul eden `Body` alanları tanımlayamazsınız çünkü bu durumda istek gövdesi `application/json` yerine `application/x-www-form-urlencoded` ile kodlanmış olur. diff --git a/docs/tr/docs/tutorial/static-files.md b/docs/tr/docs/tutorial/static-files.md index 8bff59744..da8bed86a 100644 --- a/docs/tr/docs/tutorial/static-files.md +++ b/docs/tr/docs/tutorial/static-files.md @@ -11,7 +11,7 @@ {!../../docs_src/static_files/tutorial001.py!} ``` -/// note | "Teknik Detaylar" +/// note | Teknik Detaylar Projenize dahil etmek için `from starlette.staticfiles import StaticFiles` kullanabilirsiniz. diff --git a/docs/uk/docs/alternatives.md b/docs/uk/docs/alternatives.md index 6821ffe70..1acbe237a 100644 --- a/docs/uk/docs/alternatives.md +++ b/docs/uk/docs/alternatives.md @@ -30,13 +30,13 @@ Це був один із перших прикладів **автоматичної документації API**, і саме це була одна з перших ідей, яка надихнула на «пошук» **FastAPI**. -/// note | "Примітка" +/// note | Примітка Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**. /// -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Мати автоматичний веб-інтерфейс документації API. @@ -56,7 +56,7 @@ Flask — це «мікрофреймворк», він не включає ін Враховуючи простоту Flask, він здавався хорошим підходом для створення API. Наступним, що знайшов, був «Django REST Framework» для Flask. -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин. @@ -98,7 +98,7 @@ def read_url(): Зверніть увагу на схожість у `requests.get(...)` і `@app.get(...)`. -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на * Майте простий та інтуїтивно зрозумілий API. * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом. @@ -118,7 +118,7 @@ def read_url(): Тому, коли говорять про версію 2.0, прийнято говорити «Swagger», а про версію 3+ «OpenAPI». -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми. @@ -147,7 +147,7 @@ Marshmallow створено для забезпечення цих функці Але він був створений до того, як існували підказки типу Python. Отже, щоб визначити кожну схему, вам потрібно використовувати спеціальні утиліти та класи, надані Marshmallow. -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку. @@ -163,13 +163,13 @@ Webargs — це інструмент, створений, щоб забезпе Це чудовий інструмент, і я також часто використовував його, перш ніж створити **FastAPI**. -/// info | "Інформація" +/// info | Інформація Webargs був створений тими ж розробниками Marshmallow. /// -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Мати автоматичну перевірку даних вхідного запиту. @@ -193,13 +193,13 @@ Marshmallow і Webargs забезпечують перевірку, аналіз Редактор тут нічим не може допомогти. І якщо ми змінимо параметри чи схеми Marshmallow і забудемо також змінити цю строку документа YAML, згенерована схема буде застарілою. -/// info | "Інформація" +/// info | Інформація APISpec був створений тими ж розробниками Marshmallow. /// -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Підтримувати відкритий стандарт API, OpenAPI. @@ -225,13 +225,13 @@ APISpec був створений тими ж розробниками Marshmall І ці самі генератори повного стеку були основою [**FastAPI** генераторів проектів](project-generation.md){.internal-link target=_blank}. -/// info | "Інформація" +/// info | Інформація Flask-apispec був створений тими ж розробниками Marshmallow. /// -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку. @@ -251,7 +251,7 @@ Flask-apispec був створений тими ж розробниками Mar Він не дуже добре обробляє вкладені моделі. Отже, якщо тіло JSON у запиті є об’єктом JSON із внутрішніми полями, які, у свою чергу, є вкладеними об’єктами JSON, його неможливо належним чином задокументувати та перевірити. -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Використовувати типи Python, щоб мати чудову підтримку редактора. @@ -263,7 +263,7 @@ Flask-apispec був створений тими ж розробниками Mar Це був один із перших надзвичайно швидких фреймворків Python на основі `asyncio`. Він був дуже схожий на Flask. -/// note | "Технічні деталі" +/// note | Технічні деталі Він використовував `uvloop` замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким. @@ -271,7 +271,7 @@ Flask-apispec був створений тими ж розробниками Mar /// -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Знайти спосіб отримати божевільну продуктивність. @@ -287,7 +287,7 @@ Falcon — ще один високопродуктивний фреймворк Таким чином, перевірка даних, серіалізація та документація повинні виконуватися в коді, а не автоматично. Або вони повинні бути реалізовані як фреймворк поверх Falcon, як Hug. Така сама відмінність спостерігається в інших фреймворках, натхненних дизайном Falcon, що мають один об’єкт запиту та один об’єкт відповіді як параметри. -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Знайти способи отримати чудову продуктивність. @@ -313,7 +313,7 @@ Falcon — ще один високопродуктивний фреймворк Маршрути оголошуються в одному місці з використанням функцій, оголошених в інших місцях (замість використання декораторів, які можна розмістити безпосередньо поверх функції, яка обробляє кінцеву точку). Це ближче до того, як це робить Django, ніж до Flask (і Starlette). Він розділяє в коді речі, які відносно тісно пов’язані. -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic. @@ -335,13 +335,13 @@ Hug був одним із перших фреймворків, який реа Оскільки він заснований на попередньому стандарті для синхронних веб-фреймворків Python (WSGI), він не може працювати з Websockets та іншими речами, хоча він також має високу продуктивність. -/// info | "Інформація" +/// info | Інформація Hug створив Тімоті Крослі, той самий творець `isort`, чудовий інструмент для автоматичного сортування імпорту у файлах Python. /// -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar. @@ -375,7 +375,7 @@ Hug надихнув частину APIStar і був одним із найбі Тепер APIStar — це набір інструментів для перевірки специфікацій OpenAPI, а не веб-фреймворк. -/// info | "Інформація" +/// info | Інформація APIStar створив Том Крісті. Той самий хлопець, який створив: @@ -385,7 +385,7 @@ APIStar створив Том Крісті. Той самий хлопець, я /// -/// check | "Надихнуло **FastAPI** на" +/// check | Надихнуло **FastAPI** на Існувати. @@ -407,7 +407,7 @@ Pydantic — це бібліотека для визначення переві Його можна порівняти з Marshmallow. Хоча він швидший за Marshmallow у тестах. Оскільки він базується на тих самих підказках типу Python, підтримка редактора чудова. -/// check | "**FastAPI** використовує його для" +/// check | **FastAPI** використовує його для Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON). @@ -442,7 +442,7 @@ Starlette надає всі основні функції веб-мікрофр Це одна з головних речей, які **FastAPI** додає зверху, все на основі підказок типу Python (з використанням Pydantic). Це, а також система впровадження залежностей, утиліти безпеки, створення схеми OpenAPI тощо. -/// note | "Технічні деталі" +/// note | Технічні деталі ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього. @@ -450,7 +450,7 @@ ASGI — це новий «стандарт», який розробляєтьс /// -/// check | "**FastAPI** використовує його для" +/// check | **FastAPI** використовує його для Керування всіма основними веб-частинами. Додавання функцій зверху. @@ -468,7 +468,7 @@ Uvicorn — це блискавичний сервер ASGI, побудован Це рекомендований сервер для Starlette і **FastAPI**. -/// check | "**FastAPI** рекомендує це як" +/// check | **FastAPI** рекомендує це як Основний веб-сервер для запуску програм **FastAPI**. diff --git a/docs/uk/docs/tutorial/body-fields.md b/docs/uk/docs/tutorial/body-fields.md index b1f645932..c286744a8 100644 --- a/docs/uk/docs/tutorial/body-fields.md +++ b/docs/uk/docs/tutorial/body-fields.md @@ -122,7 +122,7 @@ `Field` працює так само, як `Query`, `Path` і `Body`, у нього такі самі параметри тощо. -/// note | "Технічні деталі" +/// note | Технічні деталі Насправді, `Query`, `Path` та інші, що ви побачите далі, створюють об'єкти підкласів загального класу `Param`, котрий сам є підкласом класу `FieldInfo` з Pydantic. diff --git a/docs/uk/docs/tutorial/cookie-params.md b/docs/uk/docs/tutorial/cookie-params.md index 40ca4f6e6..229f81b63 100644 --- a/docs/uk/docs/tutorial/cookie-params.md +++ b/docs/uk/docs/tutorial/cookie-params.md @@ -116,7 +116,7 @@ //// -/// note | "Технічні Деталі" +/// note | Технічні Деталі `Cookie` це "сестра" класів `Path` і `Query`. Вони наслідуються від одного батьківського класу `Param`. Але пам'ятайте, що коли ви імпортуєте `Query`, `Path`, `Cookie` та інше з `fastapi`, це фактично функції, що повертають спеціальні класи. diff --git a/docs/uk/docs/tutorial/encoder.md b/docs/uk/docs/tutorial/encoder.md index 39dca9be8..77b0baf4d 100644 --- a/docs/uk/docs/tutorial/encoder.md +++ b/docs/uk/docs/tutorial/encoder.md @@ -42,7 +42,7 @@ Вона не повертає велику строку `str`, яка містить дані у форматі JSON (як строка). Вона повертає стандартну структуру даних Python (наприклад `dict`) із значеннями та підзначеннями, які є сумісними з JSON. -/// note | "Примітка" +/// note | Примітка `jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях. diff --git a/docs/uk/docs/tutorial/first-steps.md b/docs/uk/docs/tutorial/first-steps.md index 6f79c0d1d..63fec207d 100644 --- a/docs/uk/docs/tutorial/first-steps.md +++ b/docs/uk/docs/tutorial/first-steps.md @@ -163,7 +163,7 @@ OpenAPI описує схему для вашого API. І ця схема вк `FastAPI` це клас у Python, який надає всю функціональність для API. -/// note | "Технічні деталі" +/// note | Технічні деталі `FastAPI` це клас, який успадковується безпосередньо від `Starlette`. @@ -198,7 +198,7 @@ https://example.com/items/foo /items/foo ``` -/// info | "Додаткова інформація" +/// info | Додаткова інформація "Шлях" (path) також зазвичай називають "ендпоінтом" (endpoint) або "маршрутом" (route). @@ -250,7 +250,7 @@ https://example.com/items/foo * шлях `/` * використовуючи get операцію -/// info | "`@decorator` Додаткова інформація" +/// info | `@decorator` Додаткова інформація Синтаксис `@something` у Python називається "декоратором". @@ -277,7 +277,7 @@ https://example.com/items/foo * `@app.patch()` * `@app.trace()` -/// tip | "Порада" +/// tip | Порада Ви можете використовувати кожну операцію (HTTP-метод) на свій розсуд. @@ -315,7 +315,7 @@ FastAPI викликатиме її щоразу, коли отримає зап {!../../docs_src/first_steps/tutorial003.py!} ``` -/// note | "Примітка" +/// note | Примітка Якщо не знаєте в чому різниця, подивіться [Конкурентність: *"Поспішаєш?"*](../async.md#in-a-hurry){.internal-link target=_blank}. diff --git a/docs/vi/docs/tutorial/first-steps.md b/docs/vi/docs/tutorial/first-steps.md index d80d78506..934527b8e 100644 --- a/docs/vi/docs/tutorial/first-steps.md +++ b/docs/vi/docs/tutorial/first-steps.md @@ -139,7 +139,7 @@ Bạn cũng có thể sử dụng nó để sinh code tự động, với các c `FastAPI` là một Python class cung cấp tất cả chức năng cho API của bạn. -/// note | "Chi tiết kĩ thuật" +/// note | Chi tiết kĩ thuật `FastAPI` là một class kế thừa trực tiếp `Starlette`. diff --git a/docs/zh/docs/advanced/additional-status-codes.md b/docs/zh/docs/advanced/additional-status-codes.md index f79b853ef..b8f9b0837 100644 --- a/docs/zh/docs/advanced/additional-status-codes.md +++ b/docs/zh/docs/advanced/additional-status-codes.md @@ -18,7 +18,7 @@ {!../../docs_src/additional_status_codes/tutorial001.py!} ``` -/// warning | "警告" +/// warning | 警告 当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。 @@ -28,7 +28,7 @@ FastAPI 不会用模型等对该响应进行序列化。 /// -/// note | "技术细节" +/// note | 技术细节 你也可以使用 `from starlette.responses import JSONResponse`。  diff --git a/docs/zh/docs/advanced/advanced-dependencies.md b/docs/zh/docs/advanced/advanced-dependencies.md index f3fe1e395..bd37ecebb 100644 --- a/docs/zh/docs/advanced/advanced-dependencies.md +++ b/docs/zh/docs/advanced/advanced-dependencies.md @@ -60,7 +60,7 @@ checker(q="somequery") {!../../docs_src/dependencies/tutorial011.py!} ``` -/// tip | "提示" +/// tip | 提示 本章示例有些刻意,也看不出有什么用处。 diff --git a/docs/zh/docs/advanced/behind-a-proxy.md b/docs/zh/docs/advanced/behind-a-proxy.md index 8c4b6bb04..5ed6baa82 100644 --- a/docs/zh/docs/advanced/behind-a-proxy.md +++ b/docs/zh/docs/advanced/behind-a-proxy.md @@ -37,7 +37,7 @@ browser --> proxy proxy --> server ``` -/// tip | "提示" +/// tip | 提示 IP `0.0.0.0` 常用于指程序监听本机或服务器上的所有有效 IP。 @@ -78,7 +78,7 @@ $ uvicorn main:app --root-path /api/v1 Hypercorn 也支持 `--root-path `选项。 -/// note | "技术细节" +/// note | 技术细节 ASGI 规范定义的 `root_path` 就是为了这种用例。 @@ -172,7 +172,7 @@ Uvicorn 预期代理在 `http://127.0.0.1:8000/app` 访问 Uvicorn,而在顶 这个文件把 Traefik 监听端口设置为 `9999`,并设置要使用另一个文件 `routes.toml`。 -/// tip | "提示" +/// tip | 提示 使用端口 9999 代替标准的 HTTP 端口 80,这样就不必使用管理员权限运行(`sudo`)。 @@ -242,7 +242,7 @@ $ uvicorn main:app --root-path /api/v1 } ``` -/// tip | "提示" +/// tip | 提示 注意,就算访问 `http://127.0.0.1:8000/app`,也显示从选项 `--root-path` 中提取的 `/api/v1`,这是 `root_path` 的值。 @@ -289,7 +289,7 @@ $ uvicorn main:app --root-path /api/v1 ## 附加的服务器 -/// warning | "警告" +/// warning | 警告 此用例较难,可以跳过。 @@ -332,7 +332,7 @@ $ uvicorn main:app --root-path /api/v1 } ``` -/// tip | "提示" +/// tip | 提示 注意,自动生成服务器时,`url` 的值 `/api/v1` 提取自 `roog_path`。 @@ -342,7 +342,7 @@ $ uvicorn main:app --root-path /api/v1 -/// tip | "提示" +/// tip | 提示 API 文档与所选的服务器进行交互。 diff --git a/docs/zh/docs/advanced/custom-response.md b/docs/zh/docs/advanced/custom-response.md index 27c026904..85ca1d06d 100644 --- a/docs/zh/docs/advanced/custom-response.md +++ b/docs/zh/docs/advanced/custom-response.md @@ -12,7 +12,7 @@ 并且如果该 `Response` 有一个 JSON 媒体类型(`application/json`),比如使用 `JSONResponse` 或者 `UJSONResponse` 的时候,返回的数据将使用你在路径操作装饰器中声明的任何 Pydantic 的 `response_model` 自动转换(和过滤)。 -/// note | "说明" +/// note | 说明 如果你使用不带有任何媒体类型的响应类,FastAPI 认为你的响应没有任何内容,所以不会在生成的OpenAPI文档中记录响应格式。 @@ -28,7 +28,7 @@ {!../../docs_src/custom_response/tutorial001b.py!} ``` -/// info | "提示" +/// info | 提示 参数 `response_class` 也会用来定义响应的「媒体类型」。 @@ -38,7 +38,7 @@ /// -/// tip | "小贴士" +/// tip | 小贴士 `ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。 @@ -55,7 +55,7 @@ {!../../docs_src/custom_response/tutorial002.py!} ``` -/// info | "提示" +/// info | 提示 参数 `response_class` 也会用来定义响应的「媒体类型」。 @@ -75,13 +75,13 @@ {!../../docs_src/custom_response/tutorial003.py!} ``` -/// warning | "警告" +/// warning | 警告 *路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。 /// -/// info | "提示" +/// info | 提示 当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。 @@ -115,7 +115,7 @@ 要记得你可以使用 `Response` 来返回任何其他东西,甚至创建一个自定义的子类。 -/// note | "技术细节" +/// note | 技术细节 你也可以使用 `from starlette.responses import HTMLResponse`。 @@ -170,7 +170,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 `UJSONResponse` 是一个使用 `ujson` 的可选 JSON 响应。 -/// warning | "警告" +/// warning | 警告 在处理某些边缘情况时,`ujson` 不如 Python 的内置实现那么谨慎。 @@ -180,7 +180,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 {!../../docs_src/custom_response/tutorial001.py!} ``` -/// tip | "小贴士" +/// tip | 小贴士 `ORJSONResponse` 可能是一个更快的选择。 @@ -212,7 +212,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 {!../../docs_src/custom_response/tutorial008.py!} ``` -/// tip | "小贴士" +/// tip | 小贴士 注意在这里,因为我们使用的是不支持 `async` 和 `await` 的标准 `open()`,我们使用普通的 `def` 声明了路径操作。 diff --git a/docs/zh/docs/advanced/dataclasses.md b/docs/zh/docs/advanced/dataclasses.md index f33c05ff4..7d977a0c7 100644 --- a/docs/zh/docs/advanced/dataclasses.md +++ b/docs/zh/docs/advanced/dataclasses.md @@ -20,7 +20,7 @@ FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 数据类的和运作方式与 Pydantic 模型相同。实际上,它的底层使用的也是 Pydantic。 -/// info | "说明" +/// info | 说明 注意,数据类不支持 Pydantic 模型的所有功能。 diff --git a/docs/zh/docs/advanced/events.md b/docs/zh/docs/advanced/events.md index e5b44f321..a34c03f3f 100644 --- a/docs/zh/docs/advanced/events.md +++ b/docs/zh/docs/advanced/events.md @@ -4,7 +4,7 @@ 事件函数既可以声明为异步函数(`async def`),也可以声明为普通函数(`def`)。 -/// warning | "警告" +/// warning | 警告 **FastAPI** 只执行主应用中的事件处理器,不执行[子应用 - 挂载](sub-applications.md){.internal-link target=_blank}中的事件处理器。 @@ -34,13 +34,13 @@ 此处,`shutdown` 事件处理器函数在 `log.txt` 中写入一行文本 `Application shutdown`。 -/// info | "说明" +/// info | 说明 `open()` 函数中,`mode="a"` 指的是**追加**。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。 /// -/// tip | "提示" +/// tip | 提示 注意,本例使用 Python `open()` 标准函数与文件交互。 @@ -52,7 +52,7 @@ /// -/// info | "说明" +/// info | 说明 有关事件处理器的详情,请参阅 Starlette 官档 - 事件。 diff --git a/docs/zh/docs/advanced/middleware.md b/docs/zh/docs/advanced/middleware.md index 525dc89ac..78a7d559c 100644 --- a/docs/zh/docs/advanced/middleware.md +++ b/docs/zh/docs/advanced/middleware.md @@ -43,7 +43,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** 为常见用例提供了一些中间件,下面介绍怎么使用这些中间件。 -/// note | "技术细节" +/// note | 技术细节 以下几个示例中也可以使用 `from starlette.middleware.something import SomethingMiddleware`。 diff --git a/docs/zh/docs/advanced/openapi-callbacks.md b/docs/zh/docs/advanced/openapi-callbacks.md index dc1c2539b..601cbdb5d 100644 --- a/docs/zh/docs/advanced/openapi-callbacks.md +++ b/docs/zh/docs/advanced/openapi-callbacks.md @@ -35,7 +35,7 @@ API 的用户 (外部开发者)要在您的 API 内使用 POST 请求创建 {!../../docs_src/openapi_callbacks/tutorial001.py!} ``` -/// tip | "提示" +/// tip | 提示 `callback_url` 查询参数使用 Pydantic 的 URL 类型。 @@ -64,7 +64,7 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) 本例没有实现回调本身(只是一行代码),只有文档部分。 -/// tip | "提示" +/// tip | 提示 实际的回调只是 HTTP 请求。 @@ -80,7 +80,7 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) 我们要使用与存档*外部 API* 相同的知识……通过创建外部 API 要实现的*路径操作*(您的 API 要调用的)。 -/// tip | "提示" +/// tip | 提示 编写存档回调的代码时,假设您是*外部开发者*可能会用的上。并且您当前正在实现的是*外部 API*,不是*您自己的 API*。 @@ -163,7 +163,7 @@ JSON 请求体包含如下内容: } ``` -/// tip | "提示" +/// tip | 提示 注意,回调 URL包含 `callback_url` (`https://www.external.org/events`)中的查询参数,还有 JSON 请求体内部的发票 ID(`2expen51ve`)。 @@ -179,7 +179,7 @@ JSON 请求体包含如下内容: {!../../docs_src/openapi_callbacks/tutorial001.py!} ``` -/// tip | "提示" +/// tip | 提示 注意,不能把路由本身(`invoices_callback_router`)传递给 `callback=`,要传递 `invoices_callback_router.routes` 中的 `.routes` 属性。 diff --git a/docs/zh/docs/advanced/response-cookies.md b/docs/zh/docs/advanced/response-cookies.md index 5772664b0..2d56c6e9b 100644 --- a/docs/zh/docs/advanced/response-cookies.md +++ b/docs/zh/docs/advanced/response-cookies.md @@ -40,7 +40,7 @@ ### 更多信息 -/// note | "技术细节" +/// note | 技术细节 你也可以使用`from starlette.responses import Response` 或者 `from starlette.responses import JSONResponse`。 diff --git a/docs/zh/docs/advanced/response-directly.md b/docs/zh/docs/advanced/response-directly.md index 9d191c622..934f60ef6 100644 --- a/docs/zh/docs/advanced/response-directly.md +++ b/docs/zh/docs/advanced/response-directly.md @@ -14,7 +14,7 @@ 事实上,你可以返回任意 `Response` 或者任意 `Response` 的子类。 -/// tip | "小贴士" +/// tip | 小贴士 `JSONResponse` 本身是一个 `Response` 的子类。 @@ -39,7 +39,7 @@ {!../../docs_src/response_directly/tutorial001.py!} ``` -/// note | "技术细节" +/// note | 技术细节 你也可以使用 `from starlette.responses import JSONResponse`。 diff --git a/docs/zh/docs/advanced/response-headers.md b/docs/zh/docs/advanced/response-headers.md index d593fdccc..e7861ad0c 100644 --- a/docs/zh/docs/advanced/response-headers.md +++ b/docs/zh/docs/advanced/response-headers.md @@ -25,7 +25,7 @@ ``` -/// note | "技术细节" +/// note | 技术细节 你也可以使用`from starlette.responses import Response`或`from starlette.responses import JSONResponse`。 diff --git a/docs/zh/docs/advanced/security/index.md b/docs/zh/docs/advanced/security/index.md index 836086ae2..267e7ced7 100644 --- a/docs/zh/docs/advanced/security/index.md +++ b/docs/zh/docs/advanced/security/index.md @@ -4,7 +4,7 @@ 除 [教程 - 用户指南: 安全性](../../tutorial/security/index.md){.internal-link target=_blank} 中涵盖的功能之外,还有一些额外的功能来处理安全性. -/// tip | "小贴士" +/// tip | 小贴士 接下来的章节 **并不一定是 "高级的"**. diff --git a/docs/zh/docs/advanced/security/oauth2-scopes.md b/docs/zh/docs/advanced/security/oauth2-scopes.md index d6354230e..b26522113 100644 --- a/docs/zh/docs/advanced/security/oauth2-scopes.md +++ b/docs/zh/docs/advanced/security/oauth2-scopes.md @@ -10,7 +10,7 @@ OAuth2 也是脸书、谷歌、GitHub、微软、推特等第三方身份验证 本章介绍如何在 **FastAPI** 应用中使用 OAuth2 作用域管理验证与授权。 -/// warning | "警告" +/// warning | 警告 本章内容较难,刚接触 FastAPI 的新手可以跳过。 @@ -46,7 +46,7 @@ OpenAPI 中(例如 API 文档)可以定义**安全方案**。 * 脸书和 Instagram 使用 `instagram_basic` * 谷歌使用 `https://www.googleapis.com/auth/drive` -/// info | "说明" +/// info | 说明 OAuth2 中,**作用域**只是声明特定权限的字符串。 @@ -94,7 +94,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 这样,返回的 JWT 令牌中就包含了作用域。 -/// danger | "危险" +/// danger | 危险 为了简明起见,本例把接收的作用域直接添加到了令牌里。 @@ -122,7 +122,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 本例要求使用作用域 `me`(还可以使用更多作用域)。 -/// note | "笔记" +/// note | 笔记 不必在不同位置添加不同的作用域。 @@ -134,7 +134,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 {!../../docs_src/security/tutorial005.py!} ``` -/// info | "技术细节" +/// info | 技术细节 `Security` 实际上是 `Depends` 的子类,而且只比 `Depends` 多一个参数。 @@ -231,7 +231,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 * `security_scopes.scopes` 包含*路径操作* `read_users_me` 的 `["me"]`,因为它在依赖项里被声明 * `security_scopes.scopes` 包含用于*路径操作* `read_system_status` 的 `[]`(空列表),并且它的依赖项 `get_current_user` 也没有声明任何 `scope` -/// tip | "提示" +/// tip | 提示 此处重要且**神奇**的事情是,`get_current_user` 检查每个*路径操作*时可以使用不同的 `scopes` 列表。 @@ -275,7 +275,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 最安全的是代码流,但实现起来更复杂,而且需要更多步骤。因为它更复杂,很多第三方身份验证应用最终建议使用隐式流。 -/// note | "笔记" +/// note | 笔记 每个身份验证应用都会采用不同方式会命名流,以便融合入自己的品牌。 diff --git a/docs/zh/docs/advanced/templates.md b/docs/zh/docs/advanced/templates.md index 1159302a9..7692aa47b 100644 --- a/docs/zh/docs/advanced/templates.md +++ b/docs/zh/docs/advanced/templates.md @@ -31,20 +31,20 @@ $ pip install jinja2 {!../../docs_src/templates/tutorial001.py!} ``` -/// note | "笔记" +/// note | 笔记 在FastAPI 0.108.0,Starlette 0.29.0之前,`name`是第一个参数。 并且,在此之前,`request`对象是作为context的一部分以键值对的形式传递的。 /// -/// tip | "提示" +/// tip | 提示 通过声明 `response_class=HTMLResponse`,API 文档就能识别响应的对象是 HTML。 /// -/// note | "技术细节" +/// note | 技术细节 您还可以使用 `from starlette.templating import Jinja2Templates`。 diff --git a/docs/zh/docs/advanced/testing-dependencies.md b/docs/zh/docs/advanced/testing-dependencies.md index c3d912e2f..b4b5b32df 100644 --- a/docs/zh/docs/advanced/testing-dependencies.md +++ b/docs/zh/docs/advanced/testing-dependencies.md @@ -32,7 +32,7 @@ {!../../docs_src/dependency_testing/tutorial001.py!} ``` -/// tip | "提示" +/// tip | 提示 **FastAPI** 应用中的任何位置都可以实现覆盖依赖项。 @@ -48,7 +48,7 @@ FastAPI 可以覆盖这些位置的依赖项。 app.dependency_overrides = {} ``` -/// tip | "提示" +/// tip | 提示 如果只在某些测试时覆盖依赖项,您可以在测试开始时(在测试函数内)设置覆盖依赖项,并在结束时(在测试函数结尾)重置覆盖依赖项。 diff --git a/docs/zh/docs/advanced/testing-websockets.md b/docs/zh/docs/advanced/testing-websockets.md index a69053f24..b30939b97 100644 --- a/docs/zh/docs/advanced/testing-websockets.md +++ b/docs/zh/docs/advanced/testing-websockets.md @@ -8,7 +8,7 @@ {!../../docs_src/app_testing/tutorial002.py!} ``` -/// note | "笔记" +/// note | 笔记 更多细节详见 Starlette 官档 - 测试 WebSockets。 diff --git a/docs/zh/docs/advanced/using-request-directly.md b/docs/zh/docs/advanced/using-request-directly.md index 992458217..f01644de6 100644 --- a/docs/zh/docs/advanced/using-request-directly.md +++ b/docs/zh/docs/advanced/using-request-directly.md @@ -35,7 +35,7 @@ 把*路径操作函数*的参数类型声明为 `Request`,**FastAPI** 就能把 `Request` 传递到参数里。 -/// tip | "提示" +/// tip | 提示 注意,本例除了声明请求参数之外,还声明了路径参数。 @@ -49,7 +49,7 @@ 更多细节详见 Starlette 官档 - `Request` 对象。 -/// note | "技术细节" +/// note | 技术细节 您也可以使用 `from starlette.requests import Request`。 diff --git a/docs/zh/docs/advanced/websockets.md b/docs/zh/docs/advanced/websockets.md index 15ae84c58..dcd4cd5a9 100644 --- a/docs/zh/docs/advanced/websockets.md +++ b/docs/zh/docs/advanced/websockets.md @@ -46,7 +46,7 @@ $ pip install websockets {!../../docs_src/websockets/tutorial001.py!} ``` -/// note | "技术细节" +/// note | 技术细节 您也可以使用 `from starlette.websockets import WebSocket`。 diff --git a/docs/zh/docs/contributing.md b/docs/zh/docs/contributing.md index 85b341a8d..cad093c2a 100644 --- a/docs/zh/docs/contributing.md +++ b/docs/zh/docs/contributing.md @@ -138,7 +138,7 @@ $ pip install -r requirements.txt 这样,你不必再去重新"安装"你的本地版本即可测试所有更改。 -/// note | "技术细节" +/// note | 技术细节 仅当你使用此项目中的 `requirements.txt` 安装而不是直接使用 `pip install fastapi` 安装时,才会发生这种情况。 diff --git a/docs/zh/docs/fastapi-cli.md b/docs/zh/docs/fastapi-cli.md index 00235bd02..f532c7fb7 100644 --- a/docs/zh/docs/fastapi-cli.md +++ b/docs/zh/docs/fastapi-cli.md @@ -80,7 +80,7 @@ FastAPI CLI 接收你的 Python 程序路径,自动检测包含 FastAPI 的变 在大多数情况下,你会(且应该)有一个“终止代理”在上层为你处理 HTTPS,这取决于你如何部署应用程序,你的服务提供商可能会为你处理此事,或者你可能需要自己设置。 -/// tip | "提示" +/// tip | 提示 你可以在 [deployment documentation](deployment/index.md){.internal-link target=_blank} 获得更多信息。 diff --git a/docs/zh/docs/help-fastapi.md b/docs/zh/docs/help-fastapi.md index fc47ed89d..09f37a44b 100644 --- a/docs/zh/docs/help-fastapi.md +++ b/docs/zh/docs/help-fastapi.md @@ -108,7 +108,7 @@ 快加入 👥 Discord 聊天服务器 👥 和 FastAPI 社区里的小伙伴一起哈皮吧。 -/// tip | "提示" +/// tip | 提示 如有问题,请在 GitHub Issues 里提问,在这里更容易得到 [FastAPI 专家](fastapi-people.md#_3){.internal-link target=_blank}的帮助。 diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md index 64afd99af..318e10fd7 100644 --- a/docs/zh/docs/tutorial/bigger-applications.md +++ b/docs/zh/docs/tutorial/bigger-applications.md @@ -414,7 +414,7 @@ from .routers.users import router 它将包含来自该路由器的所有路由作为其一部分。 -/// note | "技术细节" +/// note | 技术细节 实际上,它将在内部为声明在 `APIRouter` 中的每个*路径操作*创建一个*路径操作*。 @@ -477,7 +477,7 @@ from .routers.users import router 它将与通过 `app.include_router()` 添加的所有其他*路径操作*一起正常运行。 -/// info | "特别的技术细节" +/// info | 特别的技术细节 **注意**:这是一个非常技术性的细节,你也许可以**直接跳过**。 diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md index ac59d7e6a..9aeb481ef 100644 --- a/docs/zh/docs/tutorial/body-fields.md +++ b/docs/zh/docs/tutorial/body-fields.md @@ -58,7 +58,7 @@ //// -/// warning | "警告" +/// warning | 警告 注意,与从 `fastapi` 导入 `Query`,`Path`、`Body` 不同,要直接从 `pydantic` 导入 `Field` 。 @@ -122,7 +122,7 @@ Prefer to use the `Annotated` version if possible. `Field` 的工作方式和 `Query`、`Path`、`Body` 相同,参数也相同。 -/// note | "技术细节" +/// note | 技术细节 实际上,`Query`、`Path` 都是 `Params` 的子类,而 `Params` 类又是 Pydantic 中 `FieldInfo` 的子类。 @@ -134,7 +134,7 @@ Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。 /// -/// tip | "提示" +/// tip | 提示 注意,模型属性的类型、默认值及 `Field` 的代码结构与*路径操作函数*的参数相同,只不过是用 `Field` 替换了`Path`、`Query`、`Body`。 diff --git a/docs/zh/docs/tutorial/body-updates.md b/docs/zh/docs/tutorial/body-updates.md index 5e9008d6a..9372e1dfd 100644 --- a/docs/zh/docs/tutorial/body-updates.md +++ b/docs/zh/docs/tutorial/body-updates.md @@ -34,7 +34,7 @@ 即,只发送要更新的数据,其余数据保持不变。 -/// note | "笔记" +/// note | 笔记 `PATCH` 没有 `PUT` 知名,也怎么不常用。 @@ -89,14 +89,14 @@ {!../../docs_src/body_updates/tutorial002.py!} ``` -/// tip | "提示" +/// tip | 提示 实际上,HTTP `PUT` 也可以完成相同的操作。 但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。 /// -/// note | "笔记" +/// note | 笔记 注意,输入模型仍需验证。 diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md index 67a7f28e0..bf3117beb 100644 --- a/docs/zh/docs/tutorial/body.md +++ b/docs/zh/docs/tutorial/body.md @@ -8,7 +8,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 使用 Pydantic 模型声明**请求体**,能充分利用它的功能和优点。 -/// info | "说明" +/// info | 说明 发送数据使用 `POST`(最常用)、`PUT`、`DELETE`、`PATCH` 等操作。 @@ -149,7 +149,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 -/// tip | "提示" +/// tip | 提示 使用 PyCharm 编辑器时,推荐安装 Pydantic PyCharm 插件。 @@ -233,7 +233,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 - 类型是(`int`、`float`、`str`、`bool` 等)**单类型**的参数,是**查询**参数 - 类型是 **Pydantic 模型**的参数,是**请求体** -/// note | "笔记" +/// note | 笔记 因为默认值是 `None`, FastAPI 会把 `q` 当作可选参数。 diff --git a/docs/zh/docs/tutorial/cookie-params.md b/docs/zh/docs/tutorial/cookie-params.md index b01c28238..762dca766 100644 --- a/docs/zh/docs/tutorial/cookie-params.md +++ b/docs/zh/docs/tutorial/cookie-params.md @@ -117,7 +117,7 @@ //// -/// note | "技术细节" +/// note | 技术细节 `Cookie` 、`Path` 、`Query` 是**兄弟类**,都继承自共用的 `Param` 类。 @@ -125,7 +125,7 @@ /// -/// info | "说明" +/// info | 说明 必须使用 `Cookie` 声明 cookie 参数,否则该参数会被解释为查询参数。 diff --git a/docs/zh/docs/tutorial/cors.md b/docs/zh/docs/tutorial/cors.md index 1166d5c97..84c435c97 100644 --- a/docs/zh/docs/tutorial/cors.md +++ b/docs/zh/docs/tutorial/cors.md @@ -78,7 +78,7 @@ 更多关于 CORS 的信息,请查看 Mozilla CORS 文档。 -/// note | "技术细节" +/// note | 技术细节 你也可以使用 `from starlette.middleware.cors import CORSMiddleware`。 diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index c7cfe0531..c202c977b 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -20,7 +20,7 @@ 路径操作装饰器依赖项(以下简称为**“路径装饰器依赖项”**)的执行或解析方式和普通依赖项一样,但就算这些依赖项会返回值,它们的值也不会传递给*路径操作函数*。 -/// tip | "提示" +/// tip | 提示 有些编辑器会检查代码中没使用过的函数参数,并显示错误提示。 @@ -30,7 +30,7 @@ /// -/// info | "说明" +/// info | 说明 本例中,使用的是自定义响应头 `X-Key` 和 `X-Token`。 diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md index a30313719..792b6784d 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md @@ -10,7 +10,7 @@ FastAPI支持在完成后执行一些上下文管理器完成的。 diff --git a/docs/zh/docs/tutorial/dependencies/index.md b/docs/zh/docs/tutorial/dependencies/index.md index b039e1654..e0d2c5f70 100644 --- a/docs/zh/docs/tutorial/dependencies/index.md +++ b/docs/zh/docs/tutorial/dependencies/index.md @@ -75,7 +75,7 @@ FastAPI 提供了简单易用,但功能强大的** read_users 这样,只编写一次代码,**FastAPI** 就可以为多个*路径操作*共享这段代码 。 -/// check | "检查" +/// check | 检查 注意,无需创建专门的类,并将之传递给 **FastAPI** 以进行「注册」或执行类似的操作。 @@ -118,7 +118,7 @@ common_parameters --> read_users 上述这些操作都是可行的,**FastAPI** 知道该怎么处理。 -/// note | "笔记" +/// note | 笔记 如里不了解异步,请参阅[异步:*“着急了?”*](../../async.md){.internal-link target=_blank} 一章中 `async` 和 `await` 的内容。 diff --git a/docs/zh/docs/tutorial/dependencies/sub-dependencies.md b/docs/zh/docs/tutorial/dependencies/sub-dependencies.md index dd4c60857..e0b75aa0c 100644 --- a/docs/zh/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/zh/docs/tutorial/dependencies/sub-dependencies.md @@ -41,7 +41,7 @@ FastAPI 支持创建含**子依赖项**的依赖项。 {!../../docs_src/dependencies/tutorial005.py!} ``` -/// info | "信息" +/// info | 信息 注意,这里在*路径操作函数*中只声明了一个依赖项,即 `query_or_cookie_extractor` 。 @@ -81,7 +81,7 @@ async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False 但它依然非常强大,能够声明任意嵌套深度的「图」或树状的依赖结构。 -/// tip | "提示" +/// tip | 提示 这些简单的例子现在看上去虽然没有什么实用价值, diff --git a/docs/zh/docs/tutorial/extra-models.md b/docs/zh/docs/tutorial/extra-models.md index 6649b06c7..982cf15fb 100644 --- a/docs/zh/docs/tutorial/extra-models.md +++ b/docs/zh/docs/tutorial/extra-models.md @@ -8,7 +8,7 @@ * **输出模型**不应含密码 * **数据库模型**需要加密的密码 -/// danger | "危险" +/// danger | 危险 千万不要存储用户的明文密码。始终存储可以进行验证的**安全哈希值**。 @@ -146,7 +146,7 @@ UserInDB( ) ``` -/// warning | "警告" +/// warning | 警告 辅助的附加函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全机制。 @@ -194,7 +194,7 @@ FastAPI 可以做得更好。 为此,请使用 Python 标准类型提示 `typing.Union`: -/// note | "笔记" +/// note | 笔记 定义 `Union` 类型时,要把详细的类型写在前面,然后是不太详细的类型。下例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。 diff --git a/docs/zh/docs/tutorial/first-steps.md b/docs/zh/docs/tutorial/first-steps.md index b9bbca193..2f573501c 100644 --- a/docs/zh/docs/tutorial/first-steps.md +++ b/docs/zh/docs/tutorial/first-steps.md @@ -140,7 +140,7 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送 `FastAPI` 是一个为你的 API 提供了所有功能的 Python 类。 -/// note | "技术细节" +/// note | 技术细节 `FastAPI` 是直接从 `Starlette` 继承的类。 @@ -260,7 +260,7 @@ https://example.com/items/foo * 请求路径为 `/` * 使用 get 操作 -/// info | "`@decorator` Info" +/// info | `@decorator` Info `@something` 语法在 Python 中被称为「装饰器」。 diff --git a/docs/zh/docs/tutorial/handling-errors.md b/docs/zh/docs/tutorial/handling-errors.md index 0820c363c..799e81eb2 100644 --- a/docs/zh/docs/tutorial/handling-errors.md +++ b/docs/zh/docs/tutorial/handling-errors.md @@ -67,7 +67,7 @@ ``` -/// tip | "提示" +/// tip | 提示 触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。 @@ -116,7 +116,7 @@ ``` -/// note | "技术细节" +/// note | 技术细节 `from starlette.requests import Request` 和 `from starlette.responses import JSONResponse` 也可以用于导入 `Request` 和 `JSONResponse`。 @@ -176,7 +176,7 @@ path -> item_id ### `RequestValidationError` vs `ValidationError` -/// warning | "警告" +/// warning | 警告 如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。 @@ -203,7 +203,7 @@ path -> item_id ``` -/// note | "技术细节" +/// note | 技术细节 还可以使用 `from starlette.responses import PlainTextResponse`。 diff --git a/docs/zh/docs/tutorial/header-params.md b/docs/zh/docs/tutorial/header-params.md index 4de8bf4df..c45a6b095 100644 --- a/docs/zh/docs/tutorial/header-params.md +++ b/docs/zh/docs/tutorial/header-params.md @@ -116,7 +116,7 @@ //// -/// note | "技术细节" +/// note | 技术细节 `Header` 是 `Path`、`Query`、`Cookie` 的**兄弟类**,都继承自共用的 `Param` 类。 @@ -124,7 +124,7 @@ /// -/// info | "说明" +/// info | 说明 必须使用 `Header` 声明 header 参数,否则该参数会被解释为查询参数。 @@ -198,7 +198,7 @@ //// -/// warning | "警告" +/// warning | 警告 注意,使用 `convert_underscores = False` 要慎重,有些 HTTP 代理和服务器不支持使用带有下划线的请求头。 diff --git a/docs/zh/docs/tutorial/metadata.md b/docs/zh/docs/tutorial/metadata.md index 7252db9f6..2398f3e01 100644 --- a/docs/zh/docs/tutorial/metadata.md +++ b/docs/zh/docs/tutorial/metadata.md @@ -46,7 +46,7 @@ 注意你可以在描述内使用 Markdown,例如「login」会显示为粗体(**login**)以及「fancy」会显示为斜体(_fancy_)。 -/// tip | "提示" +/// tip | 提示 不必为你使用的所有标签都添加元数据。 @@ -60,7 +60,7 @@ {!../../docs_src/metadata/tutorial004.py!} ``` -/// info | "信息" +/// info | 信息 阅读更多关于标签的信息[路径操作配置](path-operation-configuration.md#tags){.internal-link target=_blank}。 diff --git a/docs/zh/docs/tutorial/middleware.md b/docs/zh/docs/tutorial/middleware.md index fb2874ba3..8076f8d52 100644 --- a/docs/zh/docs/tutorial/middleware.md +++ b/docs/zh/docs/tutorial/middleware.md @@ -11,7 +11,7 @@ * 它可以对该**响应**做些什么或者执行任何需要的代码. * 然后它返回这个 **响应**. -/// note | "技术细节" +/// note | 技术细节 如果你使用了 `yield` 关键字依赖, 依赖中的退出代码将在执行中间件*后*执行. @@ -43,7 +43,7 @@ /// -/// note | "技术细节" +/// note | 技术细节 你也可以使用 `from starlette.requests import Request`. diff --git a/docs/zh/docs/tutorial/path-operation-configuration.md b/docs/zh/docs/tutorial/path-operation-configuration.md index 12e1f24ba..add370d1c 100644 --- a/docs/zh/docs/tutorial/path-operation-configuration.md +++ b/docs/zh/docs/tutorial/path-operation-configuration.md @@ -2,7 +2,7 @@ *路径操作装饰器*支持多种配置参数。 -/// warning | "警告" +/// warning | 警告 注意:以下参数应直接传递给**路径操作装饰器**,不能传递给*路径操作函数*。 @@ -22,7 +22,7 @@ 状态码在响应中使用,并会被添加到 OpenAPI 概图。 -/// note | "技术细节" +/// note | 技术细节 也可以使用 `from starlette import status` 导入状态码。 @@ -72,13 +72,13 @@ OpenAPI 概图会自动添加标签,供 API 文档接口使用: {!../../docs_src/path_operation_configuration/tutorial005.py!} ``` -/// info | "说明" +/// info | 说明 注意,`response_description` 只用于描述响应,`description` 一般则用于描述*路径操作*。 /// -/// check | "检查" +/// check | 检查 OpenAPI 规定每个*路径操作*都要有响应描述。 diff --git a/docs/zh/docs/tutorial/path-params-numeric-validations.md b/docs/zh/docs/tutorial/path-params-numeric-validations.md index 29197ac53..3a1ebdbca 100644 --- a/docs/zh/docs/tutorial/path-params-numeric-validations.md +++ b/docs/zh/docs/tutorial/path-params-numeric-validations.md @@ -222,7 +222,7 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参 /// -/// note | "技术细节" +/// note | 技术细节 当你从 `fastapi` 导入 `Query`、`Path` 和其他同类对象时,它们实际上是函数。 diff --git a/docs/zh/docs/tutorial/path-params.md b/docs/zh/docs/tutorial/path-params.md index a29ee0e2b..0666783e2 100644 --- a/docs/zh/docs/tutorial/path-params.md +++ b/docs/zh/docs/tutorial/path-params.md @@ -24,7 +24,7 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(** 本例把 `item_id` 的类型声明为 `int`。 -/// check | "检查" +/// check | 检查 类型声明将为函数提供错误检查、代码补全等编辑器支持。 @@ -38,7 +38,7 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(** {"item_id":3} ``` -/// check | "检查" +/// check | 检查 注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。 @@ -69,7 +69,7 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(** 值的类型不是 `int ` 而是浮点数(`float`)时也会显示同样的错误,比如: http://127.0.0.1:8000/items/4.2。 -/// check | "检查" +/// check | 检查 **FastAPI** 使用 Python 类型声明实现了数据校验。 @@ -85,7 +85,7 @@ FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(** -/// check | "检查" +/// check | 检查 还是使用 Python 类型声明,**FastAPI** 提供了(集成 Swagger UI 的)API 文档。 @@ -143,13 +143,13 @@ FastAPI 充分地利用了 枚举(即 enums)。 /// -/// tip | "提示" +/// tip | 提示 **AlexNet**、**ResNet**、**LeNet** 是机器学习模型。 @@ -189,7 +189,7 @@ Python 3.4 及之后版本支持`python-multipart`。 @@ -28,7 +28,7 @@ FastAPI 支持同时使用 `File` 和 `Form` 定义文件和表单字段。 声明文件可以使用 `bytes` 或 `UploadFile` 。 -/// warning | "警告" +/// warning | 警告 可在一个*路径操作*中声明多个 `File` 与 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码为 `multipart/form-data`,不是 `application/json`。 diff --git a/docs/zh/docs/tutorial/request-forms.md b/docs/zh/docs/tutorial/request-forms.md index 94c8839b3..5938bb83d 100644 --- a/docs/zh/docs/tutorial/request-forms.md +++ b/docs/zh/docs/tutorial/request-forms.md @@ -2,7 +2,7 @@ 接收的不是 JSON,而是表单字段时,要使用 `Form`。 -/// info | "说明" +/// info | 说明 要使用表单,需预先安装 `python-multipart`。 @@ -32,13 +32,13 @@ 使用 `Form` 可以声明与 `Body` (及 `Query`、`Path`、`Cookie`)相同的元数据和验证。 -/// info | "说明" +/// info | 说明 `Form` 是直接继承自 `Body` 的类。 /// -/// tip | "提示" +/// tip | 提示 声明表单体要显式使用 `Form` ,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。 @@ -50,7 +50,7 @@ **FastAPI** 要确保从正确的位置读取数据,而不是读取 JSON。 -/// note | "技术细节" +/// note | 技术细节 表单数据的「媒体类型」编码一般为 `application/x-www-form-urlencoded`。 @@ -60,7 +60,7 @@ /// -/// warning | "警告" +/// warning | 警告 可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。 diff --git a/docs/zh/docs/tutorial/response-model.md b/docs/zh/docs/tutorial/response-model.md index 40fb40720..fd0facca8 100644 --- a/docs/zh/docs/tutorial/response-model.md +++ b/docs/zh/docs/tutorial/response-model.md @@ -51,7 +51,7 @@ FastAPI 将使用此 `response_model` 来: * 会将输出数据限制在该模型定义内。下面我们会看到这一点有多重要。 -/// note | "技术细节" +/// note | 技术细节 响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。 diff --git a/docs/zh/docs/tutorial/response-status-code.md b/docs/zh/docs/tutorial/response-status-code.md index 55bf502ae..1e5e7964f 100644 --- a/docs/zh/docs/tutorial/response-status-code.md +++ b/docs/zh/docs/tutorial/response-status-code.md @@ -12,7 +12,7 @@ {!../../docs_src/response_status_code/tutorial001.py!} ``` -/// note | "笔记" +/// note | 笔记 注意,`status_code` 是(`get`、`post` 等)**装饰器**方法中的参数。与之前的参数和请求体不同,不是*路径操作函数*的参数。 @@ -20,7 +20,7 @@ `status_code` 参数接收表示 HTTP 状态码的数字。 -/// info | "说明" +/// info | 说明 `status_code` 还能接收 `IntEnum` 类型,比如 Python 的 `http.HTTPStatus`。 @@ -33,7 +33,7 @@ -/// note | "笔记" +/// note | 笔记 某些响应状态码表示响应没有响应体(参阅下一章)。 @@ -43,7 +43,7 @@ FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。 ## 关于 HTTP 状态码 -/// note | "笔记" +/// note | 笔记 如果已经了解 HTTP 状态码,请跳到下一章。 @@ -66,7 +66,7 @@ FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。 * 对于来自客户端的一般错误,可以只使用 `400` * `500` 及以上的状态码用于表示服务器端错误。几乎永远不会直接使用这些状态码。应用代码或服务器出现问题时,会自动返回这些状态代码 -/// tip | "提示" +/// tip | 提示 状态码及适用场景的详情,请参阅 MDN 的 HTTP 状态码文档。 @@ -94,7 +94,7 @@ FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。 -/// note | "技术细节" +/// note | 技术细节 也可以使用 `from starlette import status`。 diff --git a/docs/zh/docs/tutorial/security/first-steps.md b/docs/zh/docs/tutorial/security/first-steps.md index 8294b6444..561721f6e 100644 --- a/docs/zh/docs/tutorial/security/first-steps.md +++ b/docs/zh/docs/tutorial/security/first-steps.md @@ -52,7 +52,7 @@ ## 运行 -/// info | "说明" +/// info | 说明 先安装 `python-multipart`。 @@ -82,7 +82,7 @@ $ uvicorn main:app --reload -/// check | "Authorize 按钮!" +/// check | Authorize 按钮! 页面右上角出现了一个「**Authorize**」按钮。 @@ -94,7 +94,7 @@ $ uvicorn main:app --reload -/// note | "笔记" +/// note | 笔记 目前,在表单中输入内容不会有任何反应,后文会介绍相关内容。 @@ -140,7 +140,7 @@ OAuth2 的设计目标是为了让后端或 API 独立于服务器验证用户 本例使用 **OAuth2** 的 **Password** 流以及 **Bearer** 令牌(`Token`)。为此要使用 `OAuth2PasswordBearer` 类。 -/// info | "说明" +/// info | 说明 `Bearer` 令牌不是唯一的选择。 @@ -158,7 +158,7 @@ OAuth2 的设计目标是为了让后端或 API 独立于服务器验证用户 {!../../docs_src/security/tutorial001.py!} ``` -/// tip | "提示" +/// tip | 提示 在此,`tokenUrl="token"` 指向的是暂未创建的相对 URL `token`。这个相对 URL 相当于 `./token`。 @@ -172,7 +172,7 @@ OAuth2 的设计目标是为了让后端或 API 独立于服务器验证用户 接下来,学习如何创建实际的路径操作。 -/// info | "说明" +/// info | 说明 严苛的 **Pythonista** 可能不喜欢用 `tokenUrl` 这种命名风格代替 `token_url`。 @@ -202,7 +202,7 @@ oauth2_scheme(some, parameters) **FastAPI** 使用依赖项在 OpenAPI 概图(及 API 文档)中定义**安全方案**。 -/// info | "技术细节" +/// info | 技术细节 **FastAPI** 使用(在依赖项中声明的)类 `OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,这是因为它继承自 `fastapi.security.oauth2.OAuth2`,而该类又是继承自`fastapi.security.base.SecurityBase`。 diff --git a/docs/zh/docs/tutorial/security/get-current-user.md b/docs/zh/docs/tutorial/security/get-current-user.md index 97461817a..e0f763b30 100644 --- a/docs/zh/docs/tutorial/security/get-current-user.md +++ b/docs/zh/docs/tutorial/security/get-current-user.md @@ -55,7 +55,7 @@ 这有助于在函数内部使用代码补全和类型检查。 -/// tip | "提示" +/// tip | 提示 还记得请求体也是使用 Pydantic 模型声明的吧。 @@ -63,7 +63,7 @@ /// -/// check | "检查" +/// check | 检查 依赖系统的这种设计方式可以支持不同的依赖项返回同一个 `User` 模型。 diff --git a/docs/zh/docs/tutorial/security/oauth2-jwt.md b/docs/zh/docs/tutorial/security/oauth2-jwt.md index 8e497b844..4bb6e6318 100644 --- a/docs/zh/docs/tutorial/security/oauth2-jwt.md +++ b/docs/zh/docs/tutorial/security/oauth2-jwt.md @@ -40,7 +40,7 @@ $ pip install pyjwt -/// info | "说明" +/// info | 说明 如果您打算使用类似 RSA 或 ECDSA 的数字签名算法,您应该安装加密库依赖项 `pyjwt[crypto]`。 @@ -82,7 +82,7 @@ $ pip install passlib[bcrypt] -/// tip | "提示" +/// tip | 提示 `passlib` 甚至可以读取 Django、Flask 的安全插件等工具创建的密码。 @@ -98,7 +98,7 @@ $ pip install passlib[bcrypt] 创建用于密码哈希和身份校验的 PassLib **上下文**。 -/// tip | "提示" +/// tip | 提示 PassLib 上下文还支持使用不同哈希算法的功能,包括只能校验的已弃用旧算法等。 @@ -166,7 +166,7 @@ Prefer to use the `Annotated` version if possible. //// -/// note | "笔记" +/// note | 笔记 查看新的(伪)数据库 `fake_users_db`,就能看到哈希后的密码:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`。 @@ -358,7 +358,7 @@ JWT 规范还包括 `sub` 键,值是令牌的主题。 用户名: `johndoe` 密码: `secret` -/// check | "检查" +/// check | 检查 注意,代码中没有明文密码**`secret`**,只保存了它的哈希值。 @@ -383,7 +383,7 @@ JWT 规范还包括 `sub` 键,值是令牌的主题。 -/// note | "笔记" +/// note | 笔记 注意,请求中 `Authorization` 响应头的值以 `Bearer` 开头。 diff --git a/docs/zh/docs/tutorial/security/simple-oauth2.md b/docs/zh/docs/tutorial/security/simple-oauth2.md index 1f031a6b2..8ce9263db 100644 --- a/docs/zh/docs/tutorial/security/simple-oauth2.md +++ b/docs/zh/docs/tutorial/security/simple-oauth2.md @@ -32,7 +32,7 @@ OAuth2 还支持客户端发送**`scope`**表单字段。 * 脸书和 Instagram 使用 `instagram_basic` * 谷歌使用 `https://www.googleapis.com/auth/drive` -/// info | "说明" +/// info | 说明 OAuth2 中,**作用域**只是声明指定权限的字符串。 @@ -63,7 +63,7 @@ OAuth2 中,**作用域**只是声明指定权限的字符串。 * 可选的 `scope` 字段,由多个空格分隔的字符串组成的长字符串 * 可选的 `grant_type` -/// tip | "提示" +/// tip | 提示 实际上,OAuth2 规范*要求* `grant_type` 字段使用固定值 `password`,但 `OAuth2PasswordRequestForm` 没有作强制约束。 @@ -74,7 +74,7 @@ OAuth2 中,**作用域**只是声明指定权限的字符串。 * 可选的 `client_id`(本例未使用) * 可选的 `client_secret`(本例未使用) -/// info | "说明" +/// info | 说明 `OAuth2PasswordRequestForm` 与 `OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类。 @@ -88,7 +88,7 @@ OAuth2 中,**作用域**只是声明指定权限的字符串。 ### 使用表单数据 -/// tip | "提示" +/// tip | 提示 `OAuth2PasswordRequestForm` 类依赖项的实例没有以空格分隔的长字符串属性 `scope`,但它支持 `scopes` 属性,由已发送的 scope 字符串列表组成。 @@ -150,7 +150,7 @@ UserInDB( ) ``` -/// info | "说明" +/// info | 说明 `user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#user_indict){.internal-link target=_blank}。 @@ -166,7 +166,7 @@ UserInDB( 本例只是简单的演示,返回的 Token 就是 `username`,但这种方式极不安全。 -/// tip | "提示" +/// tip | 提示 下一章介绍使用哈希密码和 JWT Token 的真正安全机制。 @@ -178,7 +178,7 @@ UserInDB( {!../../docs_src/security/tutorial003.py!} ``` -/// tip | "提示" +/// tip | 提示 按规范的要求,应像本示例一样,返回带有 `access_token` 和 `token_type` 的 JSON 对象。 @@ -206,7 +206,7 @@ UserInDB( {!../../docs_src/security/tutorial003.py!} ``` -/// info | "说明" +/// info | 说明 此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。 diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md index 379c44143..06b373e6d 100644 --- a/docs/zh/docs/tutorial/sql-databases.md +++ b/docs/zh/docs/tutorial/sql-databases.md @@ -167,7 +167,7 @@ connect_args={"check_same_thread": False} ...仅用于`SQLite`,在其他数据库不需要它。 -/// info | "技术细节" +/// info | 技术细节 默认情况下,SQLite 只允许一个线程与其通信,假设有多个线程的话,也只将处理一个独立的请求。 @@ -630,7 +630,7 @@ SQLAlchemy 模型`User`包含一个`hashed_password`,它应该是一个包含 //// -/// info | "技术细节" +/// info | 技术细节 参数`db`实际上是 type `SessionLocal`,但是这个类(用 创建`sessionmaker()`)是 SQLAlchemy 的“代理” `Session`,所以,编辑器并不真正知道提供了哪些方法。 @@ -713,7 +713,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): /// -/// note | "Very Technical Details" +/// note | Very Technical Details 如果您很好奇并且拥有深厚的技术知识,您可以在[Async](https://fastapi.tiangolo.com/zh/async/#very-technical-details)文档中查看有关如何处理 `async def`于`def`差别的技术细节。 diff --git a/docs/zh/docs/tutorial/static-files.md b/docs/zh/docs/tutorial/static-files.md index 37e90ad43..7580f731b 100644 --- a/docs/zh/docs/tutorial/static-files.md +++ b/docs/zh/docs/tutorial/static-files.md @@ -11,7 +11,7 @@ {!../../docs_src/static_files/tutorial001.py!} ``` -/// note | "技术细节" +/// note | 技术细节 你也可以用 `from starlette.staticfiles import StaticFiles`。 diff --git a/docs/zh/docs/tutorial/testing.md b/docs/zh/docs/tutorial/testing.md index 173e6f8a6..bb3ef8a6a 100644 --- a/docs/zh/docs/tutorial/testing.md +++ b/docs/zh/docs/tutorial/testing.md @@ -8,7 +8,7 @@ ## 使用 `TestClient` -/// info | "信息" +/// info | 信息 要使用 `TestClient`,先要安装 `httpx`. @@ -30,7 +30,7 @@ {!../../docs_src/app_testing/tutorial001.py!} ``` -/// tip | "提示" +/// tip | 提示 注意测试函数是普通的 `def`,不是 `async def`。 @@ -40,7 +40,7 @@ /// -/// note | "技术细节" +/// note | 技术细节 你也可以用 `from starlette.testclient import TestClient`。 @@ -48,7 +48,7 @@ /// -/// tip | "提示" +/// tip | 提示 除了发送请求之外,如果你还想测试时在FastAPI应用中调用 `async` 函数(例如异步数据库函数), 可以在高级教程中看下 [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} 。 @@ -148,7 +148,7 @@ //// tab | Python 3.10+ non-Annotated -/// tip | "提示" +/// tip | 提示 Prefer to use the `Annotated` version if possible. @@ -162,7 +162,7 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.8+ non-Annotated -/// tip | "提示" +/// tip | 提示 Prefer to use the `Annotated` version if possible. @@ -196,7 +196,7 @@ Prefer to use the `Annotated` version if possible. 关于如何传数据给后端的更多信息 (使用`httpx` 或 `TestClient`),请查阅 HTTPX 文档. -/// info | "信息" +/// info | 信息 注意 `TestClient` 接收可以被转化为JSON的数据,而不是Pydantic模型。 From d9119528eaf6d83dcdc906e318169d49ce0cc71b Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 16:41:55 +0000 Subject: [PATCH 404/932] =?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 [skip ci] --- 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 fa66930fc..5c40995da 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Fix admonition double quotes with new syntax. PR [#12835](https://github.com/fastapi/fastapi/pull/12835) by [@tiangolo](https://github.com/tiangolo). * 📝 Update includes in `docs/zh/docs/advanced/additional-responses.md`. PR [#12828](https://github.com/fastapi/fastapi/pull/12828) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes in `docs/en/docs/tutorial/path-params-numeric-validations.md`. PR [#12825](https://github.com/fastapi/fastapi/pull/12825) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes for `docs/en/docs/advanced/testing-websockets.md`. PR [#12761](https://github.com/fastapi/fastapi/pull/12761) by [@hamidrasti](https://github.com/hamidrasti). From ac4956d3a32f3046142bd987d0576bc0c07d7af0 Mon Sep 17 00:00:00 2001 From: AyushSinghal1794 <89984761+AyushSinghal1794@users.noreply.github.com> Date: Sat, 9 Nov 2024 22:22:15 +0530 Subject: [PATCH 405/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/advanced/generate-clients.md`=20(#12642)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/generate-clients.md | 48 ++--------------------- 1 file changed, 3 insertions(+), 45 deletions(-) diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index 7872103c3..fe4194ac7 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -32,21 +32,7 @@ There are also several other companies offering similar services that you can se Let's start with a simple FastAPI application: -//// tab | Python 3.9+ - -```Python hl_lines="7-9 12-13 16-17 21" -{!> ../../docs_src/generate_clients/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../docs_src/generate_clients/tutorial001.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *} Notice that the *path operations* define the models they use for request payload and response payload, using the models `Item` and `ResponseMessage`. @@ -151,21 +137,7 @@ In many cases your FastAPI app will be bigger, and you will probably use tags to For example, you could have a section for **items** and another section for **users**, and they could be separated by tags: -//// tab | Python 3.9+ - -```Python hl_lines="21 26 34" -{!> ../../docs_src/generate_clients/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23 28 36" -{!> ../../docs_src/generate_clients/tutorial002.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *} ### Generate a TypeScript Client with Tags @@ -212,21 +184,7 @@ For example, here it is using the first tag (you will probably have only one tag You can then pass that custom function to **FastAPI** as the `generate_unique_id_function` parameter: -//// tab | Python 3.9+ - -```Python hl_lines="6-7 10" -{!> ../../docs_src/generate_clients/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8-9 12" -{!> ../../docs_src/generate_clients/tutorial003.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *} ### Generate a TypeScript Client with Custom Operation IDs From 5d1cb40c5eb0fbad9ef4590f5f54be094437fdd1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 16:52:39 +0000 Subject: [PATCH 406/932] =?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 [skip ci] --- 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 5c40995da..8a2a0547b 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/generate-clients.md`. PR [#12642](https://github.com/fastapi/fastapi/pull/12642) by [@AyushSinghal1794](https://github.com/AyushSinghal1794). * 📝 Fix admonition double quotes with new syntax. PR [#12835](https://github.com/fastapi/fastapi/pull/12835) by [@tiangolo](https://github.com/tiangolo). * 📝 Update includes in `docs/zh/docs/advanced/additional-responses.md`. PR [#12828](https://github.com/fastapi/fastapi/pull/12828) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes in `docs/en/docs/tutorial/path-params-numeric-validations.md`. PR [#12825](https://github.com/fastapi/fastapi/pull/12825) by [@zhaohan-dong](https://github.com/zhaohan-dong). From aaab24205faf3198101e373c0b217143eaca02a9 Mon Sep 17 00:00:00 2001 From: Zhaohan Dong <65422392+zhaohan-dong@users.noreply.github.com> Date: Sat, 9 Nov 2024 16:53:31 +0000 Subject: [PATCH 407/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/de/docs/advanced/additional-responses.md`=20(#12821)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/additional-responses.md | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/docs/de/docs/advanced/additional-responses.md b/docs/de/docs/advanced/additional-responses.md index 29a7b064a..bf38d9795 100644 --- a/docs/de/docs/advanced/additional-responses.md +++ b/docs/de/docs/advanced/additional-responses.md @@ -26,9 +26,7 @@ Jedes dieser Response-`dict`s kann einen Schlüssel `model` haben, welcher ein P Um beispielsweise eine weitere Response mit dem Statuscode `404` und einem Pydantic-Modell `Message` zu deklarieren, können Sie schreiben: -```Python hl_lines="18 22" -{!../../docs_src/additional_responses/tutorial001.py!} -``` +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} /// note | Hinweis @@ -177,9 +175,7 @@ Sie können denselben `responses`-Parameter verwenden, um verschiedene Medientyp Sie können beispielsweise einen zusätzlichen Medientyp `image/png` hinzufügen und damit deklarieren, dass Ihre *Pfadoperation* ein JSON-Objekt (mit dem Medientyp `application/json`) oder ein PNG-Bild zurückgeben kann: -```Python hl_lines="19-24 28" -{!../../docs_src/additional_responses/tutorial002.py!} -``` +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} /// note | Hinweis @@ -207,9 +203,7 @@ Sie können beispielsweise eine Response mit dem Statuscode `404` deklarieren, d Und eine Response mit dem Statuscode `200`, die Ihr `response_model` verwendet, aber ein benutzerdefiniertes Beispiel (`example`) enthält: -```Python hl_lines="20-31" -{!../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} Es wird alles kombiniert und in Ihre OpenAPI eingebunden und in der API-Dokumentation angezeigt: @@ -243,9 +237,7 @@ Mit dieser Technik können Sie einige vordefinierte Responses in Ihren *Pfadoper Zum Beispiel: -```Python hl_lines="13-17 26" -{!../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## Weitere Informationen zu OpenAPI-Responses From a81662b3c15aaa0b2bd618296dc88c965d9aaf11 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 16:56:02 +0000 Subject: [PATCH 408/932] =?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 [skip ci] --- 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 8a2a0547b..efa480f5b 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/additional-responses.md`. PR [#12821](https://github.com/fastapi/fastapi/pull/12821) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes in `docs/en/docs/advanced/generate-clients.md`. PR [#12642](https://github.com/fastapi/fastapi/pull/12642) by [@AyushSinghal1794](https://github.com/AyushSinghal1794). * 📝 Fix admonition double quotes with new syntax. PR [#12835](https://github.com/fastapi/fastapi/pull/12835) by [@tiangolo](https://github.com/tiangolo). * 📝 Update includes in `docs/zh/docs/advanced/additional-responses.md`. PR [#12828](https://github.com/fastapi/fastapi/pull/12828) by [@zhaohan-dong](https://github.com/zhaohan-dong). From 6e7e6f6c5593ce7c26441317fe427bbacf67d19a Mon Sep 17 00:00:00 2001 From: Okeke Chukwuemeka Christian Date: Sat, 9 Nov 2024 16:59:54 +0000 Subject: [PATCH 409/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/tutorial/security/first-steps.md`=20(#12643)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/security/first-steps.md | 90 +------------------ 1 file changed, 3 insertions(+), 87 deletions(-) diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index 37e37cb5b..8f6578e12 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -20,35 +20,7 @@ Let's first just use the code and see how it works, and then we'll come back to Copy the example in a file `main.py`: -//// tab | Python 3.9+ - -```Python -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py *} ## Run it @@ -160,35 +132,7 @@ In that case, **FastAPI** also provides you with the tools to build it. When we create an instance of the `OAuth2PasswordBearer` class we pass in the `tokenUrl` parameter. This parameter contains the URL that the client (the frontend running in the user's browser) will use to send the `username` and `password` in order to get a token. -//// tab | Python 3.9+ - -```Python hl_lines="8" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="6" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *} /// tip @@ -226,35 +170,7 @@ So, it can be used with `Depends`. Now you can pass that `oauth2_scheme` in a dependency with `Depends`. -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} This dependency will provide a `str` that is assigned to the parameter `token` of the *path operation function*. From f5b8f39ed77b1ee5b5b5474cab8f50a9868cb27f Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 17:01:51 +0000 Subject: [PATCH 410/932] =?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 [skip ci] --- 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 efa480f5b..2baba2d16 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/tutorial/security/first-steps.md`. PR [#12643](https://github.com/fastapi/fastapi/pull/12643) by [@OCE1960](https://github.com/OCE1960). * 📝 Update includes in `docs/de/docs/advanced/additional-responses.md`. PR [#12821](https://github.com/fastapi/fastapi/pull/12821) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes in `docs/en/docs/advanced/generate-clients.md`. PR [#12642](https://github.com/fastapi/fastapi/pull/12642) by [@AyushSinghal1794](https://github.com/AyushSinghal1794). * 📝 Fix admonition double quotes with new syntax. PR [#12835](https://github.com/fastapi/fastapi/pull/12835) by [@tiangolo](https://github.com/tiangolo). From f26a1b638536a672a83ff29d4ace8543b51032c2 Mon Sep 17 00:00:00 2001 From: Okeke Chukwuemeka Christian Date: Sat, 9 Nov 2024 17:03:01 +0000 Subject: [PATCH 411/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/tutorial/security/get-current-user.md`=20(#126?= =?UTF-8?q?45)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tutorial/security/get-current-user.md | 290 +----------------- 1 file changed, 6 insertions(+), 284 deletions(-) diff --git a/docs/en/docs/tutorial/security/get-current-user.md b/docs/en/docs/tutorial/security/get-current-user.md index 069806621..5de3a8e7d 100644 --- a/docs/en/docs/tutorial/security/get-current-user.md +++ b/docs/en/docs/tutorial/security/get-current-user.md @@ -2,35 +2,7 @@ In the previous chapter the security system (which is based on the dependency injection system) was giving the *path operation function* a `token` as a `str`: -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} But that is still not that useful. @@ -42,57 +14,7 @@ First, let's create a Pydantic user model. The same way we use Pydantic to declare bodies, we can use it anywhere else: -//// tab | Python 3.10+ - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 13-17" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="3 10-14" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *} ## Create a `get_current_user` dependency @@ -104,169 +26,19 @@ Remember that dependencies can have sub-dependencies? The same as we were doing before in the *path operation* directly, our new dependency `get_current_user` will receive a `token` as a `str` from the sub-dependency `oauth2_scheme`: -//// tab | Python 3.10+ - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="26" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="23" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *} ## Get the user `get_current_user` will use a (fake) utility function we created, that takes a token as a `str` and returns our Pydantic `User` model: -//// tab | Python 3.10+ - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20-23 27-28" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17-20 24-25" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *} ## Inject the current user So now we can use the same `Depends` with our `get_current_user` in the *path operation*: -//// tab | Python 3.10+ - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="32" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="29" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *} Notice that we declare the type of `current_user` as the Pydantic model `User`. @@ -320,57 +92,7 @@ And all of them (or any portion of them that you want) can take advantage of re- And all these thousands of *path operations* can be as small as 3 lines: -//// tab | Python 3.10+ - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31-33" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="28-30" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *} ## Recap From 5df1415feee3522e3716ec88311498757c34fa8b Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 17:04:00 +0000 Subject: [PATCH 412/932] =?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 [skip ci] --- 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 2baba2d16..0fa073bcd 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/tutorial/security/get-current-user.md`. PR [#12645](https://github.com/fastapi/fastapi/pull/12645) by [@OCE1960](https://github.com/OCE1960). * 📝 Update includes for `docs/en/docs/tutorial/security/first-steps.md`. PR [#12643](https://github.com/fastapi/fastapi/pull/12643) by [@OCE1960](https://github.com/OCE1960). * 📝 Update includes in `docs/de/docs/advanced/additional-responses.md`. PR [#12821](https://github.com/fastapi/fastapi/pull/12821) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update includes in `docs/en/docs/advanced/generate-clients.md`. PR [#12642](https://github.com/fastapi/fastapi/pull/12642) by [@AyushSinghal1794](https://github.com/AyushSinghal1794). From 40912999d1e28caf49a7eb5295b662a72dff2e4a Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sat, 9 Nov 2024 17:07:05 +0000 Subject: [PATCH 413/932] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20error=20in?= =?UTF-8?q?=20`docs/en/docs/tutorial/middleware.md`=20(#12819)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/middleware.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index 4693d977a..53c47a085 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -60,7 +60,6 @@ For example, you could add a custom header `X-Process-Time` containing the time {* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} /// tip -```Python hl_lines="10 12-13" Here we use `time.perf_counter()` instead of `time.time()` because it can be more precise for these use cases. 🤓 From 5d03558363d91e6addd65c611b80742ec681187c Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 17:07:31 +0000 Subject: [PATCH 414/932] =?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 [skip ci] --- 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 0fa073bcd..ce96154e9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏️ Fix error in `docs/en/docs/tutorial/middleware.md`. PR [#12819](https://github.com/fastapi/fastapi/pull/12819) by [@alejsdev](https://github.com/alejsdev). * 📝 Update includes for `docs/en/docs/tutorial/security/get-current-user.md`. PR [#12645](https://github.com/fastapi/fastapi/pull/12645) by [@OCE1960](https://github.com/OCE1960). * 📝 Update includes for `docs/en/docs/tutorial/security/first-steps.md`. PR [#12643](https://github.com/fastapi/fastapi/pull/12643) by [@OCE1960](https://github.com/OCE1960). * 📝 Update includes in `docs/de/docs/advanced/additional-responses.md`. PR [#12821](https://github.com/fastapi/fastapi/pull/12821) by [@zhaohan-dong](https://github.com/zhaohan-dong). From 98182d02ce01c0fe074107e55d5f82bea6d35d30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 9 Nov 2024 21:13:48 +0100 Subject: [PATCH 415/932] =?UTF-8?q?=F0=9F=94=A8=20Update=20docs=20preview?= =?UTF-8?q?=20script=20to=20show=20previous=20version=20and=20English=20ve?= =?UTF-8?q?rsion=20(#12856)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/deploy_docs_status.py | 36 ++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/scripts/deploy_docs_status.py b/scripts/deploy_docs_status.py index 19dffbcb9..c652cdb6e 100644 --- a/scripts/deploy_docs_status.py +++ b/scripts/deploy_docs_status.py @@ -2,7 +2,7 @@ import logging import re from github import Github -from pydantic import SecretStr +from pydantic import BaseModel, SecretStr from pydantic_settings import BaseSettings @@ -15,7 +15,13 @@ class Settings(BaseSettings): is_done: bool = False -def main(): +class LinkData(BaseModel): + previous_link: str + preview_link: str + en_link: str | None = None + + +def main() -> None: logging.basicConfig(level=logging.INFO) settings = Settings() @@ -60,7 +66,7 @@ def main(): docs_files = [f for f in files if f.filename.startswith("docs/")] deploy_url = settings.deploy_url.rstrip("/") - lang_links: dict[str, list[str]] = {} + lang_links: dict[str, list[LinkData]] = {} for f in docs_files: match = re.match(r"docs/([^/]+)/docs/(.*)", f.filename) if not match: @@ -71,15 +77,22 @@ def main(): path = path.replace("index.md", "") else: path = path.replace(".md", "/") + en_path = path if lang == "en": - link = f"{deploy_url}/{path}" + use_path = en_path else: - link = f"{deploy_url}/{lang}/{path}" + use_path = f"{lang}/{path}" + link = LinkData( + previous_link=f"https://fastapi.tiangolo.com/{use_path}", + preview_link=f"{deploy_url}/{use_path}", + ) + if lang != "en": + link.en_link = f"https://fastapi.tiangolo.com/{en_path}" lang_links.setdefault(lang, []).append(link) - links: list[str] = [] + links: list[LinkData] = [] en_links = lang_links.get("en", []) - en_links.sort() + en_links.sort(key=lambda x: x.preview_link) links.extend(en_links) langs = list(lang_links.keys()) @@ -88,14 +101,19 @@ def main(): if lang == "en": continue current_lang_links = lang_links[lang] - current_lang_links.sort() + current_lang_links.sort(key=lambda x: x.preview_link) links.extend(current_lang_links) message = f"📝 Docs preview for commit {settings.commit_sha} at: {deploy_url}" if links: message += "\n\n### Modified Pages\n\n" - message += "\n".join([f"* {link}" for link in links]) + for link in links: + message += f"* {link.preview_link}" + message += f" - ([before]({link.previous_link}))" + if link.en_link: + message += f" - ([English]({link.en_link}))" + message += "\n" print(message) use_pr.as_issue().create_comment(message) From df6d1de3e6d5266d73a6eb9d7b2f12262927a6e1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 9 Nov 2024 20:14:12 +0000 Subject: [PATCH 416/932] =?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 [skip ci] --- 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 ce96154e9..50518f8e4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -106,6 +106,7 @@ hide: ### Internal +* 🔨 Update docs preview script to show previous version and English version. PR [#12856](https://github.com/fastapi/fastapi/pull/12856) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump tiangolo/latest-changes from 0.3.1 to 0.3.2. PR [#12794](https://github.com/fastapi/fastapi/pull/12794) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pypa/gh-action-pypi-publish from 1.12.0 to 1.12.2. PR [#12788](https://github.com/fastapi/fastapi/pull/12788) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pypa/gh-action-pypi-publish from 1.11.0 to 1.12.0. PR [#12781](https://github.com/fastapi/fastapi/pull/12781) by [@dependabot[bot]](https://github.com/apps/dependabot). From a01f9f298e2480b5c0d82e6f055dcf8cc9ece80d Mon Sep 17 00:00:00 2001 From: Baldeep Singh Handa Date: Sun, 10 Nov 2024 01:11:07 +0000 Subject: [PATCH 417/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/tutorial/dependencies/classes-as-dependencies.?= =?UTF-8?q?md`=20(#12813)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependencies/classes-as-dependencies.md | 364 +----------------- 1 file changed, 7 insertions(+), 357 deletions(-) diff --git a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md index defd61a0d..9c7bb1fd3 100644 --- a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,57 +6,7 @@ Before diving deeper into the **Dependency Injection** system, let's upgrade the In the previous example, we were returning a `dict` from our dependency ("dependable"): -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="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="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="11" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *} But then we get a `dict` in the parameter `commons` of the *path operation function*. @@ -119,165 +69,15 @@ That also applies to callables with no parameters at all. The same as it would b Then, we can change the dependency "dependable" `common_parameters` from above to the class `CommonQueryParams`: -//// tab | Python 3.10+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12-16" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9-13" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *} Pay attention to the `__init__` method used to create the instance of the class: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *} ...it has the same parameters as our previous `common_parameters`: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../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" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *} Those parameters are what **FastAPI** will use to "solve" the dependency. @@ -293,57 +93,7 @@ In both cases the data will be converted, validated, documented on the OpenAPI s Now you can declare your dependency using this class. -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *} **FastAPI** calls the `CommonQueryParams` class. This creates an "instance" of that class and the instance will be passed as the parameter `commons` to your function. @@ -437,57 +187,7 @@ commons = Depends(CommonQueryParams) ...as in: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *} But declaring the type is encouraged as that way your editor will know what will be passed as the parameter `commons`, and then it can help you with code completion, type checks, etc: @@ -575,57 +275,7 @@ You declare the dependency as the type of the parameter, and you use `Depends()` The same example would then look like: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *} ...and **FastAPI** will know what to do. From 370f4f9980afe419c74243f58a4c52221255acb2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 10 Nov 2024 01:25:37 +0000 Subject: [PATCH 418/932] =?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 [skip ci] --- 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 50518f8e4..a003755a1 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/tutorial/dependencies/classes-as-dependencies.md`. PR [#12813](https://github.com/fastapi/fastapi/pull/12813) by [@handabaldeep](https://github.com/handabaldeep). * ✏️ Fix error in `docs/en/docs/tutorial/middleware.md`. PR [#12819](https://github.com/fastapi/fastapi/pull/12819) by [@alejsdev](https://github.com/alejsdev). * 📝 Update includes for `docs/en/docs/tutorial/security/get-current-user.md`. PR [#12645](https://github.com/fastapi/fastapi/pull/12645) by [@OCE1960](https://github.com/OCE1960). * 📝 Update includes for `docs/en/docs/tutorial/security/first-steps.md`. PR [#12643](https://github.com/fastapi/fastapi/pull/12643) by [@OCE1960](https://github.com/OCE1960). From b2236d080a76f15c2712fac5115bcc7654aaef6a Mon Sep 17 00:00:00 2001 From: Baldeep Singh Handa Date: Sun, 10 Nov 2024 16:45:28 +0000 Subject: [PATCH 419/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/tutorial/dependencies/dependencies-in-path-ope?= =?UTF-8?q?ration-decorators.md`=20(#12815)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- ...pendencies-in-path-operation-decorators.md | 120 +----------------- 1 file changed, 4 insertions(+), 116 deletions(-) diff --git a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index e89d520be..88ad99403 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,35 +14,7 @@ The *path operation decorator* receives an optional argument `dependencies`. It should be a `list` of `Depends()`: -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *} These dependencies will be executed/solved the same way as normal dependencies. But their value (if they return any) won't be passed to your *path operation function*. @@ -72,69 +44,13 @@ You can use the same dependency *functions* you use normally. They can declare request requirements (like headers) or other sub-dependencies: -//// tab | Python 3.9+ - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7 12" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="6 11" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *} ### Raise exceptions These dependencies can `raise` exceptions, the same as normal dependencies: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *} ### Return values @@ -142,35 +58,7 @@ And they can return values or not, the values won't be used. So, you can reuse a normal dependency (that returns a value) you already use somewhere else, and even though the value won't be used, the dependency will be executed: -//// tab | Python 3.9+ - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *} ## Dependencies for a group of *path operations* From 2d524cca145f2535637bd4ed9ec3306fa1dee524 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 10 Nov 2024 16:45:50 +0000 Subject: [PATCH 420/932] =?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 [skip ci] --- 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 a003755a1..1cabce6f9 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/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#12815](https://github.com/fastapi/fastapi/pull/12815) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes for `docs/en/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#12813](https://github.com/fastapi/fastapi/pull/12813) by [@handabaldeep](https://github.com/handabaldeep). * ✏️ Fix error in `docs/en/docs/tutorial/middleware.md`. PR [#12819](https://github.com/fastapi/fastapi/pull/12819) by [@alejsdev](https://github.com/alejsdev). * 📝 Update includes for `docs/en/docs/tutorial/security/get-current-user.md`. PR [#12645](https://github.com/fastapi/fastapi/pull/12645) by [@OCE1960](https://github.com/OCE1960). From be6760572850245129abf128682be50fce93d4fe Mon Sep 17 00:00:00 2001 From: Nimitha J <58389915+Nimitha-jagadeesha@users.noreply.github.com> Date: Sun, 10 Nov 2024 22:26:13 +0530 Subject: [PATCH 421/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/pt/docs/advanced/wsgi.md`=20(#12769)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/pt/docs/advanced/wsgi.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/pt/docs/advanced/wsgi.md b/docs/pt/docs/advanced/wsgi.md index e6d08c8db..a36261e5e 100644 --- a/docs/pt/docs/advanced/wsgi.md +++ b/docs/pt/docs/advanced/wsgi.md @@ -12,9 +12,7 @@ Em seguinda, encapsular a aplicação WSGI (e.g. Flask) com o middleware. E então **"montar"** em um caminho de rota. -```Python hl_lines="2-3 23" -{!../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,23] *} ## Conferindo From 37a557a0a30744b91c7f4f23427321721a6ff4f3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 10 Nov 2024 16:56:41 +0000 Subject: [PATCH 422/932] =?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 [skip ci] --- 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 1cabce6f9..974fbdbd0 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/pt/docs/advanced/wsgi.md`. PR [#12769](https://github.com/fastapi/fastapi/pull/12769) by [@Nimitha-jagadeesha](https://github.com/Nimitha-jagadeesha). * 📝 Update includes for `docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#12815](https://github.com/fastapi/fastapi/pull/12815) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes for `docs/en/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#12813](https://github.com/fastapi/fastapi/pull/12813) by [@handabaldeep](https://github.com/handabaldeep). * ✏️ Fix error in `docs/en/docs/tutorial/middleware.md`. PR [#12819](https://github.com/fastapi/fastapi/pull/12819) by [@alejsdev](https://github.com/alejsdev). From ba734c23125b6afc251938e58777824feeda411d Mon Sep 17 00:00:00 2001 From: Max Patalas <40061559+MxPy@users.noreply.github.com> Date: Sun, 10 Nov 2024 17:58:43 +0100 Subject: [PATCH 423/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/vi/docs/tutorial/first-steps.md`=20(#12754)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/vi/docs/tutorial/first-steps.md | 32 +++++++--------------------- 1 file changed, 8 insertions(+), 24 deletions(-) diff --git a/docs/vi/docs/tutorial/first-steps.md b/docs/vi/docs/tutorial/first-steps.md index 934527b8e..901c8fd59 100644 --- a/docs/vi/docs/tutorial/first-steps.md +++ b/docs/vi/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Tệp tin FastAPI đơn giản nhất có thể trông như này: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Sao chép sang một tệp tin `main.py`. @@ -133,9 +131,7 @@ Bạn cũng có thể sử dụng nó để sinh code tự động, với các c ### Bước 1: import `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` là một Python class cung cấp tất cả chức năng cho API của bạn. @@ -149,9 +145,7 @@ Bạn cũng có thể sử dụng tất cả Date: Sun, 10 Nov 2024 16:59:09 +0000 Subject: [PATCH 424/932] =?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 [skip ci] --- 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 974fbdbd0..e52da6ae8 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/vi/docs/tutorial/first-steps.md`. PR [#12754](https://github.com/fastapi/fastapi/pull/12754) by [@MxPy](https://github.com/MxPy). * 📝 Update includes for `docs/pt/docs/advanced/wsgi.md`. PR [#12769](https://github.com/fastapi/fastapi/pull/12769) by [@Nimitha-jagadeesha](https://github.com/Nimitha-jagadeesha). * 📝 Update includes for `docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#12815](https://github.com/fastapi/fastapi/pull/12815) by [@handabaldeep](https://github.com/handabaldeep). * 📝 Update includes for `docs/en/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#12813](https://github.com/fastapi/fastapi/pull/12813) by [@handabaldeep](https://github.com/handabaldeep). From 1fc9a9ad3ac516e75332cd8ca817303379b4679a Mon Sep 17 00:00:00 2001 From: Okeke Chukwuemeka Christian Date: Sun, 10 Nov 2024 17:02:51 +0000 Subject: [PATCH 425/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/tutorial/security/oauth2-jwt.md`=20(#12650)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/tutorial/security/oauth2-jwt.md | 208 +------------------ 1 file changed, 4 insertions(+), 204 deletions(-) diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index 6ae1507dc..8644db45c 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -116,57 +116,7 @@ And another utility to verify if a received password matches the hash stored. And another one to authenticate and return a user. -//// tab | Python 3.10+ - -```Python hl_lines="8 49 56-57 60-61 70-76" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8 49 56-57 60-61 70-76" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 50 57-58 61-62 71-77" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8 49 56-57 60-61 70-76" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *} /// note @@ -202,57 +152,7 @@ Define a Pydantic Model that will be used in the token endpoint for the response Create a utility function to generate a new access token. -//// tab | Python 3.10+ - -```Python hl_lines="4 7 13-15 29-31 79-87" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 7 13-15 29-31 79-87" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 7 14-16 30-32 80-88" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="3 6 12-14 28-30 78-86" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="4 7 13-15 29-31 79-87" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *} ## Update the dependencies @@ -262,57 +162,7 @@ Decode the received token, verify it, and return the current user. If the token is invalid, return an HTTP error right away. -//// tab | Python 3.10+ - -```Python hl_lines="90-107" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="90-107" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="91-108" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="89-106" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="90-107" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[90:107] *} ## Update the `/token` *path operation* @@ -320,57 +170,7 @@ Create a `timedelta` with the expiration time of the token. Create a real JWT access token and return it. -//// tab | Python 3.10+ - -```Python hl_lines="118-133" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="118-133" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="119-134" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="115-130" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="116-131" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *} ### Technical details about the JWT "subject" `sub` From 1d9d189b852b92c394f7ea0617fd929b0e09f971 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 10 Nov 2024 17:03:36 +0000 Subject: [PATCH 426/932] =?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 [skip ci] --- 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 e52da6ae8..07ad0d097 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/security/oauth2-jwt.md`. PR [#12650](https://github.com/fastapi/fastapi/pull/12650) by [@OCE1960](https://github.com/OCE1960). * 📝 Update includes in `docs/vi/docs/tutorial/first-steps.md`. PR [#12754](https://github.com/fastapi/fastapi/pull/12754) by [@MxPy](https://github.com/MxPy). * 📝 Update includes for `docs/pt/docs/advanced/wsgi.md`. PR [#12769](https://github.com/fastapi/fastapi/pull/12769) by [@Nimitha-jagadeesha](https://github.com/Nimitha-jagadeesha). * 📝 Update includes for `docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#12815](https://github.com/fastapi/fastapi/pull/12815) by [@handabaldeep](https://github.com/handabaldeep). From 821b32f8b328b6746cd0c69477aedf7186b657e1 Mon Sep 17 00:00:00 2001 From: VISHNU V S <84698110+vishnuvskvkl@users.noreply.github.com> Date: Sun, 10 Nov 2024 22:39:09 +0530 Subject: [PATCH 427/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/tutorial/request-form-models.md`=20(#12649)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/tutorial/request-form-models.md | 60 +------------------- 1 file changed, 2 insertions(+), 58 deletions(-) diff --git a/docs/en/docs/tutorial/request-form-models.md b/docs/en/docs/tutorial/request-form-models.md index f1142877a..79046a3f6 100644 --- a/docs/en/docs/tutorial/request-form-models.md +++ b/docs/en/docs/tutorial/request-form-models.md @@ -24,35 +24,7 @@ This is supported since FastAPI version `0.113.0`. 🤓 You just need to declare a **Pydantic model** with the fields you want to receive as **form fields**, and then declare the parameter as `Form`: -//// tab | Python 3.9+ - -```Python hl_lines="9-11 15" -{!> ../../docs_src/request_form_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8-10 14" -{!> ../../docs_src/request_form_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7-9 13" -{!> ../../docs_src/request_form_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *} **FastAPI** will **extract** the data for **each field** from the **form data** in the request and give you the Pydantic model you defined. @@ -76,35 +48,7 @@ This is supported since FastAPI version `0.114.0`. 🤓 You can use Pydantic's model configuration to `forbid` any `extra` fields: -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/request_form_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/request_form_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/request_form_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *} If a client tries to send some extra data, they will receive an **error** response. From 9e441510bab3436927cff331cd2b2a35ba00d15f Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 10 Nov 2024 17:09:31 +0000 Subject: [PATCH 428/932] =?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 [skip ci] --- 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 07ad0d097..fc562bf57 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/request-form-models.md`. PR [#12649](https://github.com/fastapi/fastapi/pull/12649) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes in `docs/en/docs/tutorial/security/oauth2-jwt.md`. PR [#12650](https://github.com/fastapi/fastapi/pull/12650) by [@OCE1960](https://github.com/OCE1960). * 📝 Update includes in `docs/vi/docs/tutorial/first-steps.md`. PR [#12754](https://github.com/fastapi/fastapi/pull/12754) by [@MxPy](https://github.com/MxPy). * 📝 Update includes for `docs/pt/docs/advanced/wsgi.md`. PR [#12769](https://github.com/fastapi/fastapi/pull/12769) by [@Nimitha-jagadeesha](https://github.com/Nimitha-jagadeesha). From 9fa2474be03e4b90565ff50087776ef03734dbf0 Mon Sep 17 00:00:00 2001 From: VISHNU V S <84698110+vishnuvskvkl@users.noreply.github.com> Date: Sun, 10 Nov 2024 22:40:49 +0530 Subject: [PATCH 429/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/tutorial/request-forms.md`=20(#12648)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/tutorial/request-forms.md | 60 +------------------------- 1 file changed, 2 insertions(+), 58 deletions(-) diff --git a/docs/en/docs/tutorial/request-forms.md b/docs/en/docs/tutorial/request-forms.md index c65e9874c..3c6a0ddaa 100644 --- a/docs/en/docs/tutorial/request-forms.md +++ b/docs/en/docs/tutorial/request-forms.md @@ -18,69 +18,13 @@ $ pip install python-multipart Import `Form` from `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} ## Define `Form` parameters Create form parameters the same way you would for `Body` or `Query`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} For example, in one of the ways the OAuth2 specification can be used (called "password flow") it is required to send a `username` and `password` as form fields. From 290e1060caac80409b3ee9595517789daf1ecaea Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 10 Nov 2024 17:11:35 +0000 Subject: [PATCH 430/932] =?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 [skip ci] --- 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 fc562bf57..8224856e2 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/request-forms.md`. PR [#12648](https://github.com/fastapi/fastapi/pull/12648) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes in `docs/en/docs/tutorial/request-form-models.md`. PR [#12649](https://github.com/fastapi/fastapi/pull/12649) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes in `docs/en/docs/tutorial/security/oauth2-jwt.md`. PR [#12650](https://github.com/fastapi/fastapi/pull/12650) by [@OCE1960](https://github.com/OCE1960). * 📝 Update includes in `docs/vi/docs/tutorial/first-steps.md`. PR [#12754](https://github.com/fastapi/fastapi/pull/12754) by [@MxPy](https://github.com/MxPy). From 8767a31c8012aebc2410135a04c60acb036b50b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 10 Nov 2024 18:11:56 +0100 Subject: [PATCH 431/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20`contributing.m?= =?UTF-8?q?d`=20docs,=20include=20note=20to=20not=20translate=20this=20pag?= =?UTF-8?q?e=20(#12841)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/contributing.md | 484 ------------------------------- docs/em/docs/contributing.md | 493 -------------------------------- docs/en/docs/contributing.md | 3 +- docs/fr/docs/contributing.md | 533 ----------------------------------- docs/ja/docs/contributing.md | 498 -------------------------------- docs/pt/docs/contributing.md | 507 --------------------------------- docs/ru/docs/contributing.md | 496 -------------------------------- docs/zh/docs/contributing.md | 472 ------------------------------- scripts/docs.py | 1 + 9 files changed, 3 insertions(+), 3484 deletions(-) delete mode 100644 docs/de/docs/contributing.md delete mode 100644 docs/em/docs/contributing.md delete mode 100644 docs/fr/docs/contributing.md delete mode 100644 docs/ja/docs/contributing.md delete mode 100644 docs/pt/docs/contributing.md delete mode 100644 docs/ru/docs/contributing.md delete mode 100644 docs/zh/docs/contributing.md diff --git a/docs/de/docs/contributing.md b/docs/de/docs/contributing.md deleted file mode 100644 index 9dfa1e65a..000000000 --- a/docs/de/docs/contributing.md +++ /dev/null @@ -1,484 +0,0 @@ -# Entwicklung – Mitwirken - -Vielleicht möchten Sie sich zuerst die grundlegenden Möglichkeiten anschauen, [FastAPI zu helfen und Hilfe zu erhalten](help-fastapi.md){.internal-link target=_blank}. - -## Entwicklung - -Wenn Sie das fastapi Repository bereits geklont haben und tief in den Code eintauchen möchten, hier einen Leitfaden zum Einrichten Ihrer Umgebung. - -### Virtuelle Umgebung mit `venv` - -Sie können mit dem Python-Modul `venv` in einem Verzeichnis eine isolierte virtuelle lokale Umgebung erstellen. Machen wir das im geklonten Repository (da wo sich die `requirements.txt` befindet): - -
- -```console -$ python -m venv env -``` - -
- -Das erstellt ein Verzeichnis `./env/` mit den Python-Binärdateien und Sie können dann Packages in dieser lokalen Umgebung installieren. - -### Umgebung aktivieren - -Aktivieren Sie die neue Umgebung mit: - -//// tab | Linux, macOS - -
- -```console -$ source ./env/bin/activate -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ .\env\Scripts\Activate.ps1 -``` - -
- -//// - -//// tab | Windows Bash - -Oder, wenn Sie Bash für Windows verwenden (z. B. Git Bash): - -
- -```console -$ source ./env/Scripts/activate -``` - -
- -//// - -Um zu überprüfen, ob es funktioniert hat, geben Sie ein: - -//// tab | Linux, macOS, Windows Bash - -
- -```console -$ which pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ Get-Command pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -Wenn die `pip` Binärdatei unter `env/bin/pip` angezeigt wird, hat es funktioniert. 🎉 - -Stellen Sie sicher, dass Sie über die neueste Version von pip in Ihrer lokalen Umgebung verfügen, um Fehler bei den nächsten Schritten zu vermeiden: - -
- -```console -$ python -m pip install --upgrade pip - ----> 100% -``` - -
- -/// tip | Tipp - -Aktivieren Sie jedes Mal, wenn Sie ein neues Package mit `pip` in dieser Umgebung installieren, die Umgebung erneut. - -Dadurch wird sichergestellt, dass Sie, wenn Sie ein von diesem Package installiertes Terminalprogramm verwenden, das Programm aus Ihrer lokalen Umgebung verwenden und kein anderes, das global installiert sein könnte. - -/// - -### Benötigtes mit pip installieren - -Nachdem Sie die Umgebung wie oben beschrieben aktiviert haben: - -
- -```console -$ pip install -r requirements.txt - ----> 100% -``` - -
- -Das installiert alle Abhängigkeiten und Ihr lokales FastAPI in Ihrer lokalen Umgebung. - -#### Das lokale FastAPI verwenden - -Wenn Sie eine Python-Datei erstellen, die FastAPI importiert und verwendet, und diese mit dem Python aus Ihrer lokalen Umgebung ausführen, wird Ihr geklonter lokaler FastAPI-Quellcode verwendet. - -Und wenn Sie diesen lokalen FastAPI-Quellcode aktualisieren und dann die Python-Datei erneut ausführen, wird die neue Version von FastAPI verwendet, die Sie gerade bearbeitet haben. - -Auf diese Weise müssen Sie Ihre lokale Version nicht „installieren“, um jede Änderung testen zu können. - -/// note | Technische Details - -Das geschieht nur, wenn Sie die Installation mit der enthaltenen `requirements.txt` durchführen, anstatt `pip install fastapi` direkt auszuführen. - -Das liegt daran, dass in der Datei `requirements.txt` die lokale Version von FastAPI mit der Option `-e` für die Installation im „editierbaren“ Modus markiert ist. - -/// - -### Den Code formatieren - -Es gibt ein Skript, das, wenn Sie es ausführen, Ihren gesamten Code formatiert und bereinigt: - -
- -```console -$ bash scripts/format.sh -``` - -
- -Es sortiert auch alle Ihre Importe automatisch. - -Damit es sie richtig sortiert, muss FastAPI lokal in Ihrer Umgebung installiert sein, mit dem Befehl vom obigen Abschnitt, welcher `-e` verwendet. - -## Dokumentation - -Stellen Sie zunächst sicher, dass Sie Ihre Umgebung wie oben beschrieben einrichten, was alles Benötigte installiert. - -### Dokumentation live - -Während der lokalen Entwicklung gibt es ein Skript, das die Site erstellt, auf Änderungen prüft und direkt neu lädt (Live Reload): - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Das stellt die Dokumentation unter `http://127.0.0.1:8008` bereit. - -Auf diese Weise können Sie die Dokumentation/Quelldateien bearbeiten und die Änderungen live sehen. - -/// tip | Tipp - -Alternativ können Sie die Schritte des Skripts auch manuell ausführen. - -Gehen Sie in das Verzeichnis für die entsprechende Sprache. Das für die englischsprachige Hauptdokumentation befindet sich unter `docs/en/`: - -```console -$ cd docs/en/ -``` - -Führen Sie dann `mkdocs` in diesem Verzeichnis aus: - -```console -$ mkdocs serve --dev-addr 8008 -``` - -/// - -#### Typer-CLI (optional) - -Die Anleitung hier zeigt Ihnen, wie Sie das Skript unter `./scripts/docs.py` direkt mit dem `python` Programm verwenden. - -Sie können aber auch Typer CLI verwenden und erhalten dann Autovervollständigung für Kommandos in Ihrem Terminal, nach dem Sie dessen Vervollständigung installiert haben. - -Wenn Sie Typer CLI installieren, können Sie die Vervollständigung installieren mit: - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### Dokumentationsstruktur - -Die Dokumentation verwendet MkDocs. - -Und es gibt zusätzliche Tools/Skripte für Übersetzungen, in `./scripts/docs.py`. - -/// tip | Tipp - -Sie müssen sich den Code in `./scripts/docs.py` nicht anschauen, verwenden Sie ihn einfach in der Kommandozeile. - -/// - -Die gesamte Dokumentation befindet sich im Markdown-Format im Verzeichnis `./docs/en/`. - -Viele der Tutorials enthalten Codeblöcke. - -In den meisten Fällen handelt es sich bei diesen Codeblöcken um vollständige Anwendungen, die unverändert ausgeführt werden können. - -Tatsächlich sind diese Codeblöcke nicht Teil des Markdowns, sondern Python-Dateien im Verzeichnis `./docs_src/`. - -Und diese Python-Dateien werden beim Generieren der Site in die Dokumentation eingefügt. - -### Dokumentation für Tests - -Tatsächlich arbeiten die meisten Tests mit den Beispielquelldateien in der Dokumentation. - -Dadurch wird sichergestellt, dass: - -* Die Dokumentation aktuell ist. -* Die Dokumentationsbeispiele ohne Änderung ausgeführt werden können. -* Die meisten Funktionalitäten durch die Dokumentation abgedeckt werden, sichergestellt durch die Testabdeckung. - -#### Gleichzeitig Apps und Dokumentation - -Wenn Sie die Beispiele ausführen, mit z. B.: - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -wird das, da Uvicorn standardmäßig den Port `8000` verwendet, mit der Dokumentation auf dem Port `8008` nicht in Konflikt geraten. - -### Übersetzungen - -Hilfe bei Übersetzungen wird SEHR geschätzt! Und es kann nicht getan werden, ohne die Hilfe der Gemeinschaft. 🌎 🚀 - -Hier sind die Schritte, die Ihnen bei Übersetzungen helfen. - -#### Tipps und Richtlinien - -* Schauen Sie nach aktuellen Pull Requests für Ihre Sprache. Sie können die Pull Requests nach dem Label für Ihre Sprache filtern. Für Spanisch lautet das Label beispielsweise `lang-es`. - -* Sehen Sie diese Pull Requests durch (Review), schlagen Sie Änderungen vor, oder segnen Sie sie ab (Approval). Bei den Sprachen, die ich nicht spreche, warte ich, bis mehrere andere die Übersetzung durchgesehen haben, bevor ich den Pull Request merge. - -/// tip | Tipp - -Sie können Kommentare mit Änderungsvorschlägen zu vorhandenen Pull Requests hinzufügen. - -Schauen Sie sich die Dokumentation an, wie man ein Review zu einem Pull Request hinzufügt, welches den PR absegnet oder Änderungen vorschlägt. - -/// - -* Überprüfen Sie, ob es eine GitHub-Diskussion gibt, die Übersetzungen für Ihre Sprache koordiniert. Sie können sie abonnieren, und wenn ein neuer Pull Request zum Review vorliegt, wird der Diskussion automatisch ein Kommentar hinzugefügt. - -* Wenn Sie Seiten übersetzen, fügen Sie einen einzelnen Pull Request pro übersetzter Seite hinzu. Dadurch wird es für andere viel einfacher, ihn zu durchzusehen. - -* Um den Zwei-Buchstaben-Code für die Sprache zu finden, die Sie übersetzen möchten, schauen Sie sich die Tabelle List of ISO 639-1 codes an. - -#### Vorhandene Sprache - -Angenommen, Sie möchten eine Seite für eine Sprache übersetzen, die bereits Übersetzungen für einige Seiten hat, beispielsweise für Spanisch. - -Im Spanischen lautet der Zwei-Buchstaben-Code `es`. Das Verzeichnis für spanische Übersetzungen befindet sich also unter `docs/es/`. - -/// tip | Tipp - -Die Haupt („offizielle“) Sprache ist Englisch und befindet sich unter `docs/en/`. - -/// - -Führen Sie nun den Live-Server für die Dokumentation auf Spanisch aus: - -
- -```console -// Verwenden Sie das Kommando „live“ und fügen Sie den Sprach-Code als Argument hinten an -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -/// tip | Tipp - -Alternativ können Sie die Schritte des Skripts auch manuell ausführen. - -Gehen Sie in das Sprachverzeichnis, für die spanischen Übersetzungen ist das `docs/es/`: - -```console -$ cd docs/es/ -``` - -Dann führen Sie in dem Verzeichnis `mkdocs` aus: - -```console -$ mkdocs serve --dev-addr 8008 -``` - -/// - -Jetzt können Sie auf http://127.0.0.1:8008 gehen und Ihre Änderungen live sehen. - -Sie werden sehen, dass jede Sprache alle Seiten hat. Einige Seiten sind jedoch nicht übersetzt und haben oben eine Info-Box, dass die Übersetzung noch fehlt. - -Nehmen wir nun an, Sie möchten eine Übersetzung für den Abschnitt [Features](features.md){.internal-link target=_blank} hinzufügen. - -* Kopieren Sie die Datei: - -``` -docs/en/docs/features.md -``` - -* Fügen Sie sie an genau derselben Stelle ein, jedoch für die Sprache, die Sie übersetzen möchten, z. B.: - -``` -docs/es/docs/features.md -``` - -/// tip | Tipp - -Beachten Sie, dass die einzige Änderung in Pfad und Dateiname der Sprachcode ist, von `en` zu `es`. - -/// - -Wenn Sie in Ihrem Browser nachsehen, werden Sie feststellen, dass die Dokumentation jetzt Ihren neuen Abschnitt anzeigt (die Info-Box oben ist verschwunden). 🎉 - -Jetzt können Sie alles übersetzen und beim Speichern sehen, wie es aussieht. - -#### Neue Sprache - -Nehmen wir an, Sie möchten Übersetzungen für eine Sprache hinzufügen, die noch nicht übersetzt ist, nicht einmal einige Seiten. - -Angenommen, Sie möchten Übersetzungen für Kreolisch hinzufügen, diese sind jedoch noch nicht in den Dokumenten enthalten. - -Wenn Sie den Link von oben überprüfen, lautet der Sprachcode für Kreolisch `ht`. - -Der nächste Schritt besteht darin, das Skript auszuführen, um ein neues Übersetzungsverzeichnis zu erstellen: - -
- -```console -// Verwenden Sie das Kommando new-lang und fügen Sie den Sprach-Code als Argument hinten an -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -``` - -
- -Jetzt können Sie in Ihrem Code-Editor das neu erstellte Verzeichnis `docs/ht/` sehen. - -Obiges Kommando hat eine Datei `docs/ht/mkdocs.yml` mit einer Minimal-Konfiguration erstellt, die alles von der `en`-Version erbt: - -```yaml -INHERIT: ../en/mkdocs.yml -``` - -/// tip | Tipp - -Sie können diese Datei mit diesem Inhalt auch einfach manuell erstellen. - -/// - -Das Kommando hat auch eine Dummy-Datei `docs/ht/index.md` für die Hauptseite erstellt. Sie können mit der Übersetzung dieser Datei beginnen. - -Sie können nun mit den obigen Instruktionen für eine „vorhandene Sprache“ fortfahren. - -Fügen Sie dem ersten Pull Request beide Dateien `docs/ht/mkdocs.yml` und `docs/ht/index.md` bei. 🎉 - -#### Vorschau des Ergebnisses - -Wie bereits oben erwähnt, können Sie `./scripts/docs.py` mit dem Befehl `live` verwenden, um eine Vorschau der Ergebnisse anzuzeigen (oder `mkdocs serve`). - -Sobald Sie fertig sind, können Sie auch alles so testen, wie es online aussehen würde, einschließlich aller anderen Sprachen. - -Bauen Sie dazu zunächst die gesamte Dokumentation: - -
- -```console -// Verwenden Sie das Kommando „build-all“, das wird ein wenig dauern -$ python ./scripts/docs.py build-all - -Building docs for: en -Building docs for: es -Successfully built docs for: es -``` - -
- -Dadurch werden alle diese unabhängigen MkDocs-Sites für jede Sprache erstellt, kombiniert und das endgültige Resultat unter `./site/` gespeichert. - -Dieses können Sie dann mit dem Befehl `serve` bereitstellen: - -
- -```console -// Verwenden Sie das Kommando „serve“ nachdem Sie „build-all“ ausgeführt haben. -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -#### Übersetzungsspezifische Tipps und Richtlinien - -* Übersetzen Sie nur die Markdown-Dokumente (`.md`). Übersetzen Sie nicht die Codebeispiele unter `./docs_src`. - -* In Codeblöcken innerhalb des Markdown-Dokuments, übersetzen Sie Kommentare (`# ein Kommentar`), aber lassen Sie den Rest unverändert. - -* Ändern Sie nichts, was in "``" (Inline-Code) eingeschlossen ist. - -* In Zeilen, die mit `===` oder `!!!` beginnen, übersetzen Sie nur den ` "... Text ..."`-Teil. Lassen Sie den Rest unverändert. - -* Sie können Info-Boxen wie `!!! warning` mit beispielsweise `!!! warning "Achtung"` übersetzen. Aber ändern Sie nicht das Wort direkt nach dem `!!!`, es bestimmt die Farbe der Info-Box. - -* Ändern Sie nicht die Pfade in Links zu Bildern, Codedateien, Markdown Dokumenten. - -* Wenn ein Markdown-Dokument übersetzt ist, ändern sich allerdings unter Umständen die `#hash-teile` in Links zu dessen Überschriften. Aktualisieren Sie diese Links, wenn möglich. - * Suchen Sie im übersetzten Dokument nach solchen Links mit dem Regex `#[^# ]`. - * Suchen Sie in allen bereits in ihre Sprache übersetzen Dokumenten nach `ihr-ubersetztes-dokument.md`. VS Code hat beispielsweise eine Option „Bearbeiten“ -> „In Dateien suchen“. - * Übersetzen Sie bei der Übersetzung eines Dokuments nicht „im Voraus“ `#hash-teile`, die zu Überschriften in noch nicht übersetzten Dokumenten verlinken. - -## Tests - -Es gibt ein Skript, das Sie lokal ausführen können, um den gesamten Code zu testen und Code Coverage Reporte in HTML zu generieren: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -Dieses Kommando generiert ein Verzeichnis `./htmlcov/`. Wenn Sie die Datei `./htmlcov/index.html` in Ihrem Browser öffnen, können Sie interaktiv die Codebereiche erkunden, die von den Tests abgedeckt werden, und feststellen, ob Bereiche fehlen. diff --git a/docs/em/docs/contributing.md b/docs/em/docs/contributing.md deleted file mode 100644 index 3ac1afda4..000000000 --- a/docs/em/docs/contributing.md +++ /dev/null @@ -1,493 +0,0 @@ -# 🛠️ - 📉 - -🥇, 👆 💪 💚 👀 🔰 🌌 [ℹ FastAPI & 🤚 ℹ](help-fastapi.md){.internal-link target=_blank}. - -## 🛠️ - -🚥 👆 ⏪ 🖖 🗃 & 👆 💭 👈 👆 💪 ⏬ 🤿 📟, 📥 📄 ⚒ 🆙 👆 🌐. - -### 🕹 🌐 ⏮️ `venv` - -👆 💪 ✍ 🕹 🌐 📁 ⚙️ 🐍 `venv` 🕹: - -
- -```console -$ python -m venv env -``` - -
- -👈 🔜 ✍ 📁 `./env/` ⏮️ 🐍 💱 & ⤴️ 👆 🔜 💪 ❎ 📦 👈 ❎ 🌐. - -### 🔓 🌐 - -🔓 🆕 🌐 ⏮️: - -//// tab | 💾, 🇸🇻 - -
- -```console -$ source ./env/bin/activate -``` - -
- -//// - -//// tab | 🚪 📋 - -
- -```console -$ .\env\Scripts\Activate.ps1 -``` - -
- -//// - -//// tab | 🚪 🎉 - -⚖️ 🚥 👆 ⚙️ 🎉 🖥 (✅ 🐛 🎉): - -
- -```console -$ source ./env/Scripts/activate -``` - -
- -//// - -✅ ⚫️ 👷, ⚙️: - -//// tab | 💾, 🇸🇻, 🚪 🎉 - -
- -```console -$ which pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -//// tab | 🚪 📋 - -
- -```console -$ Get-Command pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -🚥 ⚫️ 🎦 `pip` 💱 `env/bin/pip` ⤴️ ⚫️ 👷. 👶 - -⚒ 💭 👆 ✔️ 📰 🐖 ⏬ 🔛 👆 🕹 🌐 ❎ ❌ 🔛 ⏭ 📶: - -
- -```console -$ python -m pip install --upgrade pip - ----> 100% -``` - -
- -/// tip - -🔠 🕰 👆 ❎ 🆕 📦 ⏮️ `pip` 🔽 👈 🌐, 🔓 🌐 🔄. - -👉 ⚒ 💭 👈 🚥 👆 ⚙️ 📶 📋 ❎ 👈 📦, 👆 ⚙️ 1️⃣ ⚪️➡️ 👆 🇧🇿 🌐 & 🚫 🙆 🎏 👈 💪 ❎ 🌐. - -/// - -### 🐖 - -⏮️ 🔓 🌐 🔬 🔛: - -
- -```console -$ pip install -r requirements.txt - ----> 100% -``` - -
- -⚫️ 🔜 ❎ 🌐 🔗 & 👆 🇧🇿 FastAPI 👆 🇧🇿 🌐. - -#### ⚙️ 👆 🇧🇿 FastAPI - -🚥 👆 ✍ 🐍 📁 👈 🗄 & ⚙️ FastAPI, & 🏃 ⚫️ ⏮️ 🐍 ⚪️➡️ 👆 🇧🇿 🌐, ⚫️ 🔜 ⚙️ 👆 🇧🇿 FastAPI ℹ 📟. - -& 🚥 👆 ℹ 👈 🇧🇿 FastAPI ℹ 📟, ⚫️ ❎ ⏮️ `-e`, 🕐❔ 👆 🏃 👈 🐍 📁 🔄, ⚫️ 🔜 ⚙️ 🍋 ⏬ FastAPI 👆 ✍. - -👈 🌌, 👆 🚫 ✔️ "❎" 👆 🇧🇿 ⏬ 💪 💯 🔠 🔀. - -### 📁 - -📤 ✍ 👈 👆 💪 🏃 👈 🔜 📁 & 🧹 🌐 👆 📟: - -
- -```console -$ bash scripts/format.sh -``` - -
- -⚫️ 🔜 🚘-😇 🌐 👆 🗄. - -⚫️ 😇 👫 ☑, 👆 💪 ✔️ FastAPI ❎ 🌐 👆 🌐, ⏮️ 📋 📄 🔛 ⚙️ `-e`. - -## 🩺 - -🥇, ⚒ 💭 👆 ⚒ 🆙 👆 🌐 🔬 🔛, 👈 🔜 ❎ 🌐 📄. - -🧾 ⚙️ . - -& 📤 ➕ 🧰/✍ 🥉 🍵 ✍ `./scripts/docs.py`. - -/// tip - -👆 🚫 💪 👀 📟 `./scripts/docs.py`, 👆 ⚙️ ⚫️ 📋 ⏸. - -/// - -🌐 🧾 ✍ 📁 📁 `./docs/en/`. - -📚 🔰 ✔️ 🍫 📟. - -🌅 💼, 👫 🍫 📟 ☑ 🏁 🈸 👈 💪 🏃. - -👐, 👈 🍫 📟 🚫 ✍ 🔘 ✍, 👫 🐍 📁 `./docs_src/` 📁. - -& 👈 🐍 📁 🔌/💉 🧾 🕐❔ 🏭 🕸. - -### 🩺 💯 - -🏆 💯 🤙 🏃 🛡 🖼 ℹ 📁 🧾. - -👉 ℹ ⚒ 💭 👈: - -* 🧾 🆙 📅. -* 🧾 🖼 💪 🏃. -* 🌅 ⚒ 📔 🧾, 🚚 💯 💰. - -⏮️ 🇧🇿 🛠️, 📤 ✍ 👈 🏗 🕸 & ✅ 🙆 🔀, 🖖-🔫: - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -⚫️ 🔜 🍦 🧾 🔛 `http://127.0.0.1:8008`. - -👈 🌌, 👆 💪 ✍ 🧾/ℹ 📁 & 👀 🔀 🖖. - -#### 🏎 ✳ (📦) - -👩‍🌾 📥 🎦 👆 ❔ ⚙️ ✍ `./scripts/docs.py` ⏮️ `python` 📋 🔗. - -✋️ 👆 💪 ⚙️ 🏎 ✳, & 👆 🔜 🤚 ✍ 👆 📶 📋 ⏮️ ❎ 🛠️. - -🚥 👆 ❎ 🏎 ✳, 👆 💪 ❎ 🛠️ ⏮️: - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### 📱 & 🩺 🎏 🕰 - -🚥 👆 🏃 🖼 ⏮️, ✅: - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -Uvicorn 🔢 🔜 ⚙️ ⛴ `8000`, 🧾 🔛 ⛴ `8008` 🏆 🚫 ⚔. - -### ✍ - -ℹ ⏮️ ✍ 📶 🌅 👍 ❗ & ⚫️ 💪 🚫 🔨 🍵 ℹ ⚪️➡️ 👪. 👶 👶 - -📥 📶 ℹ ⏮️ ✍. - -#### 💁‍♂ & 📄 - -* ✅ ⏳ ♻ 🚲 📨 👆 🇪🇸 & 🚮 📄 ✔ 🔀 ⚖️ ✔ 👫. - -/// tip - -👆 💪 🚮 🏤 ⏮️ 🔀 🔑 ♻ 🚲 📨. - -✅ 🩺 🔃 ❎ 🚲 📨 📄 ✔ ⚫️ ⚖️ 📨 🔀. - -/// - -* ✅ 👀 🚥 📤 1️⃣ 🛠️ ✍ 👆 🇪🇸. - -* 🚮 👁 🚲 📨 📍 📃 💬. 👈 🔜 ⚒ ⚫️ 🌅 ⏩ 🎏 📄 ⚫️. - -🇪🇸 👤 🚫 💬, 👤 🔜 ⌛ 📚 🎏 📄 ✍ ⏭ 🔗. - -* 👆 💪 ✅ 🚥 📤 ✍ 👆 🇪🇸 & 🚮 📄 👫, 👈 🔜 ℹ 👤 💭 👈 ✍ ☑ & 👤 💪 🔗 ⚫️. - -* ⚙️ 🎏 🐍 🖼 & 🕴 💬 ✍ 🩺. 👆 🚫 ✔️ 🔀 🕳 👉 👷. - -* ⚙️ 🎏 🖼, 📁 📛, & 🔗. 👆 🚫 ✔️ 🔀 🕳 ⚫️ 👷. - -* ✅ 2️⃣-🔤 📟 🇪🇸 👆 💚 💬 👆 💪 ⚙️ 🏓 📇 💾 6️⃣3️⃣9️⃣-1️⃣ 📟. - -#### ♻ 🇪🇸 - -➡️ 💬 👆 💚 💬 📃 🇪🇸 👈 ⏪ ✔️ ✍ 📃, 💖 🇪🇸. - -💼 🇪🇸, 2️⃣-🔤 📟 `es`. , 📁 🇪🇸 ✍ 🔎 `docs/es/`. - -/// tip - -👑 ("🛂") 🇪🇸 🇪🇸, 🔎 `docs/en/`. - -/// - -🔜 🏃 🖖 💽 🩺 🇪🇸: - -
- -```console -// Use the command "live" and pass the language code as a CLI argument -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -🔜 👆 💪 🚶 http://127.0.0.1:8008 & 👀 👆 🔀 🖖. - -🚥 👆 👀 FastAPI 🩺 🕸, 👆 🔜 👀 👈 🔠 🇪🇸 ✔️ 🌐 📃. ✋️ 📃 🚫 💬 & ✔️ 📨 🔃 ❌ ✍. - -✋️ 🕐❔ 👆 🏃 ⚫️ 🌐 💖 👉, 👆 🔜 🕴 👀 📃 👈 ⏪ 💬. - -🔜 ➡️ 💬 👈 👆 💚 🚮 ✍ 📄 [⚒](features.md){.internal-link target=_blank}. - -* 📁 📁: - -``` -docs/en/docs/features.md -``` - -* 📋 ⚫️ ⚫️❔ 🎏 🗺 ✋️ 🇪🇸 👆 💚 💬, ✅: - -``` -docs/es/docs/features.md -``` - -/// tip - -👀 👈 🕴 🔀 ➡ & 📁 📛 🇪🇸 📟, ⚪️➡️ `en` `es`. - -/// - -* 🔜 📂 ⬜ 📁 📁 🇪🇸: - -``` -docs/en/mkdocs.yml -``` - -* 🔎 🥉 🌐❔ 👈 `docs/features.md` 🔎 📁 📁. 👱 💖: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -* 📂 ⬜ 📁 📁 🇪🇸 👆 ✍, ✅: - -``` -docs/es/mkdocs.yml -``` - -* 🚮 ⚫️ 📤 ☑ 🎏 🗺 ⚫️ 🇪🇸, ✅: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -⚒ 💭 👈 🚥 📤 🎏 ⛔, 🆕 ⛔ ⏮️ 👆 ✍ ⚫️❔ 🎏 ✔ 🇪🇸 ⏬. - -🚥 👆 🚶 👆 🖥 👆 🔜 👀 👈 🔜 🩺 🎦 👆 🆕 📄. 👶 - -🔜 👆 💪 💬 ⚫️ 🌐 & 👀 ❔ ⚫️ 👀 👆 🖊 📁. - -#### 🆕 🇪🇸 - -➡️ 💬 👈 👆 💚 🚮 ✍ 🇪🇸 👈 🚫 💬, 🚫 📃. - -➡️ 💬 👆 💚 🚮 ✍ 🇭🇹, & ⚫️ 🚫 📤 🩺. - -✅ 🔗 ⚪️➡️ 🔛, 📟 "🇭🇹" `ht`. - -⏭ 🔁 🏃 ✍ 🏗 🆕 ✍ 📁: - -
- -```console -// Use the command new-lang, pass the language code as a CLI argument -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -Updating ht -Updating en -``` - -
- -🔜 👆 💪 ✅ 👆 📟 👨‍🎨 ⏳ ✍ 📁 `docs/ht/`. - -/// tip - -✍ 🥇 🚲 📨 ⏮️ 👉, ⚒ 🆙 📳 🆕 🇪🇸, ⏭ ❎ ✍. - -👈 🌌 🎏 💪 ℹ ⏮️ 🎏 📃 ⏪ 👆 👷 🔛 🥇 🕐. 👶 - -/// - -▶️ ✍ 👑 📃, `docs/ht/index.md`. - -⤴️ 👆 💪 😣 ⏮️ ⏮️ 👩‍🌾, "♻ 🇪🇸". - -##### 🆕 🇪🇸 🚫 🐕‍🦺 - -🚥 🕐❔ 🏃‍♂ 🖖 💽 ✍ 👆 🤚 ❌ 🔃 🇪🇸 🚫 ➖ 🐕‍🦺, 🕳 💖: - -``` - raise TemplateNotFound(template) -jinja2.exceptions.TemplateNotFound: partials/language/xx.html -``` - -👈 ⛓ 👈 🎢 🚫 🐕‍🦺 👈 🇪🇸 (👉 💼, ⏮️ ❌ 2️⃣-🔤 📟 `xx`). - -✋️ 🚫 😟, 👆 💪 ⚒ 🎢 🇪🇸 🇪🇸 & ⤴️ 💬 🎚 🩺. - -🚥 👆 💪 👈, ✍ `mkdocs.yml` 👆 🆕 🇪🇸, ⚫️ 🔜 ✔️ 🕳 💖: - -```YAML hl_lines="5" -site_name: FastAPI -# More stuff -theme: - # More stuff - language: xx -``` - -🔀 👈 🇪🇸 ⚪️➡️ `xx` (⚪️➡️ 👆 🇪🇸 📟) `en`. - -⤴️ 👆 💪 ▶️ 🖖 💽 🔄. - -#### 🎮 🏁 - -🕐❔ 👆 ⚙️ ✍ `./scripts/docs.py` ⏮️ `live` 📋 ⚫️ 🕴 🎦 📁 & ✍ 💪 ⏮️ 🇪🇸. - -✋️ 🕐 👆 🔨, 👆 💪 💯 ⚫️ 🌐 ⚫️ 🔜 👀 💳. - -👈, 🥇 🏗 🌐 🩺: - -
- -```console -// Use the command "build-all", this will take a bit -$ python ./scripts/docs.py build-all - -Updating es -Updating en -Building docs for: en -Building docs for: es -Successfully built docs for: es -Copying en index.md to README.md -``` - -
- -👈 🏗 🌐 🩺 `./docs_build/` 🔠 🇪🇸. 👉 🔌 ❎ 🙆 📁 ⏮️ ❌ ✍, ⏮️ 🗒 💬 👈 "👉 📁 🚫 ✔️ ✍". ✋️ 👆 🚫 ✔️ 🕳 ⏮️ 👈 📁. - -⤴️ ⚫️ 🏗 🌐 👈 🔬 ⬜ 🕸 🔠 🇪🇸, 🌀 👫, & 🏗 🏁 🔢 `./site/`. - -⤴️ 👆 💪 🍦 👈 ⏮️ 📋 `serve`: - -
- -```console -// Use the command "serve" after running "build-all" -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -## 💯 - -📤 ✍ 👈 👆 💪 🏃 🌐 💯 🌐 📟 & 🏗 💰 📄 🕸: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -👉 📋 🏗 📁 `./htmlcov/`, 🚥 👆 📂 📁 `./htmlcov/index.html` 👆 🖥, 👆 💪 🔬 🖥 🇹🇼 📟 👈 📔 💯, & 👀 🚥 📤 🙆 🇹🇼 ❌. diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index 3a25b4ed5..a29bb03e9 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -289,6 +289,7 @@ Now you can translate it all and see how it looks as you save the file. * `newsletter.md` * `management-tasks.md` * `management.md` +* `contributing.md` Some of these files are updated very frequently and a translation would always be behind, or they include the main content from English source files, etc. @@ -380,7 +381,7 @@ Serving at: http://127.0.0.1:8008 * Do not change anything enclosed in "``" (inline code). -* In lines starting with `///` translate only the ` "... Text ..."` part. Leave the rest unchanged. +* In lines starting with `///` translate only the text part after `|`. Leave the rest unchanged. * You can translate info boxes like `/// warning` with for example `/// warning | Achtung`. But do not change the word immediately after the `///`, it determines the color of the info box. diff --git a/docs/fr/docs/contributing.md b/docs/fr/docs/contributing.md deleted file mode 100644 index 408958339..000000000 --- a/docs/fr/docs/contributing.md +++ /dev/null @@ -1,533 +0,0 @@ -# Développement - Contribuer - -Tout d'abord, vous voudrez peut-être voir les moyens de base pour [aider FastAPI et obtenir de l'aide](help-fastapi.md){.internal-link target=_blank}. - -## Développement - -Si vous avez déjà cloné le dépôt et que vous savez que vous devez vous plonger dans le code, voici quelques directives pour mettre en place votre environnement. - -### Environnement virtuel avec `venv` - -Vous pouvez créer un environnement virtuel dans un répertoire en utilisant le module `venv` de Python : - -
- -```console -$ python -m venv env -``` - -
- -Cela va créer un répertoire `./env/` avec les binaires Python et vous pourrez alors installer des paquets pour cet environnement isolé. - -### Activer l'environnement - -Activez le nouvel environnement avec : - -//// tab | Linux, macOS - -
- -```console -$ source ./env/bin/activate -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ .\env\Scripts\Activate.ps1 -``` - -
- -//// - -//// tab | Windows Bash - -Ou si vous utilisez Bash pour Windows (par exemple Git Bash): - -
- -```console -$ source ./env/Scripts/activate -``` - -
- -//// - -Pour vérifier que cela a fonctionné, utilisez : - -//// tab | Linux, macOS, Windows Bash - -
- -```console -$ which pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ Get-Command pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -Si celui-ci montre le binaire `pip` à `env/bin/pip`, alors ça a fonctionné. 🎉 - - - -/// tip - -Chaque fois que vous installez un nouveau paquet avec `pip` sous cet environnement, activez à nouveau l'environnement. - -Cela permet de s'assurer que si vous utilisez un programme terminal installé par ce paquet (comme `flit`), vous utilisez celui de votre environnement local et pas un autre qui pourrait être installé globalement. - -/// - -### Flit - -**FastAPI** utilise Flit pour build, packager et publier le projet. - -Après avoir activé l'environnement comme décrit ci-dessus, installez `flit` : - -
- -```console -$ pip install flit - ----> 100% -``` - -
- -Réactivez maintenant l'environnement pour vous assurer que vous utilisez le "flit" que vous venez d'installer (et non un environnement global). - -Et maintenant, utilisez `flit` pour installer les dépendances de développement : - -//// tab | Linux, macOS - -
- -```console -$ flit install --deps develop --symlink - ----> 100% -``` - -
- -//// - -//// tab | Windows - -Si vous êtes sous Windows, utilisez `--pth-file` au lieu de `--symlink` : - -
- -```console -$ flit install --deps develop --pth-file - ----> 100% -``` - -
- -//// - -Il installera toutes les dépendances et votre FastAPI local dans votre environnement local. - -#### Utiliser votre FastAPI local - -Si vous créez un fichier Python qui importe et utilise FastAPI, et que vous l'exécutez avec le Python de votre environnement local, il utilisera votre code source FastAPI local. - -Et si vous mettez à jour le code source local de FastAPI, tel qu'il est installé avec `--symlink` (ou `--pth-file` sous Windows), lorsque vous exécutez à nouveau ce fichier Python, il utilisera la nouvelle version de FastAPI que vous venez d'éditer. - -De cette façon, vous n'avez pas à "installer" votre version locale pour pouvoir tester chaque changement. - -### Formatage - -Il existe un script que vous pouvez exécuter qui formatera et nettoiera tout votre code : - -
- -```console -$ bash scripts/format.sh -``` - -
- -Il effectuera également un tri automatique de touts vos imports. - -Pour qu'il puisse les trier correctement, vous devez avoir FastAPI installé localement dans votre environnement, avec la commande dans la section ci-dessus en utilisant `--symlink` (ou `--pth-file` sous Windows). - -### Formatage des imports - -Il existe un autre script qui permet de formater touts les imports et de s'assurer que vous n'avez pas d'imports inutilisés : - -
- -```console -$ bash scripts/format-imports.sh -``` - -
- -Comme il exécute une commande après l'autre et modifie et inverse de nombreux fichiers, il prend un peu plus de temps à s'exécuter, il pourrait donc être plus facile d'utiliser fréquemment `scripts/format.sh` et `scripts/format-imports.sh` seulement avant de commit. - -## Documentation - -Tout d'abord, assurez-vous que vous configurez votre environnement comme décrit ci-dessus, qui installera toutes les exigences. - -La documentation utilise MkDocs. - -Et il y a des outils/scripts supplémentaires en place pour gérer les traductions dans `./scripts/docs.py`. - -/// tip - -Vous n'avez pas besoin de voir le code dans `./scripts/docs.py`, vous l'utilisez simplement dans la ligne de commande. - -/// - -Toute la documentation est au format Markdown dans le répertoire `./docs/fr/`. - -De nombreux tutoriels comportent des blocs de code. - -Dans la plupart des cas, ces blocs de code sont de véritables applications complètes qui peuvent être exécutées telles quelles. - -En fait, ces blocs de code ne sont pas écrits à l'intérieur du Markdown, ce sont des fichiers Python dans le répertoire `./docs_src/`. - -Et ces fichiers Python sont inclus/injectés dans la documentation lors de la génération du site. - -### Documentation pour les tests - -La plupart des tests sont en fait effectués par rapport aux exemples de fichiers sources dans la documentation. - -Cela permet de s'assurer que : - -* La documentation est à jour. -* Les exemples de documentation peuvent être exécutés tels quels. -* La plupart des fonctionnalités sont couvertes par la documentation, assurées par la couverture des tests. - -Au cours du développement local, un script build le site et vérifie les changements éventuels, puis il est rechargé en direct : - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Il servira la documentation sur `http://127.0.0.1:8008`. - -De cette façon, vous pouvez modifier la documentation/les fichiers sources et voir les changements en direct. - -#### Typer CLI (facultatif) - -Les instructions ici vous montrent comment utiliser le script à `./scripts/docs.py` avec le programme `python` directement. - -Mais vous pouvez également utiliser Typer CLI, et vous obtiendrez l'auto-complétion dans votre terminal pour les commandes après l'achèvement de l'installation. - -Si vous installez Typer CLI, vous pouvez installer la complétion avec : - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### Apps et documentation en même temps - -Si vous exécutez les exemples avec, par exemple : - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -Comme Uvicorn utilisera par défaut le port `8000`, la documentation sur le port `8008` n'entrera pas en conflit. - -### Traductions - -L'aide aux traductions est TRÈS appréciée ! Et cela ne peut se faire sans l'aide de la communauté. 🌎 🚀 - -Voici les étapes à suivre pour aider à la traduction. - -#### Conseils et lignes directrices - -* Vérifiez les pull requests existantes pour votre langue et ajouter des reviews demandant des changements ou les approuvant. - -/// tip - -Vous pouvez ajouter des commentaires avec des suggestions de changement aux pull requests existantes. - -Consultez les documents concernant l'ajout d'un review de pull request pour l'approuver ou demander des modifications. - -/// - -* Vérifiez dans issues pour voir s'il y a une personne qui coordonne les traductions pour votre langue. - -* Ajoutez une seule pull request par page traduite. Il sera ainsi beaucoup plus facile pour les autres de l'examiner. - -Pour les langues que je ne parle pas, je vais attendre plusieurs autres reviews de la traduction avant de merge. - -* Vous pouvez également vérifier s'il existe des traductions pour votre langue et y ajouter une review, ce qui m'aidera à savoir si la traduction est correcte et je pourrai la fusionner. - -* Utilisez les mêmes exemples en Python et ne traduisez que le texte des documents. Vous n'avez pas besoin de changer quoi que ce soit pour que cela fonctionne. - -* Utilisez les mêmes images, noms de fichiers et liens. Vous n'avez pas besoin de changer quoi que ce soit pour que cela fonctionne. - -* Pour vérifier le code à 2 lettres de la langue que vous souhaitez traduire, vous pouvez utiliser le tableau Liste des codes ISO 639-1. - -#### Langue existante - -Disons que vous voulez traduire une page pour une langue qui a déjà des traductions pour certaines pages, comme l'espagnol. - -Dans le cas de l'espagnol, le code à deux lettres est `es`. Ainsi, le répertoire des traductions espagnoles se trouve à l'adresse `docs/es/`. - -/// tip - -La langue principale ("officielle") est l'anglais, qui se trouve à l'adresse "docs/en/". - -/// - -Maintenant, lancez le serveur en live pour les documents en espagnol : - -
- -```console -// Use the command "live" and pass the language code as a CLI argument -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Vous pouvez maintenant aller sur http://127.0.0.1:8008 et voir vos changements en direct. - -Si vous regardez le site web FastAPI docs, vous verrez que chaque langue a toutes les pages. Mais certaines pages ne sont pas traduites et sont accompagnées d'une notification concernant la traduction manquante. - -Mais si vous le gérez localement de cette manière, vous ne verrez que les pages déjà traduites. - -Disons maintenant que vous voulez ajouter une traduction pour la section [Features](features.md){.internal-link target=_blank}. - -* Copiez le fichier à : - -``` -docs/en/docs/features.md -``` - -* Collez-le exactement au même endroit mais pour la langue que vous voulez traduire, par exemple : - -``` -docs/es/docs/features.md -``` - -/// tip - -Notez que le seul changement dans le chemin et le nom du fichier est le code de langue, qui passe de `en` à `es`. - -/// - -* Ouvrez maintenant le fichier de configuration de MkDocs pour l'anglais à - -``` -docs/en/docs/mkdocs.yml -``` - -* Trouvez l'endroit où cette `docs/features.md` se trouve dans le fichier de configuration. Quelque part comme : - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -* Ouvrez le fichier de configuration MkDocs pour la langue que vous éditez, par exemple : - -``` -docs/es/docs/mkdocs.yml -``` - -* Ajoutez-le à l'endroit exact où il se trouvait pour l'anglais, par exemple : - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -Assurez-vous que s'il y a d'autres entrées, la nouvelle entrée avec votre traduction est exactement dans le même ordre que dans la version anglaise. - -Si vous allez sur votre navigateur, vous verrez que maintenant les documents montrent votre nouvelle section. 🎉 - -Vous pouvez maintenant tout traduire et voir à quoi cela ressemble au fur et à mesure que vous enregistrez le fichier. - -#### Nouvelle langue - -Disons que vous voulez ajouter des traductions pour une langue qui n'est pas encore traduite, pas même quelques pages. - -Disons que vous voulez ajouter des traductions pour le Créole, et que ce n'est pas encore dans les documents. - -En vérifiant le lien ci-dessus, le code pour "Créole" est `ht`. - -L'étape suivante consiste à exécuter le script pour générer un nouveau répertoire de traduction : - -
- -```console -// Use the command new-lang, pass the language code as a CLI argument -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -Updating ht -Updating en -``` - -
- -Vous pouvez maintenant vérifier dans votre éditeur de code le répertoire nouvellement créé `docs/ht/`. - -/// tip - -Créez une première demande d'extraction à l'aide de cette fonction, afin de configurer la nouvelle langue avant d'ajouter des traductions. - -Ainsi, d'autres personnes peuvent vous aider à rédiger d'autres pages pendant que vous travaillez sur la première. 🚀 - -/// - -Commencez par traduire la page principale, `docs/ht/index.md`. - -Vous pouvez ensuite continuer avec les instructions précédentes, pour une "langue existante". - -##### Nouvelle langue non prise en charge - -Si, lors de l'exécution du script du serveur en direct, vous obtenez une erreur indiquant que la langue n'est pas prise en charge, quelque chose comme : - -``` - raise TemplateNotFound(template) -jinja2.exceptions.TemplateNotFound: partials/language/xx.html -``` - -Cela signifie que le thème ne supporte pas cette langue (dans ce cas, avec un faux code de 2 lettres de `xx`). - -Mais ne vous inquiétez pas, vous pouvez définir la langue du thème en anglais et ensuite traduire le contenu des documents. - -Si vous avez besoin de faire cela, modifiez le fichier `mkdocs.yml` pour votre nouvelle langue, il aura quelque chose comme : - -```YAML hl_lines="5" -site_name: FastAPI -# More stuff -theme: - # More stuff - language: xx -``` - -Changez cette langue de `xx` (de votre code de langue) à `fr`. - -Vous pouvez ensuite relancer le serveur live. - -#### Prévisualisez le résultat - -Lorsque vous utilisez le script à `./scripts/docs.py` avec la commande `live`, il n'affiche que les fichiers et les traductions disponibles pour la langue courante. - -Mais une fois que vous avez terminé, vous pouvez tester le tout comme il le ferait en ligne. - -Pour ce faire, il faut d'abord construire tous les documents : - -
- -```console -// Use the command "build-all", this will take a bit -$ python ./scripts/docs.py build-all - -Updating es -Updating en -Building docs for: en -Building docs for: es -Successfully built docs for: es -Copying en index.md to README.md -``` - -
- -Cela génère tous les documents à `./docs_build/` pour chaque langue. Cela inclut l'ajout de tout fichier dont la traduction est manquante, avec une note disant que "ce fichier n'a pas encore de traduction". Mais vous n'avez rien à faire avec ce répertoire. - -Ensuite, il construit tous ces sites MkDocs indépendants pour chaque langue, les combine, et génère le résultat final à `./site/`. - -Ensuite, vous pouvez servir cela avec le commandement `serve`: - -
- -```console -// Use the command "serve" after running "build-all" -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -## Tests - -Il existe un script que vous pouvez exécuter localement pour tester tout le code et générer des rapports de couverture en HTML : - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -Cette commande génère un répertoire `./htmlcov/`, si vous ouvrez le fichier `./htmlcov/index.html` dans votre navigateur, vous pouvez explorer interactivement les régions de code qui sont couvertes par les tests, et remarquer s'il y a une région manquante. diff --git a/docs/ja/docs/contributing.md b/docs/ja/docs/contributing.md deleted file mode 100644 index 3ee742ec2..000000000 --- a/docs/ja/docs/contributing.md +++ /dev/null @@ -1,498 +0,0 @@ -# 開発 - 貢献 - -まず、[FastAPIを応援 - ヘルプの入手](help-fastapi.md){.internal-link target=_blank}の基本的な方法を見て、ヘルプを得た方がいいかもしれません。 - -## 開発 - -すでにリポジトリをクローンし、コードを詳しく調べる必要があるとわかっている場合に、環境構築のためのガイドラインをいくつか紹介します。 - -### `venv`を使用した仮想環境 - -Pythonの`venv`モジュールを使用して、ディレクトリに仮想環境を作成します: - -
- -```console -$ python -m venv env -``` - -
- -これにより、Pythonバイナリを含む`./env/`ディレクトリが作成され、その隔離された環境にパッケージのインストールが可能になります。 - -### 仮想環境の有効化 - -新しい環境を有効化するには: - -//// tab | Linux, macOS - -
- -```console -$ source ./env/bin/activate -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ .\env\Scripts\Activate.ps1 -``` - -
- -//// - -//// tab | Windows Bash - -もしwindows用のBash (例えば、Git Bash)を使っているなら: - -
- -```console -$ source ./env/Scripts/activate -``` - -
- -//// - -動作の確認には、下記を実行します: - -//// tab | Linux, macOS, Windows Bash - -
- -```console -$ which pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ Get-Command pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -`env/bin/pip`に`pip`バイナリが表示される場合は、正常に機能しています。🎉 - - -/// tip | 豆知識 - -この環境で`pip`を使って新しいパッケージをインストールするたびに、仮想環境を再度有効化します。 - -これにより、そのパッケージによってインストールされたターミナルのプログラム を使用する場合、ローカル環境のものを使用し、グローバルにインストールされたものは使用されなくなります。 - -/// - -### pip - -上記のように環境を有効化した後: - -
- -```console -$ pip install -r requirements.txt - ----> 100% -``` - -
- -これで、すべての依存関係とFastAPIを、ローカル環境にインストールします。 - -#### ローカル環境でFastAPIを使う - -FastAPIをインポートして使用するPythonファイルを作成し、ローカル環境で実行すると、ローカルのFastAPIソースコードが使用されます。 - -そして、`-e` でインストールされているローカルのFastAPIソースコードを更新した場合、そのPythonファイルを再度実行すると、更新したばかりの新しいバージョンのFastAPIが使用されます。 - -これにより、ローカルバージョンを「インストール」しなくても、すべての変更をテストできます。 - -### コードの整形 - -すべてのコードを整形してクリーンにするスクリプトがあります: - -
- -```console -$ bash scripts/format.sh -``` - -
- -また、すべてのインポートを自動でソートします。 - -正しく並べ替えるには、上記セクションのコマンドで `-e` を使い、FastAPIをローカル環境にインストールしている必要があります。 - -### インポートの整形 - -他にも、すべてのインポートを整形し、未使用のインポートがないことを確認するスクリプトがあります: - -
- -```console -$ bash scripts/format-imports.sh -``` - -
- -多くのファイルを編集したり、リバートした後、これらのコマンドを実行すると、少し時間がかかります。なので`scripts/format.sh`を頻繁に使用し、`scripts/format-imports.sh`をコミット前に実行する方が楽でしょう。 - -## ドキュメント - -まず、上記のように環境をセットアップしてください。すべての必要なパッケージがインストールされます。 - -ドキュメントは、MkDocsを使っています。 - -そして、翻訳を処理するためのツール/スクリプトが、`./scripts/docs.py`に用意されています。 - -/// tip | 豆知識 - -`./scripts/docs.py`のコードを見る必要はなく、コマンドラインからただ使うだけです。 - -/// - -すべてのドキュメントが、Markdown形式で`./docs/en/`ディレクトリにあります。 - -多くのチュートリアルには、コードブロックがあります。 - -ほとんどの場合、これらのコードブロックは、実際にそのまま実行できる完全なアプリケーションです。 - -実際、これらのコードブロックはMarkdown内には記述されておらず、`./docs_src/`ディレクトリのPythonファイルです。 - -そして、これらのPythonファイルは、サイトの生成時にドキュメントに含まれるか/挿入されます。 - -### ドキュメントのテスト - -ほとんどのテストは、実際にドキュメント内のサンプルソースファイルに対して実行されます。 - -これにより、次のことが確認できます: - -* ドキュメントが最新であること。 -* ドキュメントの例が、そのまま実行できること。 -* ほとんどの機能がドキュメントでカバーされており、テスト範囲で保証されていること。 - -ローカル開発中に、サイトを構築して変更がないかチェックするスクリプトがあり、ライブリロードされます: - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -ドキュメントは、`http://127.0.0.1:8008`で提供します。 - -そうすることで、ドキュメント/ソースファイルを編集し、変更をライブで見ることができます。 - -#### Typer CLI (任意) - -ここでは、`./scripts/docs.py`のスクリプトを`python`プログラムで直接使う方法を説明します。 - -ですがTyper CLIを使用して、インストール完了後にターミナルでの自動補完もできます。 - -Typer CLIをインストールする場合、次のコマンドで補完をインストールできます: - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### アプリとドキュメントを同時に - -以下の様にサンプルを実行すると: - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -Uvicornはデフォルトでポート`8000`を使用するため、ポート`8008`のドキュメントは衝突しません。 - -### 翻訳 - -翻訳のヘルプをとても歓迎しています!これはコミュニティの助けなしでは成し遂げられません。 🌎🚀 - -翻訳を支援するための手順は次のとおりです。 - -#### 豆知識とガイドライン - -* あなたの言語の今あるプルリクエストを確認し、変更や承認をするレビューを追加します。 - -/// tip | 豆知識 - -すでにあるプルリクエストに修正提案つきのコメントを追加できます。 - -修正提案の承認のためにプルリクエストのレビューの追加のドキュメントを確認してください。 - -/// - -* issuesをチェックして、あなたの言語に対応する翻訳があるかどうかを確認してください。 - -* 翻訳したページごとに1つのプルリクエストを追加します。これにより、他のユーザーがレビューしやすくなります。 - -私が話さない言語については、他の何人かが翻訳をレビューするのを待って、マージします。 - -* 自分の言語の翻訳があるかどうか確認し、レビューを追加できます。これにより、翻訳が正しく、マージできることがわかります。 - -* 同じPythonの例を使用し、ドキュメント内のテキストのみを翻訳してください。何も変更する必要はありません。 - -* 同じ画像、ファイル名、リンクを使用します。何も変更する必要はありません。 - -* 翻訳する言語の2文字のコードを確認するには、表 ISO 639-1コードのリストが使用できます。 - -#### すでにある言語 - -スペイン語の様に、既に一部のページが翻訳されている言語の翻訳を追加したいとしましょう。 - -スペイン語の場合、2文字のコードは`es`です。したがって、スペイン語のディレクトリは`docs/es/`です。 - -/// tip | 豆知識 - -メイン (「公式」) 言語は英語で、`docs/en/`にあります。 - -/// - -次に、ドキュメントのライブサーバーをスペイン語で実行します: - -
- -```console -// コマンド"live"を使用し、言語コードをCLIに引数で渡します。 -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -これでhttp://127.0.0.1:8008 を開いて、変更を確認できます。 - -FastAPI docs Webサイトを見ると、すべての言語にすべてのページがあります。しかし、一部のページは翻訳されておらず、翻訳の欠落ページについて通知があります。 - -しかし、このようにローカルで実行すると、翻訳済みのページのみが表示されます。 - -ここで、セクション[Features](features.md){.internal-link target=_blank}の翻訳を追加するとします。 - -* 下記のファイルをコピーします: - -``` -docs/en/docs/features.md -``` - -* 翻訳したい言語のまったく同じところに貼り付けます。例えば: - -``` -docs/es/docs/features.md -``` - -/// tip | 豆知識 - -パスとファイル名の変更は、`en`から`es`への言語コードだけであることに注意してください。 - -/// - -* ここで、英語のMkDocs構成ファイルを開きます: - -``` -docs/en/docs/mkdocs.yml -``` - -* 設定ファイルの中で、`docs/features.md`が記述されている箇所を見つけます: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -* 編集している言語のMkDocs構成ファイルを開きます。例えば: - -``` -docs/es/docs/mkdocs.yml -``` - -* 英語とまったく同じ場所に追加します。例えば: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -他のエントリがある場合は、翻訳を含む新しいエントリが英語版とまったく同じ順序になっていることを確認してください。 - -ブラウザにアクセスすれば、ドキュメントに新しいセクションが表示されています。 🎉 - -これですべて翻訳して、ファイルを保存した状態を確認できます。 - -#### 新しい言語 - -まだ翻訳されていない言語の翻訳を追加したいとしましょう。 - -クレオール語の翻訳を追加したいのですが、それはまだドキュメントにありません。 - -上記のリンクを確認すると、「クレオール語」のコードは`ht`です。 - -次のステップは、スクリプトを実行して新しい翻訳ディレクトリを生成することです: - -
- -```console -// コマンド「new-lang」を使用して、言語コードをCLIに引数で渡します -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -Updating ht -Updating en -``` - -
- -これで、新しく作成された`docs/ht/`ディレクトリをコードエディターから確認できます。 - -/// tip | 豆知識 - -翻訳を追加する前に、これだけで最初のプルリクエストを作成し、新しい言語の設定をセットアップします。 - -そうすることで、最初のページで作業している間、誰かの他のページの作業を助けることができます。 🚀 - -/// - -まず、メインページの`docs/ht/index.md`を翻訳します。 - -その後、「既存の言語」で、さきほどの手順を続行してください。 - -##### まだサポートされていない新しい言語 - -ライブサーバースクリプトを実行するときに、サポートされていない言語に関するエラーが発生した場合は、次のように表示されます: - -``` - raise TemplateNotFound(template) -jinja2.exceptions.TemplateNotFound: partials/language/xx.html -``` - -これは、テーマがその言語をサポートしていないことを意味します (この場合は、`xx`の2文字の偽のコード) 。 - -ただし、心配しないでください。テーマ言語を英語に設定して、ドキュメントの内容を翻訳できます。 - -その必要がある場合は、新しい言語の`mkdocs.yml`を次のように編集してください: - -```YAML hl_lines="5" -site_name: FastAPI -# More stuff -theme: - # More stuff - language: xx -``` - -その言語を`xx` (あなたの言語コード) から`en`に変更します。 - -その後、ライブサーバーを再起動します。 - -#### 結果のプレビュー - -`./scripts/docs.py`のスクリプトを`live`コマンドで使用すると、現在の言語で利用可能なファイルと翻訳のみが表示されます。 - -しかし一度実行したら、オンラインで表示されるのと同じように、すべてをテストできます。 - -このために、まずすべてのドキュメントをビルドします: - -
- -```console -// 「build-all」コマンドは少し時間がかかります。 -$ python ./scripts/docs.py build-all - -Updating es -Updating en -Building docs for: en -Building docs for: es -Successfully built docs for: es -Copying en index.md to README.md -``` - -
- -これで、言語ごとにすべてのドキュメントが`./docs_build/`に作成されます。 - -これには、翻訳が欠落しているファイルを追加することと、「このファイルにはまだ翻訳がない」というメモが含まれます。ただし、そのディレクトリで何もする必要はありません。 - -次に、言語ごとにこれらすべての個別のMkDocsサイトを構築し、それらを組み合わせて、`./site/`に最終結果を出力します。 - -これは、コマンド`serve`で提供できます: - -
- -```console -// 「build-all」コマンドの実行の後に、「serve」コマンドを使います -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -## テスト - -すべてのコードをテストし、HTMLでカバレッジレポートを生成するためにローカルで実行できるスクリプトがあります: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -このコマンドは`./htmlcov/`ディレクトリを生成します。ブラウザでファイル`./htmlcov/index.html`を開くと、テストでカバーされているコードの領域をインタラクティブに探索できます。それによりテストが不足しているかどうか気付くことができます。 diff --git a/docs/pt/docs/contributing.md b/docs/pt/docs/contributing.md deleted file mode 100644 index bb518a2fa..000000000 --- a/docs/pt/docs/contributing.md +++ /dev/null @@ -1,507 +0,0 @@ -# Desenvolvimento - Contribuindo - -Primeiramente, você deveria ver os meios básicos para [ajudar FastAPI e pedir ajuda](help-fastapi.md){.internal-link target=_blank}. - -## Desenvolvendo - -Se você já clonou o repositório e precisa mergulhar no código, aqui estão algumas orientações para configurar seu ambiente. - -### Ambiente virtual com `venv` - -Você pode criar um ambiente virtual em um diretório utilizando o módulo `venv` do Python: - -
- -```console -$ python -m venv env -``` - -
- -Isso criará o diretório `./env/` com os binários Python e então você será capaz de instalar pacotes nesse ambiente isolado. - -### Ativar o ambiente - -Ative o novo ambiente com: - -//// tab | Linux, macOS - -
- -```console -$ source ./env/bin/activate -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ .\env\Scripts\Activate.ps1 -``` - -
- -//// - -//// tab | Windows Bash - -Ou se você usa Bash para Windows (por exemplo Git Bash): - -
- -```console -$ source ./env/Scripts/activate -``` - -
- -//// - -Para verificar se funcionou, use: - -//// tab | Linux, macOS, Windows Bash - -
- -```console -$ which pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ Get-Command pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -Se ele exibir o binário `pip` em `env/bin/pip` então funcionou. 🎉 - - - -/// tip - -Toda vez que você instalar um novo pacote com `pip` nesse ambiente, ative o ambiente novamente. - -Isso garante que se você usar um programa instalado por aquele pacote, você utilizará aquele de seu ambiente local e não outro que possa estar instalado globalmente. - -/// - -### pip - -Após ativar o ambiente como descrito acima: - -
- -```console -$ pip install -r requirements.txt - ----> 100% -``` - -
- -Isso irá instalar todas as dependências e seu FastAPI local em seu ambiente local. - -#### Usando seu FastAPI local - -Se você cria um arquivo Python que importa e usa FastAPI, e roda com Python de seu ambiente local, ele irá utilizar o código fonte de seu FastAPI local. - -E se você atualizar o código fonte do FastAPI local, como ele é instalado com `-e`, quando você rodar aquele arquivo Python novamente, ele irá utilizar a nova versão do FastAPI que você acabou de editar. - -Desse modo, você não tem que "instalar" sua versão local para ser capaz de testar cada mudança. - -### Formato - -Tem um arquivo que você pode rodar que irá formatar e limpar todo o seu código: - -
- -```console -$ bash scripts/format.sh -``` - -
- -Ele irá organizar também todos os seus imports. - -Para que ele organize os imports corretamente, você precisa ter o FastAPI instalado localmente em seu ambiente, com o comando na seção acima usando `-e`. - -### Formato dos imports - -Tem outro _script_ que formata todos os imports e garante que você não tenha imports não utilizados: - -
- -```console -$ bash scripts/format-imports.sh -``` - -
- -Como ele roda um comando após o outro, modificando e revertendo muitos arquivos, ele demora um pouco para concluir, então pode ser um pouco mais fácil utilizar `scripts/format.sh` frequentemente e `scripts/format-imports.sh` somente após "commitar uma branch". - -## Documentação - -Primeiro, tenha certeza de configurar seu ambiente como descrito acima, isso irá instalar todas as requisições. - -A documentação usa MkDocs. - -E existem ferramentas/_scripts_ extras para controlar as traduções em `./scripts/docs.py`. - -/// tip - -Você não precisa ver o código em `./scripts/docs.py`, você apenas o utiliza na linha de comando. - -/// - -Toda a documentação está no formato Markdown no diretório `./docs/pt/`. - -Muitos dos tutoriais tem blocos de código. - -Na maioria dos casos, esse blocos de código são aplicações completas que podem ser rodadas do jeito que estão apresentados. - -De fato, esses blocos de código não estão escritos dentro do Markdown, eles são arquivos Python dentro do diretório `./docs_src/`. - -E esses arquivos Python são incluídos/injetados na documentação quando se gera o site. - -### Testes para Documentação - -A maioria dos testes na verdade rodam encima dos arquivos fonte na documentação. - -Isso ajuda a garantir: - -* Que a documentação esteja atualizada. -* Que os exemplos da documentação possam ser rodadas do jeito que estão apresentadas. -* A maior parte dos recursos é coberta pela documentação, garantida por cobertura de testes. - -Durante o desenvolvimento local, existe um _script_ que constrói o site e procura por quaisquer mudanças, carregando na hora: - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Isso irá servir a documentação em `http://127.0.0.1:8008`. - -Desse jeito, você poderá editar a documentação/arquivos fonte e ver as mudanças na hora. - -#### Typer CLI (opcional) - -As instruções aqui mostram como utilizar _scripts_ em `./scripts/docs.py` com o programa `python` diretamente. - -Mas você pode usar também Typer CLI, e você terá auto-completação para comandos no seu terminal após instalar o _completion_. - -Se você instalou Typer CLI, você pode instalar _completion_ com: - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### Aplicações e documentação ao mesmo tempo - -Se você rodar os exemplos com, por exemplo: - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -como Uvicorn utiliza por padrão a porta `8000`, a documentação na porta `8008` não dará conflito. - -### Traduções - -Ajuda com traduções É MUITO apreciada! E essa tarefa não pode ser concluída sem a ajuda da comunidade. 🌎 🚀 - -Aqui estão os passos para ajudar com as traduções. - -#### Dicas e orientações - -* Verifique sempre os _pull requests_ existentes para a sua linguagem e faça revisões das alterações e aprove elas. - -/// tip - -Você pode adicionar comentários com sugestões de alterações para _pull requests_ existentes. - -Verifique as documentações sobre adicionar revisão ao _pull request_ para aprovação ou solicitação de alterações. - -/// - -* Verifique em _issues_ para ver se existe alguém coordenando traduções para a sua linguagem. - -* Adicione um único _pull request_ por página traduzida. Isso tornará muito mais fácil a revisão para as outras pessoas. - -Para as linguagens que eu não falo, vou esperar por várias pessoas revisarem a tradução antes de _mergear_. - -* Você pode verificar também se há traduções para sua linguagem e adicionar revisão para elas, isso irá me ajudar a saber que a tradução está correta e eu possa _mergear_. - -* Utilize os mesmos exemplos Python e somente traduza o texto na documentação. Você não tem que alterar nada no código para que funcione. - -* Utilize as mesmas imagens, nomes de arquivo e links. Você não tem que alterar nada disso para que funcione. - -* Para verificar o código de duas letras para a linguagem que você quer traduzir, você pode usar a Lista de códigos ISO 639-1. - -#### Linguagem existente - -Vamos dizer que você queira traduzir uma página para uma linguagem que já tenha traduções para algumas páginas, como o Espanhol. - -No caso do Espanhol, o código de duas letras é `es`. Então, o diretório para traduções em Espanhol está localizada em `docs/es/`. - -/// tip - -A principal ("oficial") linguagem é o Inglês, localizado em `docs/en/`. - -/// - -Agora rode o _servidor ao vivo_ para as documentações em Espanhol: - -
- -```console -// Use o comando "live" e passe o código da linguagem como um argumento de linha de comando -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Agora você pode ir em http://127.0.0.1:8008 e ver suas mudanças ao vivo. - -Se você procurar no site da documentação do FastAPI, você verá que toda linguagem tem todas as páginas. Mas algumas páginas não estão traduzidas e tem notificação sobre a falta da tradução. - -Mas quando você rodar localmente como descrito acima, você somente verá as páginas que já estão traduzidas. - -Agora vamos dizer que você queira adicionar uma tradução para a seção [Recursos](features.md){.internal-link target=_blank}. - -* Copie o arquivo em: - -``` -docs/en/docs/features.md -``` - -* Cole ele exatamente no mesmo local mas para a linguagem que você quer traduzir, por exemplo: - -``` -docs/es/docs/features.md -``` - -/// tip - -Observe que a única mudança na rota é o código da linguagem, de `en` para `es`. - -/// - -* Agora abra o arquivo de configuração MkDocs para Inglês em: - -``` -docs/en/docs/mkdocs.yml -``` - -* Procure o lugar onde `docs/features.md` está localizado no arquivo de configuração. Algum lugar como: - -```YAML hl_lines="8" -site_name: FastAPI -# Mais coisas -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -* Abra o arquivo de configuração MkDocs para a linguagem que você está editando, por exemplo: - -``` -docs/es/docs/mkdocs.yml -``` - -* Adicione no mesmo local que está no arquivo em Inglês, por exemplo: - -```YAML hl_lines="8" -site_name: FastAPI -# Mais coisas -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -Tenha certeza que se existem outras entradas, a nova entrada com sua tradução esteja exatamente na mesma ordem como na versão em Inglês. - -Se você for no seu navegador verá que agora a documentação mostra sua nova seção. 🎉 - -Agora você poderá traduzir tudo e ver como está toda vez que salva o arquivo. - -#### Nova linguagem - -Vamos dizer que você queira adicionar traduções para uma linguagem que ainda não foi traduzida, nem sequer uma página. - -Vamos dizer que você queira adicionar tradução para Haitiano, e ainda não tenha na documentação. - -Verificando o link acima, o código para "Haitiano" é `ht`. - -O próximo passo é rodar o _script_ para gerar um novo diretório de tradução: - -
- -```console -// Use o comando new-lang, passe o código da linguagem como um argumento de linha de comando -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -Updating ht -Updating en -``` - -
- -Agora você pode verificar em seu editor de código o mais novo diretório criado `docs/ht/`. - -/// tip - -Crie um primeiro _pull request_ com apenas isso, para iniciar a configuração da nova linguagem, antes de adicionar traduções. - -Desse modo outros poderão ajudar com outras páginas enquanto você trabalha na primeira. 🚀 - -/// - -Inicie traduzindo a página principal, `docs/ht/index.md`. - -Então você pode continuar com as instruções anteriores, para uma "Linguagem Existente". - -##### Nova linguagem não suportada - -Se quando rodar o _script_ do _servidor ao vivo_ você pega um erro sobre linguagem não suportada, alguma coisa como: - -``` - raise TemplateNotFound(template) -jinja2.exceptions.TemplateNotFound: partials/language/xx.html -``` - -Isso significa que o tema não suporta essa linguagem (nesse caso, com um código falso de duas letras `xx`). - -Mas não se preocupe, você pode configurar o tema de linguagem para Inglês e então traduzir o conteúdo da documentação. - -Se você precisar fazer isso, edite o `mkdocs.yml` para sua nova linguagem, teremos algo como: - -```YAML hl_lines="5" -site_name: FastAPI -# Mais coisas -theme: - # Mais coisas - language: xx -``` - -Altere essa linguagem de `xx` (do seu código de linguagem) para `en`. - -Então você poderá iniciar novamente o _servidor ao vivo_. - -#### Pré-visualize o resultado - -Quando você usa o _script_ em `./scripts/docs.py` com o comando `live` ele somente exibe os arquivos e traduções disponíveis para a linguagem atual. - -Mas uma vez que você tenha concluído, você poderá testar tudo como se parecesse _online_. - -Para fazer isso, primeiro construa toda a documentação: - -
- -```console -// Use o comando "build-all", isso leverá um tempinho -$ python ./scripts/docs.py build-all - -Updating es -Updating en -Building docs for: en -Building docs for: es -Successfully built docs for: es -Copying en index.md to README.md -``` - -
- -Isso gera toda a documentação em `./docs_build/` para cada linguagem. Isso inclui a adição de quaisquer arquivos com tradução faltando, com uma nota dizendo que "esse arquivo ainda não tem tradução". Mas você não tem que fazer nada com esse diretório. - -Então ele constrói todos aqueles _sites_ independentes MkDocs para cada linguagem, combina eles, e gera a saída final em `./site/`. - -Então você poderá "servir" eles com o comando `serve`: - -
- -```console -// Use o comando "serve" após rodar "build-all" -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -## Testes - -Tem um _script_ que você pode rodar localmente para testar todo o código e gerar relatórios de cobertura em HTML: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -Esse comando gera um diretório `./htmlcov/`, se você abrir o arquivo `./htmlcov/index.html` no seu navegador, poderá explorar interativamente as regiões de código que estão cobertas pelos testes, e observar se existe alguma região faltando. - -### Testes no seu editor - -Se você quer usar os testes integrados em seu editor adicione `./docs_src` na sua variável `PYTHONPATH`. - -Por exemplo, no VS Code você pode criar um arquivo `.env` com: - -```env -PYTHONPATH=./docs_src -``` diff --git a/docs/ru/docs/contributing.md b/docs/ru/docs/contributing.md deleted file mode 100644 index 67034ad03..000000000 --- a/docs/ru/docs/contributing.md +++ /dev/null @@ -1,496 +0,0 @@ -# Участие в разработке фреймворка - -Возможно, для начала Вам стоит ознакомиться с основными способами [помочь FastAPI или получить помощь](help-fastapi.md){.internal-link target=_blank}. - -## Разработка - -Если Вы уже склонировали репозиторий и знаете, что Вам нужно более глубокое погружение в код фреймворка, то здесь представлены некоторые инструкции по настройке виртуального окружения. - -### Виртуальное окружение с помощью `venv` - -Находясь в нужной директории, Вы можете создать виртуальное окружение при помощи Python модуля `venv`. - -
- -```console -$ python -m venv env -``` - -
- -Эта команда создаст директорию `./env/` с бинарными (двоичными) файлами Python, а затем Вы сможете скачивать и устанавливать необходимые библиотеки в изолированное виртуальное окружение. - -### Активация виртуального окружения - -Активируйте виртуально окружение командой: - -//// tab | Linux, macOS - -
- -```console -$ source ./env/bin/activate -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ .\env\Scripts\Activate.ps1 -``` - -
- -//// - -//// tab | Windows Bash - -Если Вы пользуетесь Bash для Windows (например: Git Bash): - -
- -```console -$ source ./env/Scripts/activate -``` - -
- -//// - -Проверьте, что всё сработало: - -//// tab | Linux, macOS, Windows Bash - -
- -```console -$ which pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ Get-Command pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -Если в терминале появится ответ, что бинарник `pip` расположен по пути `.../env/bin/pip`, значит всё в порядке. 🎉 - -Во избежание ошибок в дальнейших шагах, удостоверьтесь, что в Вашем виртуальном окружении установлена последняя версия `pip`: - -
- -```console -$ python -m pip install --upgrade pip - ----> 100% -``` - -
- -/// tip | Подсказка - -Каждый раз, перед установкой новой библиотеки в виртуальное окружение при помощи `pip`, не забудьте активировать это виртуальное окружение. - -Это гарантирует, что если Вы используете библиотеку, установленную этим пакетом, то Вы используете библиотеку из Вашего локального окружения, а не любую другую, которая может быть установлена глобально. - -/// - -### pip - -После активации виртуального окружения, как было указано ранее, введите следующую команду: - -
- -```console -$ pip install -r requirements.txt - ----> 100% -``` - -
- -Это установит все необходимые зависимости в локальное окружение для Вашего локального FastAPI. - -#### Использование локального FastAPI - -Если Вы создаёте Python файл, который импортирует и использует FastAPI,а затем запускаете его интерпретатором Python из Вашего локального окружения, то он будет использовать код из локального FastAPI. - -И, так как при вводе вышеупомянутой команды был указан флаг `-e`, если Вы измените код локального FastAPI, то при следующем запуске этого файла, он будет использовать свежую версию локального FastAPI, который Вы только что изменили. - -Таким образом, Вам не нужно "переустанавливать" Вашу локальную версию, чтобы протестировать каждое изменение. - -### Форматировние - -Скачанный репозиторий содержит скрипт, который может отформатировать и подчистить Ваш код: - -
- -```console -$ bash scripts/format.sh -``` - -
- -Заодно он упорядочит Ваши импорты. - -Чтобы он сортировал их правильно, необходимо, чтобы FastAPI был установлен локально в Вашей среде, с помощью команды из раздела выше, использующей флаг `-e`. - -## Документация - -Прежде всего, убедитесь, что Вы настроили своё окружение, как описано выше, для установки всех зависимостей. - -Документация использует MkDocs. - -Также существуют дополнительные инструменты/скрипты для работы с переводами в `./scripts/docs.py`. - -/// tip | Подсказка - -Нет необходимости заглядывать в `./scripts/docs.py`, просто используйте это в командной строке. - -/// - -Вся документация имеет формат Markdown и расположена в директории `./docs/en/`. - -Многие руководства содержат блоки кода. - -В большинстве случаев эти блоки кода представляют собой вполне законченные приложения, которые можно запускать как есть. - -На самом деле, эти блоки кода не написаны внутри Markdown, это Python файлы в директории `./docs_src/`. - -И эти Python файлы включаются/вводятся в документацию при создании сайта. - -### Тестирование документации - - -Фактически, большинство тестов запускаются с примерами исходных файлов в документации. - -Это помогает убедиться, что: - -* Документация находится в актуальном состоянии. -* Примеры из документации могут быть запущены как есть. -* Большинство функций описаны в документации и покрыты тестами. - -Существует скрипт, который во время локальной разработки создаёт сайт и проверяет наличие любых изменений, перезагружая его в реальном времени: - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Он запустит сайт документации по адресу: `http://127.0.0.1:8008`. - - -Таким образом, Вы сможете редактировать файлы с документацией или кодом и наблюдать изменения вживую. - -#### Typer CLI (опционально) - - -Приведенная ранее инструкция показала Вам, как запускать скрипт `./scripts/docs.py` непосредственно через интерпретатор `python` . - -Но также можно использовать Typer CLI, что позволит Вам воспользоваться автозаполнением команд в Вашем терминале. - -Если Вы установили Typer CLI, то для включения функции автозаполнения, введите эту команду: - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### Приложения и документация одновременно - -Если Вы запускаете приложение, например так: - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -По умолчанию Uvicorn будет использовать порт `8000` и не будет конфликтовать с сайтом документации, использующим порт `8008`. - -### Переводы на другие языки - -Помощь с переводами ценится КРАЙНЕ ВЫСОКО! И переводы не могут быть сделаны без помощи сообщества. 🌎 🚀 - -Ниже приведены шаги, как помочь с переводами. - -#### Подсказки и инструкции - -* Проверьте существующие пул-реквесты для Вашего языка. Добавьте отзывы с просьбой внести изменения, если они необходимы, или одобрите их. - -/// tip | Подсказка - -Вы можете добавлять комментарии с предложениями по изменению в существующие пул-реквесты. - -Ознакомьтесь с документацией о добавлении отзыва к пул-реквесту, чтобы утвердить его или запросить изменения. - -/// - -* Проверьте проблемы и вопросы, чтобы узнать, есть ли кто-то, координирующий переводы для Вашего языка. - -* Добавляйте один пул-реквест для каждой отдельной переведённой страницы. Это значительно облегчит другим его просмотр. - -Для языков, которые я не знаю, прежде чем добавить перевод в основную ветку, я подожду пока несколько других участников сообщества проверят его. - -* Вы также можете проверить, есть ли переводы для Вашего языка и добавить к ним отзыв, который поможет мне убедиться в правильности перевода. Тогда я смогу объединить его с основной веткой. - -* Используйте те же самые примеры кода Python. Переводите только текст документации. Вам не нужно ничего менять, чтобы эти примеры работали. - -* Используйте те же самые изображения, имена файлов и ссылки. Вы не должны менять ничего для сохранения работоспособности. - -* Чтобы узнать 2-буквенный код языка, на который Вы хотите сделать перевод, Вы можете воспользоваться таблицей Список кодов языков ISO 639-1. - -#### Существующий язык - -Допустим, Вы хотите перевести страницу на язык, на котором уже есть какие-то переводы, например, на испанский. - -Кодом испанского языка является `es`. А значит директория для переводов на испанский язык: `docs/es/`. - -/// tip | Подсказка - -Главный ("официальный") язык - английский, директория для него `docs/en/`. - -/// - -Вы можете запустить сервер документации на испанском: - -
- -```console -// Используйте команду "live" и передайте код языка в качестве аргумента командной строки -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Теперь Вы можете перейти по адресу: http://127.0.0.1:8008 и наблюдать вносимые Вами изменения вживую. - - -Если Вы посмотрите на сайт документации FastAPI, то увидите, что все страницы есть на каждом языке. Но некоторые страницы не переведены и имеют уведомление об отсутствующем переводе. - -Но когда Вы запускаете сайт локально, Вы видите только те страницы, которые уже переведены. - - -Предположим, что Вы хотите добавить перевод страницы [Основные свойства](features.md){.internal-link target=_blank}. - -* Скопируйте файл: - -``` -docs/en/docs/features.md -``` - -* Вставьте его точно в то же место, но в директорию языка, на который Вы хотите сделать перевод, например: - -``` -docs/es/docs/features.md -``` - -/// tip | Подсказка - -Заметьте, что в пути файла мы изменили только код языка с `en` на `es`. - -/// - -* Теперь откройте файл конфигурации MkDocs для английского языка, расположенный тут: - -``` -docs/en/mkdocs.yml -``` - -* Найдите в файле конфигурации место, где расположена строка `docs/features.md`. Похожее на это: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -* Откройте файл конфигурации MkDocs для языка, на который Вы переводите, например: - -``` -docs/es/mkdocs.yml -``` - -* Добавьте строку `docs/features.md` точно в то же место, как и в случае для английского, как-то так: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -Убедитесь, что при наличии других записей, новая запись с Вашим переводом находится точно в том же порядке, что и в английской версии. - -Если Вы зайдёте в свой браузер, то увидите, что в документации стал отображаться Ваш новый раздел.🎉 - -Теперь Вы можете переводить эту страницу и смотреть, как она выглядит при сохранении файла. - -#### Новый язык - -Допустим, Вы хотите добавить перевод для языка, на который пока что не переведена ни одна страница. - -Скажем, Вы решили сделать перевод для креольского языка, но его еще нет в документации. - -Перейдите в таблицу кодов языков по ссылке указанной выше, где найдёте, что кодом креольского языка является `ht`. - -Затем запустите скрипт, генерирующий директорию для переводов на новые языки: - -
- -```console -// Используйте команду new-lang и передайте код языка в качестве аргумента командной строки -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -Updating ht -Updating en -``` - -
- -После чего Вы можете проверить в своем редакторе кода, что появился новый каталог `docs/ht/`. - -/// tip | Подсказка - -Создайте первый пул-реквест, который будет содержать только пустую директорию для нового языка, прежде чем добавлять переводы. - -Таким образом, другие участники могут переводить другие страницы, пока Вы работаете над одной. 🚀 - -/// - -Начните перевод с главной страницы `docs/ht/index.md`. - -В дальнейшем можно действовать, как указано в предыдущих инструкциях для "существующего языка". - -##### Новый язык не поддерживается - -Если при запуске скрипта `./scripts/docs.py live` Вы получаете сообщение об ошибке, что язык не поддерживается, что-то вроде: - -``` - raise TemplateNotFound(template) -jinja2.exceptions.TemplateNotFound: partials/language/xx.html -``` - -Сие означает, что тема не поддерживает этот язык (в данном случае с поддельным 2-буквенным кодом `xx`). - -Но не стоит переживать. Вы можете установить языком темы английский, а затем перевести текст документации. - -Если возникла такая необходимость, отредактируйте `mkdocs.yml` для Вашего нового языка. Это будет выглядеть как-то так: - -```YAML hl_lines="5" -site_name: FastAPI -# More stuff -theme: - # More stuff - language: xx -``` - -Измените `xx` (код Вашего языка) на `en` и перезапустите сервер. - -#### Предпросмотр результата - -Когда Вы запускаете скрипт `./scripts/docs.py` с командой `live`, то будут показаны файлы и переводы для указанного языка. - -Но когда Вы закончите, то можете посмотреть, как это будет выглядеть по-настоящему. - -Для этого сначала создайте всю документацию: - -
- -```console -// Используйте команду "build-all", это займёт немного времени -$ python ./scripts/docs.py build-all - -Updating es -Updating en -Building docs for: en -Building docs for: es -Successfully built docs for: es -Copying en index.md to README.md -``` - -
- -Скрипт сгенерирует `./docs_build/` для каждого языка. Он добавит все файлы с отсутствующими переводами с пометкой о том, что "у этого файла еще нет перевода". Но Вам не нужно ничего делать с этим каталогом. - -Затем он создаст независимые сайты MkDocs для каждого языка, объединит их и сгенерирует конечный результат на `./site/`. - -После чего Вы сможете запустить сервер со всеми языками командой `serve`: - -
- -```console -// Используйте команду "serve" после того, как отработает команда "build-all" -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -## Тесты - -Также в репозитории есть скрипт, который Вы можете запустить локально, чтобы протестировать весь код и сгенерировать отчеты о покрытии тестами в HTML: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -Эта команда создаст директорию `./htmlcov/`, в которой будет файл `./htmlcov/index.html`. Открыв его в Вашем браузере, Вы можете в интерактивном режиме изучить, все ли части кода охвачены тестами. diff --git a/docs/zh/docs/contributing.md b/docs/zh/docs/contributing.md deleted file mode 100644 index cad093c2a..000000000 --- a/docs/zh/docs/contributing.md +++ /dev/null @@ -1,472 +0,0 @@ -# 开发 - 贡献 - -首先,你可能想了解 [帮助 FastAPI 及获取帮助](help-fastapi.md){.internal-link target=_blank}的基本方式。 - -## 开发 - -如果你已经克隆了源码仓库,并且需要深入研究代码,下面是设置开发环境的指南。 - -### 通过 `venv` 管理虚拟环境 - -你可以使用 Python 的 `venv` 模块在一个目录中创建虚拟环境: - -
- -```console -$ python -m venv env -``` - -
- -这将使用 Python 程序创建一个 `./env/` 目录,然后你将能够为这个隔离的环境安装软件包。 - -### 激活虚拟环境 - -使用以下方法激活新环境: - -//// tab | Linux, macOS - -
- -```console -$ source ./env/bin/activate -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ .\env\Scripts\Activate.ps1 -``` - -
- -//// - -//// tab | Windows Bash - -Or if you use Bash for Windows (e.g. Git Bash): - -
- -```console -$ source ./env/Scripts/activate -``` - -
- -//// - -要检查操作是否成功,运行: - -//// tab | Linux, macOS, Windows Bash - -
- -```console -$ which pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ Get-Command pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -如果显示 `pip` 程序文件位于 `env/bin/pip` 则说明激活成功。 🎉 - -确保虚拟环境中的 pip 版本是最新的,以避免后续步骤出现错误: - -
- -```console -$ python -m pip install --upgrade pip - ----> 100% -``` - -
- -/// tip - -每一次你在该环境下使用 `pip` 安装了新软件包时,请再次激活该环境。 - -这样可以确保你在使用由该软件包安装的终端程序时使用的是当前虚拟环境中的程序,而不是其他的可能是全局安装的程序。 - -/// - -### pip - -如上所述激活环境后: - -
- -```console -$ pip install -r requirements.txt - ----> 100% -``` - -
- -这将在虚拟环境中安装所有依赖和本地版本的 FastAPI。 - -#### 使用本地 FastAPI - -如果你创建一个导入并使用 FastAPI 的 Python 文件,然后使用虚拟环境中的 Python 运行它,它将使用你本地的 FastAPI 源码。 - -并且如果你更改该本地 FastAPI 的源码,由于它是通过 `-e` 安装的,当你再次运行那个 Python 文件,它将使用你刚刚编辑过的最新版本的 FastAPI。 - -这样,你不必再去重新"安装"你的本地版本即可测试所有更改。 - -/// note | 技术细节 - -仅当你使用此项目中的 `requirements.txt` 安装而不是直接使用 `pip install fastapi` 安装时,才会发生这种情况。 - -这是因为在 `requirements.txt` 中,本地的 FastAPI 是使用“可编辑” (`-e`)选项安装的 - -/// - -### 格式化 - -你可以运行下面的脚本来格式化和清理所有代码: - -
- -```console -$ bash scripts/format.sh -``` - -
- -它还会自动对所有导入代码进行排序整理。 - -为了使整理正确进行,你需要在当前环境中安装本地的 FastAPI,即在运行上述段落中的命令时添加 `-e`。 - -## 文档 - -首先,请确保按上述步骤设置好环境,这将安装所有需要的依赖。 - -### 实时文档 - -在本地开发时,可以使用该脚本构建站点并检查所做的任何更改,并实时重载: - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -文档服务将运行在 `http://127.0.0.1:8008`。 - -这样,你可以编辑文档 / 源文件并实时查看更改。 - -/// tip - -或者你也可以手动执行和该脚本一样的操作 - -进入语言目录,如果是英文文档,目录则是 `docs/en/`: - -```console -$ cd docs/en/ -``` - -在该目录执行 `mkdocs` 命令 - -```console -$ mkdocs serve --dev-addr 8008 -``` - -/// - -#### Typer CLI (可选) - -本指引向你展示了如何直接用 `python` 运行 `./scripts/docs.py` 中的脚本。 - -但你也可以使用 Typer CLI,而且在安装了补全功能后,你将可以在终端中对命令进行自动补全。 - -如果你已经安装 Typer CLI ,则可以使用以下命令安装自动补全功能: - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### 文档架构 - -文档使用 MkDocs 生成。 - -在 `./scripts/docs.py` 中还有额外工具 / 脚本来处理翻译。 - -/// tip - -你不需要去了解 `./scripts/docs.py` 中的代码,只需在命令行中使用它即可。 - -/// - -所有文档均在 `./docs/en/` 目录中以 Markdown 文件格式保存。 - -许多的教程中都有一些代码块,大多数情况下,这些代码是可以直接运行的,因为这些代码不是写在 Markdown 文件里的,而是写在 `./docs_src/` 目录中的 Python 文件里。 - -在生成站点的时候,这些 Python 文件会被打包进文档中。 - -### 测试文档 - -大多数的测试实际上都是针对文档中的示例源文件运行的。 - -这有助于确保: - -* 文档始终是最新的。 -* 文档示例可以直接运行。 -* 绝大多数特性既在文档中得以阐述,又通过测试覆盖进行保障。 - - -### 应用和文档同时运行 - -如果你使用以下方式运行示例程序: - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -由于 Uvicorn 默认使用 `8000` 端口 ,因此运行在 `8008` 端口上的文档不会与之冲突。 - -### 翻译 - -**非常感谢**你能够参与文档的翻译!这项工作需要社区的帮助才能完成。 🌎 🚀 - -以下是参与帮助翻译的步骤。 - -#### 建议和指南 - -* 在当前 已有的 pull requests 中查找你使用的语言,添加要求修改或同意合并的评审意见。 - -/// tip - -你可以为已有的 pull requests 添加包含修改建议的评论。 - -详情可查看关于 添加 pull request 评审意见 以同意合并或要求修改的文档。 - -/// - -* 检查在 GitHub Discussion 是否有关于你所用语言的协作翻译。 如果有,你可以订阅它,当有一条新的 PR 请求需要评审时,系统会自动将其添加到讨论中,你也会收到对应的推送。 - -* 每翻译一个页面新增一个 pull request。这将使其他人更容易对其进行评审。 - -对于我(译注:作者使用西班牙语和英语)不懂的语言,我将在等待其他人评审翻译之后将其合并。 - -* 你还可以查看是否有你所用语言的翻译,并对其进行评审,这将帮助我了解翻译是否正确以及能否将其合并。 - * 可以在 GitHub Discussions 中查看。 - * 也可以在现有 PR 中通过你使用的语言标签来筛选对应的 PR,举个例子,对于西班牙语,标签是 `lang-es`。 - -* 请使用相同的 Python 示例,且只需翻译文档中的文本,不用修改其它东西。 - -* 请使用相同的图片、文件名以及链接地址,不用修改其它东西。 - -* 你可以从 ISO 639-1 代码列表 表中查找你想要翻译语言的两位字母代码。 - -#### 已有的语言 - -假设你想将某个页面翻译成已经翻译了一些页面的语言,例如西班牙语。 - -对于西班牙语来说,它的两位字母代码是 `es`。所以西班牙语翻译的目录位于 `docs/es/`。 - -/// tip - -默认语言是英语,位于 `docs/en/`目录。 - -/// - -现在为西班牙语文档运行实时服务器: - -
- -```console -// Use the command "live" and pass the language code as a CLI argument -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -/// tip - -或者你也可以手动执行和该脚本一样的操作 - -进入语言目录,对于西班牙语的翻译,目录是 `docs/es/`: - -```console -$ cd docs/es/ -``` - -在该目录执行 `mkdocs` 命令 - -```console -$ mkdocs serve --dev-addr 8008 -``` - -/// - -现在你可以访问 http://127.0.0.1:8008 实时查看你所做的更改。 - -如果你查看 FastAPI 的线上文档网站,会看到每种语言都有所有的文档页面,但是某些页面并未被翻译并且会有一处关于缺少翻译的提示。(但是当你像上面这样在本地运行文档时,你只会看到已经翻译的页面。) - -现在假设你要为 [Features](features.md){.internal-link target=_blank} 章节添加翻译。 - -* 复制下面的文件: - -``` -docs/en/docs/features.md -``` - -* 粘贴到你想要翻译语言目录的相同位置,比如: - -``` -docs/es/docs/features.md -``` - -/// tip - -注意路径和文件名的唯一变化是语言代码,从 `en` 更改为 `es`。 - -/// - -回到浏览器你就可以看到刚刚更新的章节了。🎉 - -现在,你可以翻译这些内容并在保存文件后进行预览。 - -#### 新语言 - -假设你想要为尚未有任何页面被翻译的语言添加翻译。 - -假设你想要添加克里奥尔语翻译,而且文档中还没有该语言的翻译。 - -点击上面提到的“ISO 639-1 代码列表”链接,可以查到“克里奥尔语”的代码为 `ht`。 - -下一步是运行脚本以生成新的翻译目录: - -
- -```console -// Use the command new-lang, pass the language code as a CLI argument -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -``` - -
- -现在,你可以在编辑器中查看新创建的目录 `docs/ht/`。 - -这条命令会生成一个从 `en` 版本继承了所有属性的配置文件 `docs/ht/mkdocs.yml`: - -```yaml -INHERIT: ../en/mkdocs.yml -``` - -/// tip - -你也可以自己手动创建包含这些内容的文件。 - -/// - -这条命令还会生成一个文档主页 `docs/ht/index.md`,你可以从这个文件开始翻译。 - -然后,你可以根据上面的"已有语言"的指引继续进行翻译。 - -翻译完成后,你就可以用 `docs/ht/mkdocs.yml` 和 `docs/ht/index.md` 发起 PR 了。🎉 - -#### 预览结果 - -你可以执行 `./scripts/docs.py live` 命令来预览结果(或者 `mkdocs serve`)。 - -但是当你完成翻译后,你可以像在线上展示一样测试所有内容,包括所有其他语言。 - -为此,首先构建所有文档: - -
- -```console -// Use the command "build-all", this will take a bit -$ python ./scripts/docs.py build-all - -Building docs for: en -Building docs for: es -Successfully built docs for: es -``` - -
- -这样会对每一种语言构建一个独立的文档站点,并最终把这些站点全部打包输出到 `./site/` 目录。 - - - -然后你可以使用命令 `serve` 来运行生成的站点: - -
- -```console -// Use the command "serve" after running "build-all" -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -## 测试 - -你可以在本地运行下面的脚本来测试所有代码并生成 HTML 格式的覆盖率报告: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -该命令生成了一个 `./htmlcov/` 目录,如果你在浏览器中打开 `./htmlcov/index.html` 文件,你可以交互式地浏览被测试所覆盖的代码区块,并注意是否缺少了任何区块。 diff --git a/scripts/docs.py b/scripts/docs.py index f26f96d85..8462e2bc1 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -35,6 +35,7 @@ non_translated_sections = [ "newsletter.md", "management-tasks.md", "management.md", + "contributing.md", ] docs_path = Path("docs") From 6cd050ceb64fa637dc3fc02a98d6b2a71a4cd465 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 10 Nov 2024 17:12:44 +0000 Subject: [PATCH 432/932] =?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 [skip ci] --- 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 8224856e2..0a67e0419 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update `contributing.md` docs, include note to not translate this page. PR [#12841](https://github.com/fastapi/fastapi/pull/12841) by [@tiangolo](https://github.com/tiangolo). * 📝 Update includes in `docs/en/docs/tutorial/request-forms.md`. PR [#12648](https://github.com/fastapi/fastapi/pull/12648) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes in `docs/en/docs/tutorial/request-form-models.md`. PR [#12649](https://github.com/fastapi/fastapi/pull/12649) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes in `docs/en/docs/tutorial/security/oauth2-jwt.md`. PR [#12650](https://github.com/fastapi/fastapi/pull/12650) by [@OCE1960](https://github.com/OCE1960). From 8f5ec897f7999dcd1e811e9406d69770c27d30b4 Mon Sep 17 00:00:00 2001 From: Zhaohan Dong <65422392+zhaohan-dong@users.noreply.github.com> Date: Sun, 10 Nov 2024 17:19:19 +0000 Subject: [PATCH 433/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/tutorial/header-param-models.md`=20(#12814)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Zhaohan Dong <65422392+zhaohan-dong@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/en/docs/tutorial/header-param-models.md | 132 +------------------ 1 file changed, 2 insertions(+), 130 deletions(-) diff --git a/docs/en/docs/tutorial/header-param-models.md b/docs/en/docs/tutorial/header-param-models.md index 78517e498..73950a668 100644 --- a/docs/en/docs/tutorial/header-param-models.md +++ b/docs/en/docs/tutorial/header-param-models.md @@ -14,71 +14,7 @@ This is supported since FastAPI version `0.115.0`. 🤓 Declare the **header parameters** that you need in a **Pydantic model**, and then declare the parameter as `Header`: -//// tab | Python 3.10+ - -```Python hl_lines="9-14 18" -{!> ../../docs_src/header_param_models/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-14 18" -{!> ../../docs_src/header_param_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10-15 19" -{!> ../../docs_src/header_param_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7-12 16" -{!> ../../docs_src/header_param_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9-14 18" -{!> ../../docs_src/header_param_models/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7-12 16" -{!> ../../docs_src/header_param_models/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *} **FastAPI** will **extract** the data for **each field** from the **headers** in the request and give you the Pydantic model you defined. @@ -96,71 +32,7 @@ In some special use cases (probably not very common), you might want to **restri You can use Pydantic's model configuration to `forbid` any `extra` fields: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/header_param_models/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/header_param_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/header_param_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/header_param_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/header_param_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/header_param_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/header_param_models/tutorial002_an_py310.py hl[10] *} If a client tries to send some **extra headers**, they will receive an **error** response. From cb53c5b9185415c5a62182c11f88b87d281c1506 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 10 Nov 2024 17:19:41 +0000 Subject: [PATCH 434/932] =?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 [skip ci] --- 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 0a67e0419..8df60f080 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/header-param-models.md`. PR [#12814](https://github.com/fastapi/fastapi/pull/12814) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update `contributing.md` docs, include note to not translate this page. PR [#12841](https://github.com/fastapi/fastapi/pull/12841) by [@tiangolo](https://github.com/tiangolo). * 📝 Update includes in `docs/en/docs/tutorial/request-forms.md`. PR [#12648](https://github.com/fastapi/fastapi/pull/12648) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes in `docs/en/docs/tutorial/request-form-models.md`. PR [#12649](https://github.com/fastapi/fastapi/pull/12649) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). From bfaf4c303fbf67fe6361277586bc432e13a0ea7d Mon Sep 17 00:00:00 2001 From: David Caro Date: Sun, 10 Nov 2024 18:23:38 +0100 Subject: [PATCH 435/932] =?UTF-8?q?=F0=9F=93=9D=20Remove=20mention=20of=20?= =?UTF-8?q?Celery=20in=20the=20project=20generators=20(#12742)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: David Caro Co-authored-by: Sebastián Ramírez --- docs/de/docs/tutorial/background-tasks.md | 2 -- docs/em/docs/tutorial/background-tasks.md | 2 -- docs/en/docs/tutorial/background-tasks.md | 2 -- docs/fr/docs/tutorial/background-tasks.md | 2 -- docs/ja/docs/tutorial/background-tasks.md | 2 -- docs/ko/docs/tutorial/background-tasks.md | 2 -- docs/pt/docs/tutorial/background-tasks.md | 2 -- docs/ru/docs/tutorial/background-tasks.md | 2 -- docs/zh/docs/tutorial/background-tasks.md | 2 -- 9 files changed, 18 deletions(-) diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md index d40b6d4fb..fc699daf4 100644 --- a/docs/de/docs/tutorial/background-tasks.md +++ b/docs/de/docs/tutorial/background-tasks.md @@ -133,8 +133,6 @@ Wenn Sie umfangreiche Hintergrundberechnungen durchführen müssen und diese nic Sie erfordern in der Regel komplexere Konfigurationen und einen Nachrichten-/Job-Queue-Manager wie RabbitMQ oder Redis, ermöglichen Ihnen jedoch die Ausführung von Hintergrundtasks in mehreren Prozessen und insbesondere auf mehreren Servern. -Um ein Beispiel zu sehen, sehen Sie sich die [Projektgeneratoren](../project-generation.md){.internal-link target=_blank} an. Sie alle enthalten Celery, bereits konfiguriert. - Wenn Sie jedoch über dieselbe **FastAPI**-Anwendung auf Variablen und Objekte zugreifen oder kleine Hintergrundtasks ausführen müssen (z. B. das Senden einer E-Mail-Benachrichtigung), können Sie einfach `BackgroundTasks` verwenden. ## Zusammenfassung diff --git a/docs/em/docs/tutorial/background-tasks.md b/docs/em/docs/tutorial/background-tasks.md index 0f4585ebe..6b14c6135 100644 --- a/docs/em/docs/tutorial/background-tasks.md +++ b/docs/em/docs/tutorial/background-tasks.md @@ -97,8 +97,6 @@ 👫 😑 🚚 🌖 🏗 📳, 📧/👨‍🏭 📤 👨‍💼, 💖 ✳ ⚖️ ✳, ✋️ 👫 ✔ 👆 🏃 🖥 📋 💗 🛠️, & ✴️, 💗 💽. -👀 🖼, ✅ [🏗 🚂](../project-generation.md){.internal-link target=_blank}, 👫 🌐 🔌 🥒 ⏪ 📶. - ✋️ 🚥 👆 💪 🔐 🔢 & 🎚 ⚪️➡️ 🎏 **FastAPI** 📱, ⚖️ 👆 💪 🎭 🤪 🖥 📋 (💖 📨 📧 📨), 👆 💪 🎯 ⚙️ `BackgroundTasks`. ## 🌃 diff --git a/docs/en/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md index 92427e36e..34685fcc4 100644 --- a/docs/en/docs/tutorial/background-tasks.md +++ b/docs/en/docs/tutorial/background-tasks.md @@ -79,8 +79,6 @@ If you need to perform heavy background computation and you don't necessarily ne They tend to require more complex configurations, a message/job queue manager, like RabbitMQ or Redis, but they allow you to run background tasks in multiple processes, and especially, in multiple servers. -To see an example, check the [Project Generators](../project-generation.md){.internal-link target=_blank}, they all include Celery already configured. - But if you need to access variables and objects from the same **FastAPI** app, or you need to perform small background tasks (like sending an email notification), you can simply just use `BackgroundTasks`. ## Recap diff --git a/docs/fr/docs/tutorial/background-tasks.md b/docs/fr/docs/tutorial/background-tasks.md index e14d5a8e8..2065ca58e 100644 --- a/docs/fr/docs/tutorial/background-tasks.md +++ b/docs/fr/docs/tutorial/background-tasks.md @@ -77,8 +77,6 @@ Si vous avez besoin de réaliser des traitements lourds en tâche d'arrière-pla Ces outils nécessitent généralement des configurations plus complexes ainsi qu'un gestionnaire de queue de message, comme RabbitMQ ou Redis, mais ils permettent d'exécuter des tâches d'arrière-plan dans différents process, et potentiellement, sur plusieurs serveurs. -Pour voir un exemple, allez voir les [Générateurs de projets](../project-generation.md){.internal-link target=_blank}, ils incluent tous Celery déjà configuré. - Mais si vous avez besoin d'accéder aux variables et objets de la même application **FastAPI**, ou si vous avez besoin d'effectuer de petites tâches d'arrière-plan (comme envoyer des notifications par email), vous pouvez simplement vous contenter d'utiliser `BackgroundTasks`. ## Résumé diff --git a/docs/ja/docs/tutorial/background-tasks.md b/docs/ja/docs/tutorial/background-tasks.md index 6f9340817..8a4bc161c 100644 --- a/docs/ja/docs/tutorial/background-tasks.md +++ b/docs/ja/docs/tutorial/background-tasks.md @@ -85,8 +85,6 @@ これらは、より複雑な構成、RabbitMQ や Redis などのメッセージ/ジョブキューマネージャーを必要とする傾向がありますが、複数のプロセス、特に複数のサーバーでバックグラウンドタスクを実行できます。 -例を確認するには、[Project Generators](../project-generation.md){.internal-link target=_blank} を参照してください。これらにはすべて、Celery が構築済みです。 - ただし、同じ **FastAPI** アプリから変数とオブジェクトにアクセスする必要がある場合、または小さなバックグラウンドタスク (電子メール通知の送信など) を実行する必要がある場合は、単に `BackgroundTasks` を使用できます。 ## まとめ diff --git a/docs/ko/docs/tutorial/background-tasks.md b/docs/ko/docs/tutorial/background-tasks.md index 376c52524..27f265608 100644 --- a/docs/ko/docs/tutorial/background-tasks.md +++ b/docs/ko/docs/tutorial/background-tasks.md @@ -97,8 +97,6 @@ FastAPI에서 `BackgroundTask`를 단독으로 사용하는 것은 여전히 가 RabbitMQ 또는 Redis와 같은 메시지/작업 큐 시스템 보다 복잡한 구성이 필요한 경향이 있지만, 여러 작업 프로세스를 특히 여러 서버의 백그라운드에서 실행할 수 있습니다. -예제를 보시려면 [프로젝트 생성기](../project-generation.md){.internal-link target=\_blank} 를 참고하세요. 해당 예제에는 이미 구성된 `Celery`가 포함되어 있습니다. - 그러나 동일한 FastAPI 앱에서 변수 및 개체에 접근해야햐는 작은 백그라운드 수행이 필요한 경우 (예 : 알림 이메일 보내기) 간단하게 `BackgroundTasks`를 사용해보세요. ## 요약 diff --git a/docs/pt/docs/tutorial/background-tasks.md b/docs/pt/docs/tutorial/background-tasks.md index 6a69ae2af..0f3796371 100644 --- a/docs/pt/docs/tutorial/background-tasks.md +++ b/docs/pt/docs/tutorial/background-tasks.md @@ -77,8 +77,6 @@ Se você precisa realizar cálculos pesados ​​em segundo plano e não necess Eles tendem a exigir configurações mais complexas, um gerenciador de fila de mensagens/tarefas, como RabbitMQ ou Redis, mas permitem que você execute tarefas em segundo plano em vários processos e, especialmente, em vários servidores. -Para ver um exemplo, verifique os [Geradores de projeto](../project-generation.md){.internal-link target=\_blank}, todos incluem celery já configurado. - Mas se você precisa acessar variáveis ​​e objetos do mesmo aplicativo **FastAPI**, ou precisa realizar pequenas tarefas em segundo plano (como enviar uma notificação por e-mail), você pode simplesmente usar `BackgroundTasks`. ## Recapitulando diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md index 0f6ce0eb3..a4f98f643 100644 --- a/docs/ru/docs/tutorial/background-tasks.md +++ b/docs/ru/docs/tutorial/background-tasks.md @@ -97,8 +97,6 @@ Их тяжелее настраивать, также им нужен брокер сообщений наподобие RabbitMQ или Redis, но зато они позволяют вам запускать фоновые задачи в нескольких процессах и даже на нескольких серверах. -Для примера, посмотрите [Project Generators](../project-generation.md){.internal-link target=_blank}, там есть проект с уже настроенным Celery. - Но если вам нужен доступ к общим переменным и объектам вашего **FastAPI** приложения или вам нужно выполнять простые фоновые задачи (наподобие отправки письма из примера) вы можете просто использовать `BackgroundTasks`. ## Резюме diff --git a/docs/zh/docs/tutorial/background-tasks.md b/docs/zh/docs/tutorial/background-tasks.md index 80622e129..40e61add7 100644 --- a/docs/zh/docs/tutorial/background-tasks.md +++ b/docs/zh/docs/tutorial/background-tasks.md @@ -117,8 +117,6 @@ 它们往往需要更复杂的配置,即消息/作业队列管理器,如RabbitMQ或Redis,但它们允许您在多个进程中运行后台任务,甚至是在多个服务器中。 -要查看示例,查阅 [Project Generators](../project-generation.md){.internal-link target=_blank},它们都包括已经配置的Celery。 - 但是,如果您需要从同一个**FastAPI**应用程序访问变量和对象,或者您需要执行小型后台任务(如发送电子邮件通知),您只需使用 `BackgroundTasks` 即可。 ## 回顾 From bfeecfc8c1b2e19317807b2f813ea6f3d6025f67 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 10 Nov 2024 17:23:59 +0000 Subject: [PATCH 436/932] =?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 [skip ci] --- 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 8df60f080..e089d63d8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Remove mention of Celery in the project generators. PR [#12742](https://github.com/fastapi/fastapi/pull/12742) by [@david-caro](https://github.com/david-caro). * 📝 Update includes in `docs/en/docs/tutorial/header-param-models.md`. PR [#12814](https://github.com/fastapi/fastapi/pull/12814) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update `contributing.md` docs, include note to not translate this page. PR [#12841](https://github.com/fastapi/fastapi/pull/12841) by [@tiangolo](https://github.com/tiangolo). * 📝 Update includes in `docs/en/docs/tutorial/request-forms.md`. PR [#12648](https://github.com/fastapi/fastapi/pull/12648) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). From be516b0d2c8b85269ffc5ac6d93ffb16998879bc Mon Sep 17 00:00:00 2001 From: davioc <14282722+davioc@users.noreply.github.com> Date: Sun, 10 Nov 2024 09:26:01 -0800 Subject: [PATCH 437/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/tutorial/body-updates.md`=20(#12712)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/tutorial/body-updates.md | 96 ++------------------------- 1 file changed, 4 insertions(+), 92 deletions(-) diff --git a/docs/en/docs/tutorial/body-updates.md b/docs/en/docs/tutorial/body-updates.md index 3ac2e3914..df5b960db 100644 --- a/docs/en/docs/tutorial/body-updates.md +++ b/docs/en/docs/tutorial/body-updates.md @@ -6,29 +6,7 @@ To update an item you can use the ../../docs_src/body_updates/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *} `PUT` is used to receive data that should replace the existing data. @@ -84,29 +62,7 @@ That would generate a `dict` with only the data that was set when creating the ` Then you can use this to generate a `dict` with only the data that was set (sent in the request), omitting default values: -//// tab | Python 3.10+ - -```Python hl_lines="32" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *} ### Using Pydantic's `update` parameter @@ -122,29 +78,7 @@ The examples here use `.copy()` for compatibility with Pydantic v1, but you shou Like `stored_item_model.model_copy(update=update_data)`: -//// tab | Python 3.10+ - -```Python hl_lines="33" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *} ### Partial updates recap @@ -161,29 +95,7 @@ In summary, to apply partial updates you would: * Save the data to your DB. * Return the updated model. -//// tab | Python 3.10+ - -```Python hl_lines="28-35" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *} /// tip From 725fd1633435cf2d0ad0db20c2144ff229d1fe98 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 10 Nov 2024 17:26:22 +0000 Subject: [PATCH 438/932] =?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 [skip ci] --- 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 e089d63d8..84477593d 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/tutorial/body-updates.md`. PR [#12712](https://github.com/fastapi/fastapi/pull/12712) by [@davioc](https://github.com/davioc). * 📝 Remove mention of Celery in the project generators. PR [#12742](https://github.com/fastapi/fastapi/pull/12742) by [@david-caro](https://github.com/david-caro). * 📝 Update includes in `docs/en/docs/tutorial/header-param-models.md`. PR [#12814](https://github.com/fastapi/fastapi/pull/12814) by [@zhaohan-dong](https://github.com/zhaohan-dong). * 📝 Update `contributing.md` docs, include note to not translate this page. PR [#12841](https://github.com/fastapi/fastapi/pull/12841) by [@tiangolo](https://github.com/tiangolo). From 3829bdc4a5c5b2658007fe8e90aa3b976c4eec53 Mon Sep 17 00:00:00 2001 From: VISHNU V S <84698110+vishnuvskvkl@users.noreply.github.com> Date: Sun, 10 Nov 2024 22:57:25 +0530 Subject: [PATCH 439/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/tutorial/dependencies/global-dependencies.md`?= =?UTF-8?q?=20(#12653)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- .../dependencies/global-dependencies.md | 29 +------------------ 1 file changed, 1 insertion(+), 28 deletions(-) diff --git a/docs/en/docs/tutorial/dependencies/global-dependencies.md b/docs/en/docs/tutorial/dependencies/global-dependencies.md index 21a8cb6be..e4696ee14 100644 --- a/docs/en/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/global-dependencies.md @@ -6,35 +6,8 @@ Similar to the way you can [add `dependencies` to the *path operation decorators In that case, they will be applied to all the *path operations* in the application: -//// tab | Python 3.9+ +{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[16] *} -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/dependencies/tutorial012.py!} -``` - -//// And all the ideas in the section about [adding `dependencies` to the *path operation decorators*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} still apply, but in this case, to all of the *path operations* in the app. From b32f612162ae998f5027ea9e322f6b4ac4857e3f Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 10 Nov 2024 17:28:13 +0000 Subject: [PATCH 440/932] =?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 [skip ci] --- 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 84477593d..d65b835b9 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/tutorial/dependencies/global-dependencies.md`. PR [#12653](https://github.com/fastapi/fastapi/pull/12653) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes for `docs/en/docs/tutorial/body-updates.md`. PR [#12712](https://github.com/fastapi/fastapi/pull/12712) by [@davioc](https://github.com/davioc). * 📝 Remove mention of Celery in the project generators. PR [#12742](https://github.com/fastapi/fastapi/pull/12742) by [@david-caro](https://github.com/david-caro). * 📝 Update includes in `docs/en/docs/tutorial/header-param-models.md`. PR [#12814](https://github.com/fastapi/fastapi/pull/12814) by [@zhaohan-dong](https://github.com/zhaohan-dong). From 9aaeb8b0573494608440236efc43088dc57fa9ea Mon Sep 17 00:00:00 2001 From: xuvjso Date: Mon, 11 Nov 2024 01:36:46 +0800 Subject: [PATCH 441/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20`docs/en/docs/t?= =?UTF-8?q?utorial/dependencies/dependencies-with-yield.md`=20(#12045)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/tutorial/dependencies/dependencies-with-yield.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md index 430b7a73f..70b5945a4 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md @@ -39,7 +39,7 @@ The yielded value is what is injected into *path operations* and other dependenc {!../../docs_src/dependencies/tutorial007.py!} ``` -The code following the `yield` statement is executed after the response has been delivered: +The code following the `yield` statement is executed after creating the response but before sending it: ```Python hl_lines="5-6" {!../../docs_src/dependencies/tutorial007.py!} From f93a29542c34982f11be1efaa2c41fdb0ae17c3e Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 10 Nov 2024 17:37:08 +0000 Subject: [PATCH 442/932] =?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 [skip ci] --- 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 d65b835b9..6ac90aa43 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update `docs/en/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#12045](https://github.com/fastapi/fastapi/pull/12045) by [@xuvjso](https://github.com/xuvjso). * 📝 Update includes for `docs/en/docs/tutorial/dependencies/global-dependencies.md`. PR [#12653](https://github.com/fastapi/fastapi/pull/12653) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes for `docs/en/docs/tutorial/body-updates.md`. PR [#12712](https://github.com/fastapi/fastapi/pull/12712) by [@davioc](https://github.com/davioc). * 📝 Remove mention of Celery in the project generators. PR [#12742](https://github.com/fastapi/fastapi/pull/12742) by [@david-caro](https://github.com/david-caro). From 694f6ccf0ddc14dd7282ec9d0f78c8347dad9157 Mon Sep 17 00:00:00 2001 From: Nimitha J <58389915+Nimitha-jagadeesha@users.noreply.github.com> Date: Sun, 10 Nov 2024 23:08:49 +0530 Subject: [PATCH 443/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/tutorial/metadata.md`=20(#12773)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/tutorial/metadata.md | 24 ++++++------------------ 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/docs/en/docs/tutorial/metadata.md b/docs/en/docs/tutorial/metadata.md index 715bb999a..6bd48caaf 100644 --- a/docs/en/docs/tutorial/metadata.md +++ b/docs/en/docs/tutorial/metadata.md @@ -18,9 +18,7 @@ You can set the following fields that are used in the OpenAPI specification and You can set them as follows: -```Python hl_lines="3-16 19-32" -{!../../docs_src/metadata/tutorial001.py!} -``` +{* ../../docs_src/metadata/tutorial001.py hl[3:16, 19:32] *} /// tip @@ -38,9 +36,7 @@ Since OpenAPI 3.1.0 and FastAPI 0.99.0, you can also set the `license_info` with For example: -```Python hl_lines="31" -{!../../docs_src/metadata/tutorial001_1.py!} -``` +{* ../../docs_src/metadata/tutorial001_1.py hl[31] *} ## Metadata for tags @@ -62,9 +58,7 @@ Let's try that in an example with tags for `users` and `items`. Create metadata for your tags and pass it to the `openapi_tags` parameter: -```Python hl_lines="3-16 18" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} Notice that you can use Markdown inside of the descriptions, for example "login" will be shown in bold (**login**) and "fancy" will be shown in italics (_fancy_). @@ -78,9 +72,7 @@ You don't have to add metadata for all the tags that you use. Use the `tags` parameter with your *path operations* (and `APIRouter`s) to assign them to different tags: -```Python hl_lines="21 26" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} /// info @@ -108,9 +100,7 @@ But you can configure it with the parameter `openapi_url`. For example, to set it to be served at `/api/v1/openapi.json`: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial002.py!} -``` +{* ../../docs_src/metadata/tutorial002.py hl[3] *} If you want to disable the OpenAPI schema completely you can set `openapi_url=None`, that will also disable the documentation user interfaces that use it. @@ -127,6 +117,4 @@ You can configure the two documentation user interfaces included: For example, to set Swagger UI to be served at `/documentation` and disable ReDoc: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial003.py!} -``` +{* ../../docs_src/metadata/tutorial003.py hl[3] *} From 9467000ad2b1fa462b4091ac97f4836cd16a471f Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 10 Nov 2024 17:39:14 +0000 Subject: [PATCH 444/932] =?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 [skip ci] --- 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 6ac90aa43..71547bb84 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/tutorial/metadata.md`. PR [#12773](https://github.com/fastapi/fastapi/pull/12773) by [@Nimitha-jagadeesha](https://github.com/Nimitha-jagadeesha). * 📝 Update `docs/en/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#12045](https://github.com/fastapi/fastapi/pull/12045) by [@xuvjso](https://github.com/xuvjso). * 📝 Update includes for `docs/en/docs/tutorial/dependencies/global-dependencies.md`. PR [#12653](https://github.com/fastapi/fastapi/pull/12653) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). * 📝 Update includes for `docs/en/docs/tutorial/body-updates.md`. PR [#12712](https://github.com/fastapi/fastapi/pull/12712) by [@davioc](https://github.com/davioc). From 13892a39cd5ab34ab7c461372d053461d96f7297 Mon Sep 17 00:00:00 2001 From: AyushSinghal1794 <89984761+AyushSinghal1794@users.noreply.github.com> Date: Sun, 10 Nov 2024 23:10:22 +0530 Subject: [PATCH 445/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/en/docs/advanced/testing-dependencies.md`=20(#12647)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/advanced/testing-dependencies.md | 52 +------------------ 1 file changed, 1 insertion(+), 51 deletions(-) diff --git a/docs/en/docs/advanced/testing-dependencies.md b/docs/en/docs/advanced/testing-dependencies.md index 1cc4313a1..17b4f9814 100644 --- a/docs/en/docs/advanced/testing-dependencies.md +++ b/docs/en/docs/advanced/testing-dependencies.md @@ -28,57 +28,7 @@ To override a dependency for testing, you put as a key the original dependency ( And then **FastAPI** will call that override instead of the original dependency. -//// tab | Python 3.10+ - -```Python hl_lines="26-27 30" -{!> ../../docs_src/dependency_testing/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="28-29 32" -{!> ../../docs_src/dependency_testing/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="29-30 33" -{!> ../../docs_src/dependency_testing/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="24-25 28" -{!> ../../docs_src/dependency_testing/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="28-29 32" -{!> ../../docs_src/dependency_testing/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependency_testing/tutorial001_an_py310.py hl[26:27,30] *} /// tip From 5a48c37056397e47ab164ba4430807aa6fc9a710 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 10 Nov 2024 17:41:44 +0000 Subject: [PATCH 446/932] =?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 [skip ci] --- 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 71547bb84..63af296a9 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/testing-dependencies.md`. PR [#12647](https://github.com/fastapi/fastapi/pull/12647) by [@AyushSinghal1794](https://github.com/AyushSinghal1794). * 📝 Update includes for `docs/en/docs/tutorial/metadata.md`. PR [#12773](https://github.com/fastapi/fastapi/pull/12773) by [@Nimitha-jagadeesha](https://github.com/Nimitha-jagadeesha). * 📝 Update `docs/en/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#12045](https://github.com/fastapi/fastapi/pull/12045) by [@xuvjso](https://github.com/xuvjso). * 📝 Update includes for `docs/en/docs/tutorial/dependencies/global-dependencies.md`. PR [#12653](https://github.com/fastapi/fastapi/pull/12653) by [@vishnuvskvkl](https://github.com/vishnuvskvkl). From 20809a175a983b91caa8d373167bfba829d4c106 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 11 Nov 2024 18:29:56 +0000 Subject: [PATCH 447/932] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#12907)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index d90e7281e..3869328a7 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.7.2 + rev: v0.7.3 hooks: - id: ruff args: From 88cc900c8392ff48a56852dfe6483ad2a1548f5c Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 11 Nov 2024 18:30:19 +0000 Subject: [PATCH 448/932] =?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 [skip ci] --- 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 63af296a9..7efdc57a0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -121,6 +121,7 @@ hide: ### Internal +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12907](https://github.com/fastapi/fastapi/pull/12907) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 🔨 Update docs preview script to show previous version and English version. PR [#12856](https://github.com/fastapi/fastapi/pull/12856) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump tiangolo/latest-changes from 0.3.1 to 0.3.2. PR [#12794](https://github.com/fastapi/fastapi/pull/12794) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pypa/gh-action-pypi-publish from 1.12.0 to 1.12.2. PR [#12788](https://github.com/fastapi/fastapi/pull/12788) by [@dependabot[bot]](https://github.com/apps/dependabot). From c1781066be39014364414fecfc537302f17364ea Mon Sep 17 00:00:00 2001 From: Gaurav Sheni Date: Tue, 12 Nov 2024 11:09:34 -0500 Subject: [PATCH 449/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/en/docs/tutorial/body.md`=20(#12757)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/tutorial/body.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md index 9c97f64cb..aba5593a5 100644 --- a/docs/en/docs/tutorial/body.md +++ b/docs/en/docs/tutorial/body.md @@ -126,7 +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: -{!> ../../docs_src/body/tutorial002_py310.py!} +{* ../../docs_src/body/tutorial002_py310.py *} ## Request body + path parameters From f71649082390d46605f6d359a2d8bd2c9fc4ed6d Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 12 Nov 2024 16:09:58 +0000 Subject: [PATCH 450/932] =?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 [skip ci] --- 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 7efdc57a0..01e8770cf 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/tutorial/body.md`. PR [#12757](https://github.com/fastapi/fastapi/pull/12757) by [@gsheni](https://github.com/gsheni). * 📝 Update includes in `docs/en/docs/advanced/testing-dependencies.md`. PR [#12647](https://github.com/fastapi/fastapi/pull/12647) by [@AyushSinghal1794](https://github.com/AyushSinghal1794). * 📝 Update includes for `docs/en/docs/tutorial/metadata.md`. PR [#12773](https://github.com/fastapi/fastapi/pull/12773) by [@Nimitha-jagadeesha](https://github.com/Nimitha-jagadeesha). * 📝 Update `docs/en/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#12045](https://github.com/fastapi/fastapi/pull/12045) by [@xuvjso](https://github.com/xuvjso). From 91a929319c4ccaa4569d55edcc52ae774b685eda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 12 Nov 2024 17:10:42 +0100 Subject: [PATCH 451/932] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Update=20internal?= =?UTF-8?q?=20checks=20to=20support=20Pydantic=202.10=20(#12914)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/_compat.py | 3 ++- fastapi/params.py | 10 +++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/fastapi/_compat.py b/fastapi/_compat.py index 56c5d744e..2b4d3e725 100644 --- a/fastapi/_compat.py +++ b/fastapi/_compat.py @@ -27,7 +27,8 @@ from typing_extensions import Annotated, Literal, get_args, get_origin # Reassign variable to make it reexported for mypy PYDANTIC_VERSION = P_VERSION -PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") +PYDANTIC_VERSION_MINOR_TUPLE = tuple(int(x) for x in PYDANTIC_VERSION.split(".")[:2]) +PYDANTIC_V2 = PYDANTIC_VERSION_MINOR_TUPLE[0] == 2 sequence_annotation_to_type = { diff --git a/fastapi/params.py b/fastapi/params.py index 90ca7cb01..8f5601dd3 100644 --- a/fastapi/params.py +++ b/fastapi/params.py @@ -6,7 +6,11 @@ from fastapi.openapi.models import Example from pydantic.fields import FieldInfo from typing_extensions import Annotated, deprecated -from ._compat import PYDANTIC_V2, PYDANTIC_VERSION, Undefined +from ._compat import ( + PYDANTIC_V2, + PYDANTIC_VERSION_MINOR_TUPLE, + Undefined, +) _Unset: Any = Undefined @@ -105,7 +109,7 @@ class Param(FieldInfo): stacklevel=4, ) current_json_schema_extra = json_schema_extra or extra - if PYDANTIC_VERSION < "2.7.0": + if PYDANTIC_VERSION_MINOR_TUPLE < (2, 7): self.deprecated = deprecated else: kwargs["deprecated"] = deprecated @@ -561,7 +565,7 @@ class Body(FieldInfo): stacklevel=4, ) current_json_schema_extra = json_schema_extra or extra - if PYDANTIC_VERSION < "2.7.0": + if PYDANTIC_VERSION_MINOR_TUPLE < (2, 7): self.deprecated = deprecated else: kwargs["deprecated"] = deprecated From c6f021ecc2a0e68979efd9fbc192369bf3f790ce Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 12 Nov 2024 16:12:19 +0000 Subject: [PATCH 452/932] =?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 [skip ci] --- 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 01e8770cf..6222ecbfa 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Refactors + +* ♻️ Update internal checks to support Pydantic 2.10. PR [#12914](https://github.com/fastapi/fastapi/pull/12914) by [@tiangolo](https://github.com/tiangolo). + ### Docs * 📝 Update includes for `docs/en/docs/tutorial/body.md`. PR [#12757](https://github.com/fastapi/fastapi/pull/12757) by [@gsheni](https://github.com/gsheni). From f057f4a0679255a01d79a96f259bc7e6ad2327e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 12 Nov 2024 17:14:23 +0100 Subject: [PATCH 453/932] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?5.5?= 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 6222ecbfa..436c07a7e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.115.5 + ### Refactors * ♻️ Update internal checks to support Pydantic 2.10. PR [#12914](https://github.com/fastapi/fastapi/pull/12914) by [@tiangolo](https://github.com/tiangolo). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 51e3ca510..12faea987 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.4" +__version__ = "0.115.5" from starlette import status as status From b81c635a11eba38ca9fa936aa6e07ffa32fef4f2 Mon Sep 17 00:00:00 2001 From: Alissa <96190409+alissadb@users.noreply.github.com> Date: Tue, 12 Nov 2024 20:56:10 +0100 Subject: [PATCH 454/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/de/docs/how-to/conditional-openapi.md`=20(#12689)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: alissa-debruijn Co-authored-by: Sebastián Ramírez --- docs/de/docs/how-to/conditional-openapi.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/de/docs/how-to/conditional-openapi.md b/docs/de/docs/how-to/conditional-openapi.md index a0a4983bb..50ae11f90 100644 --- a/docs/de/docs/how-to/conditional-openapi.md +++ b/docs/de/docs/how-to/conditional-openapi.md @@ -29,9 +29,7 @@ Sie können problemlos dieselben Pydantic-Einstellungen verwenden, um Ihre gener Zum Beispiel: -```Python hl_lines="6 11" -{!../../docs_src/conditional_openapi/tutorial001.py!} -``` +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} Hier deklarieren wir die Einstellung `openapi_url` mit dem gleichen Defaultwert `"/openapi.json"`. From 75aa13d007b76a74a58f8744ae52f14e5e4bf941 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 12 Nov 2024 19:56:38 +0000 Subject: [PATCH 455/932] =?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 [skip ci] --- 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 436c07a7e..b4398b477 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 for `docs/de/docs/how-to/conditional-openapi.md`. PR [#12689](https://github.com/fastapi/fastapi/pull/12689) by [@alissadb](https://github.com/alissadb). + ## 0.115.5 ### Refactors From 1f27f41499ab665d5e59c33faebfa6fc94154334 Mon Sep 17 00:00:00 2001 From: Alissa <96190409+alissadb@users.noreply.github.com> Date: Tue, 12 Nov 2024 20:57:07 +0100 Subject: [PATCH 456/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20for?= =?UTF-8?q?=20`docs/de/docs/advanced/using-request-directly.md`=20(#12685)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: alissa-debruijn Co-authored-by: Sebastián Ramírez --- docs/de/docs/advanced/using-request-directly.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/de/docs/advanced/using-request-directly.md b/docs/de/docs/advanced/using-request-directly.md index 1c2a6f852..a0a5ec1ab 100644 --- a/docs/de/docs/advanced/using-request-directly.md +++ b/docs/de/docs/advanced/using-request-directly.md @@ -29,9 +29,7 @@ Angenommen, Sie möchten auf die IP-Adresse/den Host des Clients in Ihrer *Pfado Dazu müssen Sie direkt auf den Request zugreifen. -```Python hl_lines="1 7-8" -{!../../docs_src/using_request_directly/tutorial001.py!} -``` +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} Durch die Deklaration eines *Pfadoperation-Funktionsparameters*, dessen Typ der `Request` ist, weiß **FastAPI**, dass es den `Request` diesem Parameter übergeben soll. From 1cfea408c0e7b516f6526682dc5c4cc938c9d62f Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 12 Nov 2024 19:58:49 +0000 Subject: [PATCH 457/932] =?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 [skip ci] --- 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 b4398b477..c58c4abc8 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/de/docs/advanced/using-request-directly.md`. PR [#12685](https://github.com/fastapi/fastapi/pull/12685) by [@alissadb](https://github.com/alissadb). * 📝 Update includes for `docs/de/docs/how-to/conditional-openapi.md`. PR [#12689](https://github.com/fastapi/fastapi/pull/12689) by [@alissadb](https://github.com/alissadb). ## 0.115.5 From 602e9531584135f31fea0a8e68ae96eab2436a7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 17 Nov 2024 23:31:41 +0100 Subject: [PATCH 458/932] =?UTF-8?q?=F0=9F=94=A5=20Remove=20obsolete=20tuto?= =?UTF-8?q?rial=20translation=20to=20Chinese=20for=20`docs/zh/docs/tutoria?= =?UTF-8?q?l/sql-databases.md`,=20it=20references=20files=20that=20are=20n?= =?UTF-8?q?o=20longer=20on=20the=20repo=20(#12949)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/sql-databases.md | 908 ------------------------- 1 file changed, 908 deletions(-) delete mode 100644 docs/zh/docs/tutorial/sql-databases.md diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md deleted file mode 100644 index 06b373e6d..000000000 --- a/docs/zh/docs/tutorial/sql-databases.md +++ /dev/null @@ -1,908 +0,0 @@ -# SQL (关系型) 数据库 - -/// info - -这些文档即将被更新。🎉 - -当前版本假设Pydantic v1和SQLAlchemy版本小于2。 - -新的文档将包括Pydantic v2以及 SQLModel(也是基于SQLAlchemy),一旦SQLModel更新为为使用Pydantic v2。 - -/// - -**FastAPI**不需要你使用SQL(关系型)数据库。 - -但是您可以使用任何您想要的关系型数据库。 - -在这里,让我们看一个使用着[SQLAlchemy](https://www.sqlalchemy.org/)的示例。 - -您可以很容易地将其调整为任何SQLAlchemy支持的数据库,如: - -* PostgreSQL -* MySQL -* SQLite -* Oracle -* Microsoft SQL Server,等等其它数据库 - -在此示例中,我们将使用**SQLite**,因为它使用单个文件并且 在Python中具有集成支持。因此,您可以复制此示例并按原样来运行它。 - -稍后,对于您的产品级别的应用程序,您可能会要使用像**PostgreSQL**这样的数据库服务器。 - -/// tip - -这儿有一个**FastAPI**和**PostgreSQL**的官方项目生成器,全部基于**Docker**,包括前端和更多工具:https://github.com/tiangolo/full-stack-fastapi-postgresql - -/// - -/// note - -请注意,大部分代码是`SQLAlchemy`的标准代码,您可以用于任何框架。FastAPI特定的代码和往常一样少。 - -/// - -## ORMs(对象关系映射) - -**FastAPI**可与任何数据库在任何样式的库中一起与 数据库进行通信。 - -一种常见的模式是使用“ORM”:对象关系映射。 - -ORM 具有在代码和数据库表(“*关系型”)中的**对象**之间转换(“*映射*”)的工具。 - -使用 ORM,您通常会在 SQL 数据库中创建一个代表映射的类,该类的每个属性代表一个列,具有名称和类型。 - -例如,一个类`Pet`可以表示一个 SQL 表`pets`。 - -该类的每个*实例对象都代表数据库中的一行数据。* - -又例如,一个对象`orion_cat`(`Pet`的一个实例)可以有一个属性`orion_cat.type`, 对标数据库中的`type`列。并且该属性的值可以是其它,例如`"cat"`。 - -这些 ORM 还具有在表或实体之间建立关系的工具(比如创建多表关系)。 - -这样,您还可以拥有一个属性`orion_cat.owner`,它包含该宠物所有者的数据,这些数据取自另外一个表。 - -因此,`orion_cat.owner.name`可能是该宠物主人的姓名(来自表`owners`中的列`name`)。 - -它可能有一个像`"Arquilian"`(一种业务逻辑)。 - -当您尝试从您的宠物对象访问它时,ORM 将完成所有工作以从相应的表*所有者那里再获取信息。* - -常见的 ORM 例如:Django-ORM(Django 框架的一部分)、SQLAlchemy ORM(SQLAlchemy 的一部分,独立于框架)和 Peewee(独立于框架)等。 - -在这里,我们将看到如何使用**SQLAlchemy ORM**。 - -以类似的方式,您也可以使用任何其他 ORM。 - -/// tip - -在文档中也有一篇使用 Peewee 的等效的文章。 - -/// - -## 文件结构 - -对于这些示例,假设您有一个名为的目录`my_super_project`,其中包含一个名为的子目录`sql_app`,其结构如下: - -``` -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - └── schemas.py -``` - -该文件`__init__.py`只是一个空文件,但它告诉 Python `sql_app` 是一个包。 - -现在让我们看看每个文件/模块的作用。 - -## 安装 SQLAlchemy - -首先你需要安装`SQLAlchemy`: - -
- -```console -$ pip install sqlalchemy - ----> 100% -``` - -
- -## 创建 SQLAlchemy 部件 - -让我们转到文件`sql_app/database.py`。 - -### 导入 SQLAlchemy 部件 - -```Python hl_lines="1-3" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -### 为 SQLAlchemy 定义数据库 URL地址 - -```Python hl_lines="5-6" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -在这个例子中,我们正在“连接”到一个 SQLite 数据库(用 SQLite 数据库打开一个文件)。 - -该文件将位于文件中的同一目录中`sql_app.db`。 - -这就是为什么最后一部分是`./sql_app.db`. - -如果您使用的是**PostgreSQL**数据库,则只需取消注释该行: - -```Python -SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" -``` - -...并根据您的数据库数据和相关凭据(也适用于 MySQL、MariaDB 或任何其他)对其进行调整。 - -/// tip - -如果您想使用不同的数据库,这是就是您必须修改的地方。 - -/// - -### 创建 SQLAlchemy 引擎 - -第一步,创建一个 SQLAlchemy的“引擎”。 - -我们稍后会将这个`engine`在其他地方使用。 - -```Python hl_lines="8-10" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -#### 注意 - -参数: - -```Python -connect_args={"check_same_thread": False} -``` - -...仅用于`SQLite`,在其他数据库不需要它。 - -/// info | 技术细节 - -默认情况下,SQLite 只允许一个线程与其通信,假设有多个线程的话,也只将处理一个独立的请求。 - -这是为了防止意外地为不同的事物(不同的请求)共享相同的连接。 - -但是在 FastAPI 中,使用普通函数(def)时,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。 - -此外,我们将确保每个请求都在依赖项中获得自己的数据库连接会话,因此不需要该默认机制。 - -/// - -### 创建一个`SessionLocal`类 - -每个`SessionLocal`类的实例都会是一个数据库会话。当然该类本身还不是数据库会话。 - -但是一旦我们创建了一个`SessionLocal`类的实例,这个实例将是实际的数据库会话。 - -我们将它命名为`SessionLocal`是为了将它与我们从 SQLAlchemy 导入的`Session`区别开来。 - -稍后我们将使用`Session`(从 SQLAlchemy 导入的那个)。 - -要创建`SessionLocal`类,请使用函数`sessionmaker`: - -```Python hl_lines="11" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -### 创建一个`Base`类 - -现在我们将使用`declarative_base()`返回一个类。 - -稍后我们将继承这个类,来创建每个数据库模型或类(ORM 模型): - -```Python hl_lines="13" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -## 创建数据库模型 - -现在让我们看看文件`sql_app/models.py`。 - -### 用`Base`类来创建 SQLAlchemy 模型 - -我们将使用我们之前创建的`Base`类来创建 SQLAlchemy 模型。 - -/// tip - -SQLAlchemy 使用的“**模型**”这个术语 来指代与数据库交互的这些类和实例。 - -而 Pydantic 也使用“模型”这个术语 来指代不同的东西,即数据验证、转换以及文档类和实例。 - -/// - -从`database`(来自上面的`database.py`文件)导入`Base`。 - -创建从它继承的类。 - -这些类就是 SQLAlchemy 模型。 - -```Python hl_lines="4 7-8 18-19" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -这个`__tablename__`属性是用来告诉 SQLAlchemy 要在数据库中为每个模型使用的数据库表的名称。 - -### 创建模型属性/列 - -现在创建所有模型(类)的属性。 - -这些属性中的每一个都代表其相应数据库表中的一列。 - -我们使用`Column`来表示 SQLAlchemy 中的默认值。 - -我们传递一个 SQLAlchemy “类型”,如`Integer`、`String`和`Boolean`,它定义了数据库中的类型,作为参数。 - -```Python hl_lines="1 10-13 21-24" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -### 创建关系 - -现在创建关系。 - -为此,我们使用SQLAlchemy ORM提供的`relationship`。 - -这将或多或少会成为一种“神奇”属性,其中表示该表与其他相关的表中的值。 - -```Python hl_lines="2 15 26" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -当访问 user 中的属性`items`时,如 中`my_user.items`,它将有一个`Item`SQLAlchemy 模型列表(来自`items`表),这些模型具有指向`users`表中此记录的外键。 - -当您访问`my_user.items`时,SQLAlchemy 实际上会从`items`表中的获取一批记录并在此处填充进去。 - -同样,当访问 Item中的属性`owner`时,它将包含表中的`User`SQLAlchemy 模型`users`。使用`owner_id`属性/列及其外键来了解要从`users`表中获取哪条记录。 - -## 创建 Pydantic 模型 - -现在让我们查看一下文件`sql_app/schemas.py`。 - -/// tip - -为了避免 SQLAlchemy*模型*和 Pydantic*模型*之间的混淆,我们将有`models.py`(SQLAlchemy 模型的文件)和`schemas.py`( Pydantic 模型的文件)。 - -这些 Pydantic 模型或多或少地定义了一个“schema”(一个有效的数据形状)。 - -因此,这将帮助我们在使用两者时避免混淆。 - -/// - -### 创建初始 Pydantic*模型*/模式 - -创建一个`ItemBase`和`UserBase`Pydantic*模型*(或者我们说“schema”),他们拥有创建或读取数据时具有的共同属性。 - -然后创建一个继承自他们的`ItemCreate`和`UserCreate`,并添加创建时所需的其他数据(或属性)。 - -因此在创建时也应当有一个`password`属性。 - -但是为了安全起见,`password`不会出现在其他同类 Pydantic*模型*中,例如通过API读取一个用户数据时,它不应当包含在内。 - -//// tab | Python 3.10+ - -```Python hl_lines="1 4-6 9-10 21-22 25-26" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -#### SQLAlchemy 风格和 Pydantic 风格 - -请注意,SQLAlchemy*模型*使用 `=`来定义属性,并将类型作为参数传递给`Column`,例如: - -```Python -name = Column(String) -``` - -虽然 Pydantic*模型*使用`:` 声明类型,但新的类型注释语法/类型提示是: - -```Python -name: str -``` - -请牢记这一点,这样您在使用`:`还是`=`时就不会感到困惑。 - -### 创建用于读取/返回的Pydantic*模型/模式* - -现在创建当从 API 返回数据时、将在读取数据时使用的Pydantic*模型(schemas)。* - -例如,在创建一个项目之前,我们不知道分配给它的 ID 是什么,但是在读取它时(从 API 返回时)我们已经知道它的 ID。 - -同样,当读取用户时,我们现在可以声明`items`,将包含属于该用户的项目。 - -不仅是这些项目的 ID,还有我们在 Pydantic*模型*中定义的用于读取项目的所有数据:`Item`. - -//// tab | Python 3.10+ - -```Python hl_lines="13-15 29-32" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="15-17 31-34" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15-17 31-34" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -/// tip - -请注意,读取用户(从 API 返回)时将使用不包括`password`的`User` Pydantic*模型*。 - -/// - -### 使用 Pydantic 的`orm_mode` - -现在,在用于查询的 Pydantic*模型*`Item`中`User`,添加一个内部`Config`类。 - -此类[`Config`](https://docs.pydantic.dev/latest/api/config/)用于为 Pydantic 提供配置。 - -在`Config`类中,设置属性`orm_mode = True`。 - -//// tab | Python 3.10+ - -```Python hl_lines="13 17-18 29 34-35" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="15 19-20 31 36-37" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15 19-20 31 36-37" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -/// tip - -请注意,它使用`=`分配一个值,例如: - -`orm_mode = True` - -它不使用之前的`:`来类型声明。 - -这是设置配置值,而不是声明类型。 - -/// - -Pydantic`orm_mode`将告诉 Pydantic*模型*读取数据,即它不是一个`dict`,而是一个 ORM 模型(或任何其他具有属性的任意对象)。 - -这样,而不是仅仅试图从`dict`上 `id` 中获取值,如下所示: - -```Python -id = data["id"] -``` - -它还会尝试从属性中获取它,如: - -```Python -id = data.id -``` - -有了这个,Pydantic*模型*与 ORM 兼容,您只需在*路径操作*`response_model`的参数中声明它即可。 - -您将能够返回一个数据库模型,它将从中读取数据。 - -#### ORM 模式的技术细节 - -SQLAlchemy 和许多其他默认情况下是“延迟加载”。 - -这意味着,例如,除非您尝试访问包含该数据的属性,否则它们不会从数据库中获取关系数据。 - -例如,访问属性`items`: - -```Python -current_user.items -``` - -将使 SQLAlchemy 转到`items`表并获取该用户的项目,在调用`.items`之前不会去查询数据库。 - -没有`orm_mode`,如果您从*路径操作*返回一个 SQLAlchemy 模型,它不会包含关系数据。 - -即使您在 Pydantic 模型中声明了这些关系,也没有用处。 - -但是在 ORM 模式下,由于 Pydantic 本身会尝试从属性访问它需要的数据(而不是假设为 `dict`),你可以声明你想要返回的特定数据,它甚至可以从 ORM 中获取它。 - -## CRUD工具 - -现在让我们看看文件`sql_app/crud.py`。 - -在这个文件中,我们将编写可重用的函数用来与数据库中的数据进行交互。 - -**CRUD**分别为:增加(**C**reate)、查询(**R**ead)、更改(**U**pdate)、删除(**D**elete),即增删改查。 - -...虽然在这个例子中我们只是新增和查询。 - -### 读取数据 - -从 `sqlalchemy.orm`中导入`Session`,这将允许您声明`db`参数的类型,并在您的函数中进行更好的类型检查和完成。 - -导入之前的`models`(SQLAlchemy 模型)和`schemas`(Pydantic*模型*/模式)。 - -创建一些工具函数来完成: - -* 通过 ID 和电子邮件查询单个用户。 -* 查询多个用户。 -* 查询多个项目。 - -```Python hl_lines="1 3 6-7 10-11 14-15 27-28" -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` - -/// tip - -通过创建仅专用于与数据库交互(获取用户或项目)的函数,独立于*路径操作函数*,您可以更轻松地在多个部分中重用它们,并为它们添加单元测试。 - -/// - -### 创建数据 - -现在创建工具函数来创建数据。 - -它的步骤是: - -* 使用您的数据创建一个 SQLAlchemy 模型*实例。* -* 使用`add`来将该实例对象添加到数据库会话。 -* 使用`commit`来将更改提交到数据库(以便保存它们)。 -* 使用`refresh`来刷新您的实例对象(以便它包含来自数据库的任何新数据,例如生成的 ID)。 - -```Python hl_lines="18-24 31-36" -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` - -/// tip - -SQLAlchemy 模型`User`包含一个`hashed_password`,它应该是一个包含散列的安全密码。 - -但由于 API 客户端提供的是原始密码,因此您需要将其提取并在应用程序中生成散列密码。 - -然后将hashed_password参数与要保存的值一起传递。 - -/// - -/// warning - -此示例不安全,密码未经过哈希处理。 - -在现实生活中的应用程序中,您需要对密码进行哈希处理,并且永远不要以明文形式保存它们。 - -有关更多详细信息,请返回教程中的安全部分。 - -在这里,我们只关注数据库的工具和机制。 - -/// - -/// tip - -这里不是将每个关键字参数传递给Item并从Pydantic模型中读取每个参数,而是先生成一个字典,其中包含Pydantic模型的数据: - -`item.dict()` - -然后我们将dict的键值对 作为关键字参数传递给 SQLAlchemy `Item`: - -`Item(**item.dict())` - -然后我们传递 Pydantic模型未提供的额外关键字参数`owner_id`: - -`Item(**item.dict(), owner_id=user_id)` - -/// - -## 主**FastAPI**应用程序 - -现在在`sql_app/main.py`文件中 让我们集成和使用我们之前创建的所有其他部分。 - -### 创建数据库表 - -以非常简单的方式创建数据库表: - -//// tab | Python 3.9+ - -```Python hl_lines="7" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -#### Alembic 注意 - -通常你可能会使用 Alembic,来进行格式化数据库(创建表等)。 - -而且您还可以将 Alembic 用于“迁移”(这是它的主要工作)。 - -“迁移”是每当您更改 SQLAlchemy 模型的结构、添加新属性等以在数据库中复制这些更改、添加新列、新表等时所需的一组步骤。 - -您可以在[Full Stack FastAPI Template](https://fastapi.tiangolo.com/zh/project-generation/)的模板中找到一个 FastAPI 项目中的 Alembic 示例。具体在[`alembic`代码目录中](https://github.com/tiangolo/full-stack-fastapi-template/tree/master/backend/app/alembic)。 - -### 创建依赖项 - -现在使用我们在`sql_app/database.py`文件中创建的`SessionLocal`来创建依赖项。 - -我们需要每个请求有一个独立的数据库会话/连接(`SessionLocal`),在整个请求中使用相同的会话,然后在请求完成后关闭它。 - -然后将为下一个请求创建一个新会话。 - -为此,我们将创建一个包含`yield`的依赖项,正如前面关于[Dependencies with`yield`](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/)的部分中所解释的那样。 - -我们的依赖项将创建一个新的 SQLAlchemy `SessionLocal`,它将在单个请求中使用,然后在请求完成后关闭它。 - -//// tab | Python 3.9+ - -```Python hl_lines="13-18" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15-20" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -/// info - -我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。 - -然后我们在finally块中关闭它。 - -通过这种方式,我们确保数据库会话在请求后始终关闭。即使在处理请求时出现异常。 - -但是您不能从退出代码中引发另一个异常(在yield之后)。可以查阅 [Dependencies with yield and HTTPException](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception) - -/// - -*然后,当在路径操作函数*中使用依赖项时,我们使用`Session`,直接从 SQLAlchemy 导入的类型声明它。 - -*这将为我们在路径操作函数*中提供更好的编辑器支持,因为编辑器将知道`db`参数的类型`Session`: - -//// tab | Python 3.9+ - -```Python hl_lines="22 30 36 45 51" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24 32 38 47 53" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -/// info | 技术细节 - -参数`db`实际上是 type `SessionLocal`,但是这个类(用 创建`sessionmaker()`)是 SQLAlchemy 的“代理” `Session`,所以,编辑器并不真正知道提供了哪些方法。 - -但是通过将类型声明为Session,编辑器现在可以知道可用的方法(.add()、.query()、.commit()等)并且可以提供更好的支持(比如完成)。类型声明不影响实际对象。 - -/// - -### 创建您的**FastAPI** *路径操作* - -现在,到了最后,编写标准的**FastAPI** *路径操作*代码。 - -//// tab | Python 3.9+ - -```Python hl_lines="21-26 29-32 35-40 43-47 50-53" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23-28 31-34 37-42 45-49 52-55" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -我们在依赖项中的每个请求之前利用`yield`创建数据库会话,然后关闭它。 - -所以我们就可以在*路径操作函数*中创建需要的依赖,就能直接获取会话。 - -这样,我们就可以直接从*路径操作函数*内部调用`crud.get_user`并使用该会话,来进行对数据库操作。 - -/// tip - -请注意,您返回的值是 SQLAlchemy 模型或 SQLAlchemy 模型列表。 - -但是由于所有路径操作的response_model都使用 Pydantic模型/使用orm_mode模式,因此您的 Pydantic 模型中声明的数据将从它们中提取并返回给客户端,并进行所有正常的过滤和验证。 - -/// - -/// tip - -另请注意,`response_models`应当是标准 Python 类型,例如`List[schemas.Item]`. - -但是由于它的内容/参数List是一个 使用orm_mode模式的Pydantic模型,所以数据将被正常检索并返回给客户端,所以没有问题。 - -/// - -### 关于 `def` 对比 `async def` - -*在这里,我们在路径操作函数*和依赖项中都使用着 SQLAlchemy 模型,它将与外部数据库进行通信。 - -这会需要一些“等待时间”。 - -但是由于 SQLAlchemy 不具有`await`直接使用的兼容性,因此类似于: - -```Python -user = await db.query(User).first() -``` - -...相反,我们可以使用: - -```Python -user = db.query(User).first() -``` - -然后我们应该声明*路径操作函数*和不带 的依赖关系`async def`,只需使用普通的`def`,如下: - -```Python hl_lines="2" -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - ... -``` - -/// info - -如果您需要异步连接到关系数据库,请参阅[Async SQL (Relational) Databases](https://fastapi.tiangolo.com/zh/advanced/async-sql-databases/) - -/// - -/// note | Very Technical Details - -如果您很好奇并且拥有深厚的技术知识,您可以在[Async](https://fastapi.tiangolo.com/zh/async/#very-technical-details)文档中查看有关如何处理 `async def`于`def`差别的技术细节。 - -/// - -## 迁移 - -因为我们直接使用 SQLAlchemy,并且我们不需要任何类型的插件来使用**FastAPI**,所以我们可以直接将数据库迁移至[Alembic](https://alembic.sqlalchemy.org/)进行集成。 - -由于与 SQLAlchemy 和 SQLAlchemy 模型相关的代码位于单独的独立文件中,您甚至可以使用 Alembic 执行迁移,而无需安装 FastAPI、Pydantic 或其他任何东西。 - -同样,您将能够在与**FastAPI**无关的代码的其他部分中使用相同的 SQLAlchemy 模型和实用程序。 - -例如,在具有[Celery](https://docs.celeryq.dev/)、[RQ](https://python-rq.org/)或[ARQ](https://arq-docs.helpmanual.io/)的后台任务工作者中。 - -## 审查所有文件 - -最后回顾整个案例,您应该有一个名为的目录`my_super_project`,其中包含一个名为`sql_app`。 - -`sql_app`中应该有以下文件: - -* `sql_app/__init__.py`:这是一个空文件。 - -* `sql_app/database.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -* `sql_app/models.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -* `sql_app/schemas.py`: - -//// tab | Python 3.10+ - -```Python -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -* `sql_app/crud.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` - -* `sql_app/main.py`: - -//// tab | Python 3.9+ - -```Python -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -## 执行项目 - -您可以复制这些代码并按原样使用它。 - -/// info - -事实上,这里的代码只是大多数测试代码的一部分。 - -/// - -你可以用 Uvicorn 运行它: - - -
- -```console -$ uvicorn sql_app.main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -打开浏览器进入 http://127.0.0.1:8000/docs。 - -您将能够与您的**FastAPI**应用程序交互,从真实数据库中读取数据: - - - -## 直接与数据库交互 - -如果您想独立于 FastAPI 直接浏览 SQLite 数据库(文件)以调试其内容、添加表、列、记录、修改数据等,您可以使用[SQLite 的 DB Browser](https://sqlitebrowser.org/) - -它看起来像这样: - - - -您还可以使用[SQLite Viewer](https://inloop.github.io/sqlite-viewer/)或[ExtendsClass](https://extendsclass.com/sqlite-browser.html)等在线 SQLite 浏览器。 - -## 中间件替代数据库会话 - -如果你不能使用带有`yield`的依赖项——例如,如果你没有使用**Python 3.7**并且不能安装上面提到的**Python 3.6**的“backports” ——你可以使用类似的方法在“中间件”中设置会话。 - -“中间件”基本上是一个对每个请求都执行的函数,其中一些代码在端点函数之前执行,另一些代码在端点函数之后执行。 - -### 创建中间件 - -我们要添加的中间件(只是一个函数)将为每个请求创建一个新的 SQLAlchemy`SessionLocal`,将其添加到请求中,然后在请求完成后关闭它。 - -//// tab | Python 3.9+ - -```Python hl_lines="12-20" -{!> ../../docs_src/sql_databases/sql_app_py39/alt_main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14-22" -{!> ../../docs_src/sql_databases/sql_app/alt_main.py!} -``` - -//// - -/// info - -我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。 - -然后我们在finally块中关闭它。 - -通过这种方式,我们确保数据库会话在请求后始终关闭,即使在处理请求时出现异常也会关闭。 - -/// - -### 关于`request.state` - -`request.state`是每个`Request`对象的属性。它用于存储附加到请求本身的任意对象,例如本例中的数据库会话。您可以在[Starlette 的关于`Request`state](https://www.starlette.io/requests/#other-state)的文档中了解更多信息。 - -对于这种情况下,它帮助我们确保在整个请求中使用单个数据库会话,然后关闭(在中间件中)。 - -### 使用`yield`依赖项与使用中间件的区别 - -在此处添加**中间件**与`yield`的依赖项的作用效果类似,但也有一些区别: - -* 中间件需要更多的代码并且更复杂一些。 -* 中间件必须是一个`async`函数。 - * 如果其中有代码必须“等待”网络,它可能会在那里“阻止”您的应用程序并稍微降低性能。 - * 尽管这里的`SQLAlchemy`工作方式可能不是很成问题。 - * 但是,如果您向等待大量I/O的中间件添加更多代码,则可能会出现问题。 -* *每个*请求都会运行一个中间件。 - * 将为每个请求创建一个连接。 - * 即使处理该请求的*路径操作*不需要数据库。 - -/// tip - -最好使用带有yield的依赖项,如果这足够满足用例需求 - -/// - -/// info - -带有`yield`的依赖项是最近刚加入**FastAPI**中的。 - -所以本教程的先前版本只有带有中间件的示例,并且可能有多个应用程序使用中间件进行数据库会话管理。 - -/// From a0c3282af0a47fe492676d8d02a33335231e8ffb Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 17 Nov 2024 22:32:05 +0000 Subject: [PATCH 459/932] =?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 [skip ci] --- 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 c58c4abc8..fa6da7090 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -12,6 +12,10 @@ hide: * 📝 Update includes for `docs/de/docs/advanced/using-request-directly.md`. PR [#12685](https://github.com/fastapi/fastapi/pull/12685) by [@alissadb](https://github.com/alissadb). * 📝 Update includes for `docs/de/docs/how-to/conditional-openapi.md`. PR [#12689](https://github.com/fastapi/fastapi/pull/12689) by [@alissadb](https://github.com/alissadb). +### Translations + +* 🔥 Remove obsolete tutorial translation to Chinese for `docs/zh/docs/tutorial/sql-databases.md`, it references files that are no longer on the repo. PR [#12949](https://github.com/fastapi/fastapi/pull/12949) by [@tiangolo](https://github.com/tiangolo). + ## 0.115.5 ### Refactors From 1c711e71472a68fd6d6e00068e803104707ed4cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 18 Nov 2024 03:25:44 +0100 Subject: [PATCH 460/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20form?= =?UTF-8?q?at=20in=20docs=20with=20an=20automated=20script=20(#12950)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/bn/docs/python-types.md | 50 +- .../docs/advanced/additional-status-codes.md | 52 +- .../de/docs/advanced/advanced-dependencies.md | 120 +-- docs/de/docs/advanced/async-tests.md | 8 +- docs/de/docs/advanced/behind-a-proxy.md | 20 +- docs/de/docs/advanced/custom-response.md | 60 +- docs/de/docs/advanced/events.md | 24 +- docs/de/docs/advanced/generate-clients.md | 56 +- docs/de/docs/advanced/middleware.md | 12 +- docs/de/docs/advanced/openapi-callbacks.md | 16 +- docs/de/docs/advanced/openapi-webhooks.md | 4 +- .../path-operation-advanced-configuration.md | 40 +- .../advanced/response-change-status-code.md | 4 +- docs/de/docs/advanced/response-cookies.md | 8 +- docs/de/docs/advanced/response-directly.md | 8 +- docs/de/docs/advanced/response-headers.md | 8 +- .../docs/advanced/security/oauth2-scopes.md | 528 +--------- docs/de/docs/advanced/settings.md | 126 +-- docs/de/docs/advanced/sub-applications.md | 12 +- docs/de/docs/advanced/templates.md | 4 +- docs/de/docs/advanced/testing-dependencies.md | 52 +- docs/de/docs/advanced/testing-events.md | 4 +- docs/de/docs/advanced/testing-websockets.md | 4 +- docs/de/docs/advanced/websockets.md | 80 +- docs/de/docs/advanced/wsgi.md | 4 +- docs/de/docs/how-to/custom-docs-ui-assets.md | 28 +- .../docs/how-to/custom-request-and-route.md | 24 +- docs/de/docs/how-to/extending-openapi.md | 20 +- docs/de/docs/how-to/graphql.md | 4 +- .../docs/how-to/separate-openapi-schemas.md | 162 +--- docs/de/docs/tutorial/background-tasks.md | 64 +- docs/de/docs/tutorial/body-fields.md | 104 +- docs/de/docs/tutorial/body-nested-models.md | 220 +---- docs/de/docs/tutorial/body-updates.md | 96 +- docs/de/docs/tutorial/body.md | 96 +- docs/de/docs/tutorial/cookie-params.md | 104 +- .../dependencies/classes-as-dependencies.md | 364 +------ ...pendencies-in-path-operation-decorators.md | 120 +-- .../dependencies/dependencies-with-yield.md | 110 +-- .../dependencies/global-dependencies.md | 30 +- docs/de/docs/tutorial/dependencies/index.md | 180 +--- .../tutorial/dependencies/sub-dependencies.md | 156 +-- docs/de/docs/tutorial/encoder.md | 16 +- docs/de/docs/tutorial/extra-data-types.md | 104 +- docs/de/docs/tutorial/extra-models.md | 80 +- docs/de/docs/tutorial/first-steps.md | 32 +- docs/de/docs/tutorial/handling-errors.md | 32 +- docs/de/docs/tutorial/header-params.md | 222 +---- docs/de/docs/tutorial/metadata.md | 24 +- .../tutorial/path-operation-configuration.md | 128 +-- .../path-params-numeric-validations.md | 230 +---- docs/de/docs/tutorial/path-params.md | 40 +- .../tutorial/query-params-str-validations.md | 708 +------------- docs/de/docs/tutorial/query-params.md | 72 +- docs/de/docs/tutorial/request-files.md | 260 +---- .../docs/tutorial/request-forms-and-files.md | 60 +- docs/de/docs/tutorial/request-forms.md | 60 +- docs/de/docs/tutorial/response-model.md | 264 +---- docs/de/docs/tutorial/security/first-steps.md | 90 +- .../tutorial/security/get-current-user.md | 290 +----- docs/de/docs/tutorial/security/oauth2-jwt.md | 208 +--- .../docs/tutorial/security/simple-oauth2.md | 260 +---- docs/de/docs/tutorial/static-files.md | 4 +- docs/de/docs/tutorial/testing.md | 19 +- docs/em/docs/advanced/additional-responses.md | 16 +- .../docs/advanced/additional-status-codes.md | 4 +- .../em/docs/advanced/advanced-dependencies.md | 16 +- docs/em/docs/advanced/async-tests.md | 16 +- docs/em/docs/advanced/behind-a-proxy.md | 16 +- docs/em/docs/advanced/custom-response.md | 60 +- docs/em/docs/advanced/dataclasses.md | 8 +- docs/em/docs/advanced/events.md | 24 +- docs/em/docs/advanced/generate-clients.md | 52 +- docs/em/docs/advanced/middleware.md | 12 +- docs/em/docs/advanced/openapi-callbacks.md | 16 +- .../path-operation-advanced-configuration.md | 32 +- .../advanced/response-change-status-code.md | 4 +- docs/em/docs/advanced/response-cookies.md | 8 +- docs/em/docs/advanced/response-directly.md | 8 +- docs/em/docs/advanced/response-headers.md | 8 +- .../docs/advanced/security/http-basic-auth.md | 12 +- .../docs/advanced/security/oauth2-scopes.md | 32 +- docs/em/docs/advanced/settings.md | 40 +- docs/em/docs/advanced/sub-applications.md | 12 +- docs/em/docs/advanced/templates.md | 4 +- docs/em/docs/advanced/testing-dependencies.md | 4 +- docs/em/docs/advanced/testing-events.md | 4 +- docs/em/docs/advanced/testing-websockets.md | 4 +- .../docs/advanced/using-request-directly.md | 4 +- docs/em/docs/advanced/websockets.md | 20 +- docs/em/docs/advanced/wsgi.md | 4 +- docs/em/docs/how-to/conditional-openapi.md | 4 +- .../docs/how-to/custom-request-and-route.md | 24 +- docs/em/docs/how-to/extending-openapi.md | 20 +- docs/em/docs/how-to/graphql.md | 4 +- docs/em/docs/tutorial/background-tasks.md | 28 +- docs/em/docs/tutorial/body-fields.md | 32 +- docs/em/docs/tutorial/body-multiple-params.md | 80 +- docs/em/docs/tutorial/body-nested-models.md | 220 +---- docs/em/docs/tutorial/body.md | 96 +- docs/em/docs/tutorial/cookie-params.md | 32 +- docs/em/docs/tutorial/cors.md | 4 +- docs/em/docs/tutorial/debugging.md | 4 +- .../dependencies/classes-as-dependencies.md | 112 +-- ...pendencies-in-path-operation-decorators.md | 16 +- .../dependencies/dependencies-with-yield.md | 28 +- .../dependencies/global-dependencies.md | 4 +- docs/em/docs/tutorial/dependencies/index.md | 48 +- .../tutorial/dependencies/sub-dependencies.md | 48 +- docs/em/docs/tutorial/encoder.md | 16 +- docs/em/docs/tutorial/extra-data-types.md | 32 +- docs/em/docs/tutorial/extra-models.md | 80 +- docs/em/docs/tutorial/first-steps.md | 32 +- docs/em/docs/tutorial/handling-errors.md | 32 +- docs/em/docs/tutorial/header-params.md | 72 +- docs/em/docs/tutorial/metadata.md | 20 +- docs/em/docs/tutorial/middleware.md | 8 +- .../tutorial/path-operation-configuration.md | 128 +-- .../path-params-numeric-validations.md | 52 +- docs/em/docs/tutorial/path-params.md | 40 +- .../tutorial/query-params-str-validations.md | 236 +---- docs/em/docs/tutorial/query-params.md | 72 +- docs/em/docs/tutorial/request-files.md | 64 +- .../docs/tutorial/request-forms-and-files.md | 8 +- docs/em/docs/tutorial/request-forms.md | 8 +- docs/em/docs/tutorial/response-model.md | 264 +---- docs/em/docs/tutorial/response-status-code.md | 12 +- docs/em/docs/tutorial/schema-extra-example.md | 64 +- docs/em/docs/tutorial/security/first-steps.md | 12 +- .../tutorial/security/get-current-user.md | 84 +- docs/em/docs/tutorial/security/oauth2-jwt.md | 64 +- .../docs/tutorial/security/simple-oauth2.md | 80 +- docs/em/docs/tutorial/sql-databases.md | 900 ------------------ docs/em/docs/tutorial/static-files.md | 4 +- docs/em/docs/tutorial/testing.md | 32 +- docs/en/docs/advanced/generate-clients.md | 8 +- docs/en/docs/advanced/settings.md | 126 +-- docs/en/docs/advanced/templates.md | 4 +- docs/en/docs/advanced/testing-events.md | 4 +- docs/en/docs/tutorial/debugging.md | 4 +- .../dependencies/dependencies-with-yield.md | 170 +--- docs/en/docs/tutorial/extra-data-types.md | 104 +- docs/en/docs/tutorial/handling-errors.md | 32 +- .../tutorial/query-params-str-validations.md | 708 +------------- docs/en/docs/tutorial/query-params.md | 72 +- .../docs/tutorial/request-forms-and-files.md | 60 +- .../docs/tutorial/security/simple-oauth2.md | 260 +---- docs/en/docs/tutorial/testing.md | 18 +- .../docs/advanced/additional-status-codes.md | 4 +- .../path-operation-advanced-configuration.md | 16 +- .../advanced/response-change-status-code.md | 4 +- docs/es/docs/advanced/response-directly.md | 8 +- docs/es/docs/advanced/response-headers.md | 8 +- docs/es/docs/how-to/graphql.md | 4 +- docs/es/docs/python-types.md | 65 +- docs/es/docs/tutorial/first-steps.md | 32 +- docs/es/docs/tutorial/path-params.md | 36 +- docs/es/docs/tutorial/query-params.md | 24 +- docs/fa/docs/advanced/sub-applications.md | 12 +- docs/fa/docs/tutorial/middleware.md | 8 +- .../docs/advanced/additional-status-codes.md | 4 +- .../docs/advanced/additional-status-codes.md | 4 +- docs/ja/docs/advanced/custom-response.md | 48 +- .../path-operation-advanced-configuration.md | 16 +- docs/ja/docs/advanced/response-directly.md | 8 +- docs/ja/docs/advanced/websockets.md | 20 +- docs/ja/docs/how-to/conditional-openapi.md | 4 +- docs/ja/docs/python-types.md | 65 +- docs/ja/docs/tutorial/background-tasks.md | 16 +- docs/ja/docs/tutorial/body-fields.md | 8 +- docs/ja/docs/tutorial/body-multiple-params.md | 20 +- docs/ja/docs/tutorial/body-nested-models.md | 44 +- docs/ja/docs/tutorial/body-updates.md | 16 +- docs/ja/docs/tutorial/body.md | 24 +- docs/ja/docs/tutorial/cookie-params.md | 8 +- docs/ja/docs/tutorial/cors.md | 4 +- docs/ja/docs/tutorial/debugging.md | 4 +- .../dependencies/classes-as-dependencies.md | 28 +- ...pendencies-in-path-operation-decorators.md | 16 +- .../dependencies/dependencies-with-yield.md | 28 +- docs/ja/docs/tutorial/dependencies/index.md | 12 +- .../tutorial/dependencies/sub-dependencies.md | 12 +- docs/ja/docs/tutorial/encoder.md | 4 +- docs/ja/docs/tutorial/extra-data-types.md | 8 +- docs/ja/docs/tutorial/extra-models.md | 20 +- docs/ja/docs/tutorial/first-steps.md | 32 +- docs/ja/docs/tutorial/handling-errors.md | 32 +- docs/ja/docs/tutorial/header-params.md | 16 +- docs/ja/docs/tutorial/metadata.md | 20 +- docs/ja/docs/tutorial/middleware.md | 8 +- .../tutorial/path-operation-configuration.md | 24 +- .../path-params-numeric-validations.md | 28 +- docs/ja/docs/tutorial/path-params.md | 36 +- .../tutorial/query-params-str-validations.md | 56 +- docs/ja/docs/tutorial/query-params.md | 24 +- .../docs/tutorial/request-forms-and-files.md | 8 +- docs/ja/docs/tutorial/request-forms.md | 8 +- docs/ja/docs/tutorial/response-model.md | 40 +- docs/ja/docs/tutorial/response-status-code.md | 12 +- docs/ja/docs/tutorial/schema-extra-example.md | 12 +- docs/ja/docs/tutorial/security/first-steps.md | 12 +- .../tutorial/security/get-current-user.md | 24 +- docs/ja/docs/tutorial/security/oauth2-jwt.md | 16 +- docs/ja/docs/tutorial/static-files.md | 4 +- docs/ja/docs/tutorial/testing.md | 32 +- .../ko/docs/advanced/advanced-dependencies.md | 120 +-- docs/ko/docs/advanced/events.md | 8 +- .../advanced/response-change-status-code.md | 4 +- docs/ko/docs/advanced/response-cookies.md | 8 +- docs/ko/docs/advanced/response-directly.md | 8 +- docs/ko/docs/advanced/response-headers.md | 8 +- docs/ko/docs/advanced/testing-events.md | 4 +- docs/ko/docs/advanced/testing-websockets.md | 4 +- .../docs/advanced/using-request-directly.md | 4 +- docs/ko/docs/advanced/wsgi.md | 4 +- docs/ko/docs/python-types.md | 65 +- docs/ko/docs/tutorial/background-tasks.md | 28 +- docs/ko/docs/tutorial/body-fields.md | 104 +- docs/ko/docs/tutorial/body-multiple-params.md | 20 +- docs/ko/docs/tutorial/body-nested-models.md | 44 +- docs/ko/docs/tutorial/body.md | 96 +- docs/ko/docs/tutorial/cookie-params.md | 104 +- docs/ko/docs/tutorial/cors.md | 4 +- docs/ko/docs/tutorial/debugging.md | 4 +- .../dependencies/classes-as-dependencies.md | 112 +-- ...pendencies-in-path-operation-decorators.md | 120 +-- .../dependencies/global-dependencies.md | 30 +- docs/ko/docs/tutorial/dependencies/index.md | 180 +--- docs/ko/docs/tutorial/encoder.md | 4 +- docs/ko/docs/tutorial/extra-data-types.md | 104 +- docs/ko/docs/tutorial/first-steps.md | 32 +- docs/ko/docs/tutorial/header-params.md | 16 +- docs/ko/docs/tutorial/metadata.md | 25 +- docs/ko/docs/tutorial/middleware.md | 8 +- .../tutorial/path-operation-configuration.md | 24 +- .../path-params-numeric-validations.md | 28 +- docs/ko/docs/tutorial/path-params.md | 36 +- .../tutorial/query-params-str-validations.md | 56 +- docs/ko/docs/tutorial/query-params.md | 24 +- docs/ko/docs/tutorial/request-files.md | 16 +- .../docs/tutorial/request-forms-and-files.md | 8 +- docs/ko/docs/tutorial/response-model.md | 40 +- docs/ko/docs/tutorial/response-status-code.md | 12 +- .../tutorial/security/get-current-user.md | 84 +- .../docs/tutorial/security/simple-oauth2.md | 76 +- docs/ko/docs/tutorial/static-files.md | 4 +- docs/nl/docs/python-types.md | 50 +- docs/pt/docs/advanced/additional-responses.md | 16 +- .../docs/advanced/additional-status-codes.md | 52 +- .../pt/docs/advanced/advanced-dependencies.md | 120 +-- docs/pt/docs/advanced/async-tests.md | 16 +- docs/pt/docs/advanced/custom-response.md | 60 +- docs/pt/docs/advanced/dataclasses.md | 8 +- docs/pt/docs/advanced/events.md | 24 +- docs/pt/docs/advanced/openapi-callbacks.md | 16 +- docs/pt/docs/advanced/openapi-webhooks.md | 4 +- .../path-operation-advanced-configuration.md | 16 +- .../advanced/response-change-status-code.md | 4 +- docs/pt/docs/advanced/response-cookies.md | 8 +- docs/pt/docs/advanced/response-directly.md | 8 +- docs/pt/docs/advanced/response-headers.md | 8 +- .../docs/advanced/security/http-basic-auth.md | 90 +- .../docs/advanced/security/oauth2-scopes.md | 528 +--------- docs/pt/docs/advanced/settings.md | 126 +-- docs/pt/docs/advanced/sub-applications.md | 12 +- docs/pt/docs/advanced/templates.md | 4 +- docs/pt/docs/advanced/testing-dependencies.md | 52 +- docs/pt/docs/advanced/testing-events.md | 4 +- docs/pt/docs/advanced/testing-websockets.md | 4 +- .../docs/advanced/using-request-directly.md | 4 +- docs/pt/docs/advanced/websockets.md | 4 +- docs/pt/docs/how-to/conditional-openapi.md | 4 +- docs/pt/docs/how-to/configure-swagger-ui.md | 16 +- docs/pt/docs/how-to/custom-docs-ui-assets.md | 28 +- .../docs/how-to/custom-request-and-route.md | 24 +- docs/pt/docs/how-to/extending-openapi.md | 21 +- docs/pt/docs/how-to/graphql.md | 4 +- .../docs/how-to/separate-openapi-schemas.md | 162 +--- docs/pt/docs/tutorial/body-fields.md | 8 +- docs/pt/docs/tutorial/body-multiple-params.md | 80 +- docs/pt/docs/tutorial/body-nested-models.md | 44 +- docs/pt/docs/tutorial/body-updates.md | 96 +- docs/pt/docs/tutorial/body.md | 24 +- docs/pt/docs/tutorial/cookie-param-models.md | 82 +- docs/pt/docs/tutorial/cookie-params.md | 104 +- docs/pt/docs/tutorial/cors.md | 4 +- docs/pt/docs/tutorial/debugging.md | 4 +- .../dependencies/classes-as-dependencies.md | 364 +------ ...pendencies-in-path-operation-decorators.md | 122 +-- .../dependencies/dependencies-with-yield.md | 66 +- .../dependencies/global-dependencies.md | 30 +- docs/pt/docs/tutorial/dependencies/index.md | 180 +--- .../tutorial/dependencies/sub-dependencies.md | 156 +-- docs/pt/docs/tutorial/encoder.md | 16 +- docs/pt/docs/tutorial/extra-data-types.md | 8 +- docs/pt/docs/tutorial/extra-models.md | 80 +- docs/pt/docs/tutorial/first-steps.md | 32 +- docs/pt/docs/tutorial/handling-errors.md | 28 +- docs/pt/docs/tutorial/header-param-models.md | 132 +-- docs/pt/docs/tutorial/header-params.md | 72 +- docs/pt/docs/tutorial/metadata.md | 24 +- docs/pt/docs/tutorial/middleware.md | 8 +- .../tutorial/path-operation-configuration.md | 128 +-- .../path-params-numeric-validations.md | 52 +- docs/pt/docs/tutorial/path-params.md | 36 +- docs/pt/docs/tutorial/query-param-models.md | 132 +-- .../tutorial/query-params-str-validations.md | 56 +- docs/pt/docs/tutorial/query-params.md | 72 +- docs/pt/docs/tutorial/request-form-models.md | 60 +- .../docs/tutorial/request-forms-and-files.md | 8 +- docs/pt/docs/tutorial/request-forms.md | 8 +- docs/pt/docs/tutorial/request_files.md | 260 +---- docs/pt/docs/tutorial/response-status-code.md | 12 +- docs/pt/docs/tutorial/schema-extra-example.md | 16 +- docs/pt/docs/tutorial/security/first-steps.md | 12 +- .../docs/tutorial/security/simple-oauth2.md | 260 +---- docs/pt/docs/tutorial/static-files.md | 4 +- docs/pt/docs/tutorial/testing.md | 16 +- docs/ru/docs/python-types.md | 65 +- docs/ru/docs/tutorial/background-tasks.md | 28 +- docs/ru/docs/tutorial/body-fields.md | 32 +- docs/ru/docs/tutorial/body-multiple-params.md | 224 +---- docs/ru/docs/tutorial/body-nested-models.md | 220 +---- docs/ru/docs/tutorial/body-updates.md | 96 +- docs/ru/docs/tutorial/body.md | 24 +- docs/ru/docs/tutorial/cookie-params.md | 32 +- docs/ru/docs/tutorial/cors.md | 4 +- docs/ru/docs/tutorial/debugging.md | 4 +- .../dependencies/classes-as-dependencies.md | 364 +------ ...pendencies-in-path-operation-decorators.md | 120 +-- .../dependencies/dependencies-with-yield.md | 80 +- .../dependencies/global-dependencies.md | 30 +- docs/ru/docs/tutorial/dependencies/index.md | 180 +--- .../tutorial/dependencies/sub-dependencies.md | 156 +-- docs/ru/docs/tutorial/encoder.md | 16 +- docs/ru/docs/tutorial/extra-data-types.md | 32 +- docs/ru/docs/tutorial/extra-models.md | 80 +- docs/ru/docs/tutorial/first-steps.md | 32 +- docs/ru/docs/tutorial/handling-errors.md | 32 +- docs/ru/docs/tutorial/header-params.md | 222 +---- docs/ru/docs/tutorial/metadata.md | 20 +- .../tutorial/path-operation-configuration.md | 128 +-- .../path-params-numeric-validations.md | 230 +---- docs/ru/docs/tutorial/path-params.md | 40 +- .../tutorial/query-params-str-validations.md | 732 +------------- docs/ru/docs/tutorial/query-params.md | 72 +- docs/ru/docs/tutorial/request-files.md | 260 +---- .../docs/tutorial/request-forms-and-files.md | 60 +- docs/ru/docs/tutorial/request-forms.md | 60 +- docs/ru/docs/tutorial/response-model.md | 264 +---- docs/ru/docs/tutorial/response-status-code.md | 12 +- docs/ru/docs/tutorial/schema-extra-example.md | 136 +-- docs/ru/docs/tutorial/security/first-steps.md | 90 +- docs/ru/docs/tutorial/static-files.md | 4 +- docs/ru/docs/tutorial/testing.md | 18 +- docs/tr/docs/advanced/testing-websockets.md | 4 +- docs/tr/docs/advanced/wsgi.md | 4 +- docs/tr/docs/python-types.md | 65 +- docs/tr/docs/tutorial/cookie-params.md | 104 +- docs/tr/docs/tutorial/first-steps.md | 32 +- docs/tr/docs/tutorial/path-params.md | 40 +- docs/tr/docs/tutorial/query-params.md | 72 +- docs/tr/docs/tutorial/request-forms.md | 60 +- docs/tr/docs/tutorial/static-files.md | 4 +- docs/uk/docs/python-types.md | 40 +- docs/uk/docs/tutorial/body-fields.md | 104 +- docs/uk/docs/tutorial/body.md | 96 +- docs/uk/docs/tutorial/cookie-params.md | 104 +- docs/uk/docs/tutorial/encoder.md | 16 +- docs/uk/docs/tutorial/extra-data-types.md | 104 +- docs/uk/docs/tutorial/first-steps.md | 28 +- docs/vi/docs/python-types.md | 50 +- .../docs/advanced/additional-status-codes.md | 4 +- .../zh/docs/advanced/advanced-dependencies.md | 16 +- docs/zh/docs/advanced/behind-a-proxy.md | 16 +- docs/zh/docs/advanced/custom-response.md | 44 +- docs/zh/docs/advanced/dataclasses.md | 8 +- docs/zh/docs/advanced/events.md | 8 +- docs/zh/docs/advanced/generate-clients.md | 52 +- docs/zh/docs/advanced/middleware.md | 12 +- docs/zh/docs/advanced/openapi-callbacks.md | 16 +- .../path-operation-advanced-configuration.md | 16 +- .../advanced/response-change-status-code.md | 4 +- docs/zh/docs/advanced/response-cookies.md | 8 +- docs/zh/docs/advanced/response-directly.md | 8 +- docs/zh/docs/advanced/response-headers.md | 9 +- .../docs/advanced/security/http-basic-auth.md | 90 +- .../docs/advanced/security/oauth2-scopes.md | 32 +- docs/zh/docs/advanced/settings.md | 118 +-- docs/zh/docs/advanced/sub-applications.md | 12 +- docs/zh/docs/advanced/templates.md | 4 +- docs/zh/docs/advanced/testing-dependencies.md | 4 +- docs/zh/docs/advanced/testing-events.md | 4 +- docs/zh/docs/advanced/testing-websockets.md | 4 +- .../docs/advanced/using-request-directly.md | 4 +- docs/zh/docs/advanced/websockets.md | 80 +- docs/zh/docs/advanced/wsgi.md | 4 +- docs/zh/docs/how-to/configure-swagger-ui.md | 16 +- docs/zh/docs/python-types.md | 65 +- docs/zh/docs/tutorial/body-fields.md | 104 +- docs/zh/docs/tutorial/body-multiple-params.md | 224 +---- docs/zh/docs/tutorial/body-nested-models.md | 220 +---- docs/zh/docs/tutorial/body-updates.md | 16 +- docs/zh/docs/tutorial/body.md | 96 +- docs/zh/docs/tutorial/cookie-params.md | 104 +- docs/zh/docs/tutorial/cors.md | 4 +- docs/zh/docs/tutorial/debugging.md | 4 +- .../dependencies/classes-as-dependencies.md | 112 +-- ...pendencies-in-path-operation-decorators.md | 16 +- .../dependencies/dependencies-with-yield.md | 170 +--- .../dependencies/global-dependencies.md | 4 +- docs/zh/docs/tutorial/dependencies/index.md | 12 +- .../tutorial/dependencies/sub-dependencies.md | 12 +- docs/zh/docs/tutorial/encoder.md | 16 +- docs/zh/docs/tutorial/extra-data-types.md | 104 +- docs/zh/docs/tutorial/extra-models.md | 80 +- docs/zh/docs/tutorial/first-steps.md | 32 +- docs/zh/docs/tutorial/handling-errors.md | 40 +- docs/zh/docs/tutorial/header-params.md | 222 +---- docs/zh/docs/tutorial/metadata.md | 20 +- docs/zh/docs/tutorial/middleware.md | 8 +- .../tutorial/path-operation-configuration.md | 24 +- .../path-params-numeric-validations.md | 134 +-- docs/zh/docs/tutorial/path-params.md | 36 +- .../tutorial/query-params-str-validations.md | 80 +- docs/zh/docs/tutorial/query-params.md | 72 +- docs/zh/docs/tutorial/request-files.md | 64 +- .../docs/tutorial/request-forms-and-files.md | 8 +- docs/zh/docs/tutorial/request-forms.md | 8 +- docs/zh/docs/tutorial/response-model.md | 96 +- docs/zh/docs/tutorial/response-status-code.md | 12 +- docs/zh/docs/tutorial/schema-extra-example.md | 84 +- docs/zh/docs/tutorial/security/first-steps.md | 38 +- .../tutorial/security/get-current-user.md | 24 +- docs/zh/docs/tutorial/security/oauth2-jwt.md | 160 +--- .../docs/tutorial/security/simple-oauth2.md | 20 +- docs/zh/docs/tutorial/static-files.md | 4 +- docs/zh/docs/tutorial/testing.md | 16 +- ...regex.py => tutorial004_regex_an_py310.py} | 0 439 files changed, 2134 insertions(+), 24948 deletions(-) delete mode 100644 docs/em/docs/tutorial/sql-databases.md rename docs_src/query_params_str_validations/{tutorial004_an_py310_regex.py => tutorial004_regex_an_py310.py} (100%) diff --git a/docs/bn/docs/python-types.md b/docs/bn/docs/python-types.md index 4a602b679..d98c2ec87 100644 --- a/docs/bn/docs/python-types.md +++ b/docs/bn/docs/python-types.md @@ -22,9 +22,8 @@ Python-এ ঐচ্ছিক "টাইপ হিন্ট" (যা "টাই চলুন একটি সাধারণ উদাহরণ দিয়ে শুরু করি: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + এই প্রোগ্রামটি কল করলে আউটপুট হয়: @@ -38,9 +37,8 @@ John Doe * প্রতিটির প্রথম অক্ষরকে `title()` ব্যবহার করে বড় হাতের অক্ষরে রূপান্তর করে। * তাদেরকে মাঝখানে একটি স্পেস দিয়ে concatenate করে। -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### এটি সম্পাদনা করুন @@ -82,9 +80,8 @@ John Doe এগুলিই "টাইপ হিন্ট": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + এটি ডিফল্ট ভ্যালু ঘোষণা করার মত নয় যেমন: @@ -112,9 +109,8 @@ John Doe এই ফাংশনটি দেখুন, এটিতে ইতিমধ্যে টাইপ হিন্ট রয়েছে: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + এডিটর ভেরিয়েবলগুলির টাইপ জানার কারণে, আপনি শুধুমাত্র অটোকমপ্লিশনই পান না, আপনি এরর চেকও পান: @@ -122,9 +118,8 @@ John Doe এখন আপনি জানেন যে আপনাকে এটি ঠিক করতে হবে, `age`-কে একটি স্ট্রিং হিসেবে রূপান্তর করতে `str(age)` ব্যবহার করতে হবে: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## টাইপ ঘোষণা @@ -143,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### টাইপ প্যারামিটার সহ জেনেরিক টাইপ @@ -369,9 +363,8 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি একটি উদাহরণ হিসেবে, এই ফাংশনটি নিন: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c.py!} -``` +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} + `name` প্যারামিটারটি `Optional[str]` হিসেবে সংজ্ঞায়িত হয়েছে, কিন্তু এটি **অপশনাল নয়**, আপনি প্যারামিটার ছাড়া ফাংশনটি কল করতে পারবেন না: @@ -387,9 +380,8 @@ say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉 সুখবর হল, একবার আপনি Python 3.10 ব্যবহার করা শুরু করলে, আপনাকে এগুলোর ব্যাপারে আর চিন্তা করতে হবে না, যেহুতু আপনি | ব্যবহার করেই ইউনিয়ন ঘোষণা করতে পারবেন: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c_py310.py!} -``` +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} + এবং তারপর আপনাকে নামগুলি যেমন `Optional` এবং `Union` নিয়ে আর চিন্তা করতে হবে না। 😎 @@ -451,15 +443,13 @@ Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্য ধরুন আপনার কাছে `Person` নামে একটি ক্লাস আছে, যার একটি নাম আছে: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + তারপর আপনি একটি ভেরিয়েবলকে `Person` টাইপের হিসেবে ঘোষণা করতে পারেন: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + এবং তারপর, আবার, আপনি এডিটর সাপোর্ট পেয়ে যাবেন: diff --git a/docs/de/docs/advanced/additional-status-codes.md b/docs/de/docs/advanced/additional-status-codes.md index 50702e7e6..b07bb90ab 100644 --- a/docs/de/docs/advanced/additional-status-codes.md +++ b/docs/de/docs/advanced/additional-status-codes.md @@ -14,57 +14,7 @@ Sie möchten aber auch, dass sie neue Artikel akzeptiert. Und wenn die Elemente Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt direkt zurück, indem Sie den gewünschten `status_code` setzen: -//// 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+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="2 23" -{!> ../../docs_src/additional_status_codes/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="4 25" -{!> ../../docs_src/additional_status_codes/tutorial001.py!} -``` - -//// +{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *} /// warning | Achtung diff --git a/docs/de/docs/advanced/advanced-dependencies.md b/docs/de/docs/advanced/advanced-dependencies.md index 80cbf1fd3..56eb7d454 100644 --- a/docs/de/docs/advanced/advanced-dependencies.md +++ b/docs/de/docs/advanced/advanced-dependencies.md @@ -18,35 +18,7 @@ Nicht die Klasse selbst (die bereits aufrufbar ist), sondern eine Instanz dieser Dazu deklarieren wir eine Methode `__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+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *} In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zusätzlichen Parametern und Unterabhängigkeiten zu suchen, und das ist es auch, was später aufgerufen wird, um einen Wert an den Parameter in Ihrer *Pfadoperation-Funktion* zu übergeben. @@ -54,35 +26,7 @@ In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zus Und jetzt können wir `__init__` verwenden, um die Parameter der Instanz zu deklarieren, die wir zum `Parametrisieren` der Abhängigkeit verwenden können: -//// 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+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *} In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmern, wir werden es direkt in unserem Code verwenden. @@ -90,35 +34,7 @@ In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmer Wir könnten eine Instanz dieser Klasse erstellen mit: -//// 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+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *} Und auf diese Weise können wir unsere Abhängigkeit „parametrisieren“, die jetzt `"bar"` enthält, als das Attribut `checker.fixed_content`. @@ -134,35 +50,7 @@ checker(q="somequery") ... und übergibt, was immer das als Wert dieser Abhängigkeit in unserer *Pfadoperation-Funktion* zurückgibt, als den Parameter `fixed_content_included`: -//// 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+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *} /// tip | Tipp diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md index c118e588f..b82aadf00 100644 --- a/docs/de/docs/advanced/async-tests.md +++ b/docs/de/docs/advanced/async-tests.md @@ -32,15 +32,11 @@ Betrachten wir als einfaches Beispiel eine Dateistruktur ähnlich der in [Größ Die Datei `main.py` hätte als Inhalt: -```Python -{!../../docs_src/async_tests/main.py!} -``` +{* ../../docs_src/async_tests/main.py *} Die Datei `test_main.py` hätte die Tests für `main.py`, das könnte jetzt so aussehen: -```Python -{!../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py *} ## Es ausführen diff --git a/docs/de/docs/advanced/behind-a-proxy.md b/docs/de/docs/advanced/behind-a-proxy.md index 9da18a626..9e2282280 100644 --- a/docs/de/docs/advanced/behind-a-proxy.md +++ b/docs/de/docs/advanced/behind-a-proxy.md @@ -18,9 +18,7 @@ In diesem Fall würde der ursprüngliche Pfad `/app` tatsächlich unter `/api/v1 Auch wenn Ihr gesamter Code unter der Annahme geschrieben ist, dass es nur `/app` gibt. -```Python hl_lines="6" -{!../../docs_src/behind_a_proxy/tutorial001.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[6] *} Und der Proxy würde das **Pfadpräfix** on-the-fly **"entfernen**", bevor er die Anfrage an Uvicorn übermittelt, dafür sorgend, dass Ihre Anwendung davon überzeugt ist, dass sie unter `/app` bereitgestellt wird, sodass Sie nicht Ihren gesamten Code dahingehend aktualisieren müssen, das Präfix `/api/v1` zu verwenden. @@ -98,9 +96,7 @@ Sie können den aktuellen `root_path` abrufen, der von Ihrer Anwendung für jede Hier fügen wir ihn, nur zu Demonstrationszwecken, in die Nachricht ein. -```Python hl_lines="8" -{!../../docs_src/behind_a_proxy/tutorial001.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *} Wenn Sie Uvicorn dann starten mit: @@ -127,9 +123,7 @@ wäre die Response etwa: Falls Sie keine Möglichkeit haben, eine Kommandozeilenoption wie `--root-path` oder ähnlich zu übergeben, können Sie als Alternative beim Erstellen Ihrer FastAPI-Anwendung den Parameter `root_path` setzen: -```Python hl_lines="3" -{!../../docs_src/behind_a_proxy/tutorial002.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *} Die Übergabe des `root_path` an `FastAPI` wäre das Äquivalent zur Übergabe der `--root-path`-Kommandozeilenoption an Uvicorn oder Hypercorn. @@ -309,9 +303,7 @@ Wenn Sie eine benutzerdefinierte Liste von Servern (`servers`) übergeben und es Zum Beispiel: -```Python hl_lines="4-7" -{!../../docs_src/behind_a_proxy/tutorial003.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *} Erzeugt ein OpenAPI-Schema, wie: @@ -358,9 +350,7 @@ Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server Wenn Sie nicht möchten, dass **FastAPI** einen automatischen Server inkludiert, welcher `root_path` verwendet, können Sie den Parameter `root_path_in_servers=False` verwenden: -```Python hl_lines="9" -{!../../docs_src/behind_a_proxy/tutorial004.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *} Dann wird er nicht in das OpenAPI-Schema aufgenommen. diff --git a/docs/de/docs/advanced/custom-response.md b/docs/de/docs/advanced/custom-response.md index 7738bfca4..43cb55e04 100644 --- a/docs/de/docs/advanced/custom-response.md +++ b/docs/de/docs/advanced/custom-response.md @@ -30,9 +30,7 @@ Das liegt daran, dass FastAPI standardmäßig jedes enthaltene Element überprü Wenn Sie jedoch sicher sind, dass der von Ihnen zurückgegebene Inhalt **mit JSON serialisierbar** ist, können Sie ihn direkt an die Response-Klasse übergeben und die zusätzliche Arbeit vermeiden, die FastAPI hätte, indem es Ihren zurückgegebenen Inhalt durch den `jsonable_encoder` leitet, bevor es ihn an die Response-Klasse übergibt. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} /// info @@ -57,9 +55,7 @@ Um eine Response mit HTML direkt von **FastAPI** zurückzugeben, verwenden Sie ` * Importieren Sie `HTMLResponse`. * Übergeben Sie `HTMLResponse` als den Parameter `response_class` Ihres *Pfadoperation-Dekorators*. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial002.py!} -``` +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} /// info @@ -77,9 +73,7 @@ Wie in [Eine Response direkt zurückgeben](response-directly.md){.internal-link Das gleiche Beispiel von oben, das eine `HTMLResponse` zurückgibt, könnte so aussehen: -```Python hl_lines="2 7 19" -{!../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} /// warning | Achtung @@ -103,9 +97,7 @@ Die `response_class` wird dann nur zur Dokumentation der OpenAPI-Pfadoperation* Es könnte zum Beispiel so etwas sein: -```Python hl_lines="7 21 23" -{!../../docs_src/custom_response/tutorial004.py!} -``` +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} In diesem Beispiel generiert die Funktion `generate_html_response()` bereits eine `Response` und gibt sie zurück, anstatt das HTML in einem `str` zurückzugeben. @@ -144,9 +136,7 @@ Sie akzeptiert die folgenden Parameter: FastAPI (eigentlich Starlette) fügt automatisch einen Content-Length-Header ein. Außerdem wird es einen Content-Type-Header einfügen, der auf dem media_type basiert, und für Texttypen einen Zeichensatz (charset) anfügen. -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ### `HTMLResponse` @@ -156,9 +146,7 @@ Nimmt Text oder Bytes entgegen und gibt eine HTML-Response zurück, wie Sie oben Nimmt Text oder Bytes entgegen und gibt eine Plain-Text-Response zurück. -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial005.py!} -``` +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} ### `JSONResponse` @@ -180,9 +168,7 @@ Eine alternative JSON-Response mit ../../docs_src/generate_clients/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../docs_src/generate_clients/tutorial001.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *} Beachten Sie, dass die *Pfadoperationen* die Modelle definieren, welche diese für die Request- und Response-Payload verwenden, indem sie die Modelle `Item` und `ResponseMessage` verwenden. @@ -147,21 +133,7 @@ In vielen Fällen wird Ihre FastAPI-Anwendung größer sein und Sie werden wahrs Beispielsweise könnten Sie einen Abschnitt für **Items (Artikel)** und einen weiteren Abschnitt für **Users (Benutzer)** haben, und diese könnten durch Tags getrennt sein: -//// tab | Python 3.9+ - -```Python hl_lines="21 26 34" -{!> ../../docs_src/generate_clients/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23 28 36" -{!> ../../docs_src/generate_clients/tutorial002.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *} ### Einen TypeScript-Client mit Tags generieren @@ -208,21 +180,7 @@ Hier verwendet sie beispielsweise den ersten Tag (Sie werden wahrscheinlich nur Anschließend können Sie diese benutzerdefinierte Funktion als Parameter `generate_unique_id_function` an **FastAPI** übergeben: -//// tab | Python 3.9+ - -```Python hl_lines="6-7 10" -{!> ../../docs_src/generate_clients/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8-9 12" -{!> ../../docs_src/generate_clients/tutorial003.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *} ### Einen TypeScript-Client mit benutzerdefinierten Operation-IDs generieren @@ -244,13 +202,7 @@ Aber für den generierten Client könnten wir die OpenAPI-Operation-IDs direkt v Wir könnten das OpenAPI-JSON in eine Datei `openapi.json` herunterladen und dann mit einem Skript wie dem folgenden **den vorangestellten Tag entfernen**: -//// tab | Python - -```Python -{!> ../../docs_src/generate_clients/tutorial004.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial004.py *} //// tab | Node.js diff --git a/docs/de/docs/advanced/middleware.md b/docs/de/docs/advanced/middleware.md index d2130c9b7..17b339788 100644 --- a/docs/de/docs/advanced/middleware.md +++ b/docs/de/docs/advanced/middleware.md @@ -57,17 +57,13 @@ Erzwingt, dass alle eingehenden Requests entweder `https` oder `wss` sein müsse Alle eingehenden Requests an `http` oder `ws` werden stattdessen an das sichere Schema umgeleitet. -```Python hl_lines="2 6" -{!../../docs_src/advanced_middleware/tutorial001.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} ## `TrustedHostMiddleware` Erzwingt, dass alle eingehenden Requests einen korrekt gesetzten `Host`-Header haben, um sich vor HTTP-Host-Header-Angriffen zu schützen. -```Python hl_lines="2 6-8" -{!../../docs_src/advanced_middleware/tutorial002.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} Die folgenden Argumente werden unterstützt: @@ -81,9 +77,7 @@ Verarbeitet GZip-Responses für alle Requests, die `"gzip"` im `Accept-Encoding` Diese Middleware verarbeitet sowohl Standard- als auch Streaming-Responses. -```Python hl_lines="2 6" -{!../../docs_src/advanced_middleware/tutorial003.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} Die folgenden Argumente werden unterstützt: diff --git a/docs/de/docs/advanced/openapi-callbacks.md b/docs/de/docs/advanced/openapi-callbacks.md index 4ee2874a3..53f06e24e 100644 --- a/docs/de/docs/advanced/openapi-callbacks.md +++ b/docs/de/docs/advanced/openapi-callbacks.md @@ -31,9 +31,7 @@ Sie verfügt über eine *Pfadoperation*, die einen `Invoice`-Body empfängt, und Dieser Teil ist ziemlich normal, der größte Teil des Codes ist Ihnen wahrscheinlich bereits bekannt: -```Python hl_lines="9-13 36-53" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *} /// tip | Tipp @@ -92,9 +90,7 @@ Wenn Sie diese Sichtweise (des *externen Entwicklers*) vorübergehend übernehme Erstellen Sie zunächst einen neuen `APIRouter`, der einen oder mehrere Callbacks enthält. -```Python hl_lines="3 25" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *} ### Die Callback-*Pfadoperation* erstellen @@ -105,9 +101,7 @@ Sie sollte wie eine normale FastAPI-*Pfadoperation* aussehen: * Sie sollte wahrscheinlich eine Deklaration des Bodys enthalten, die sie erhalten soll, z. B. `body: InvoiceEvent`. * Und sie könnte auch eine Deklaration der Response enthalten, die zurückgegeben werden soll, z. B. `response_model=InvoiceEventReceived`. -```Python hl_lines="16-18 21-22 28-32" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *} Es gibt zwei Hauptunterschiede zu einer normalen *Pfadoperation*: @@ -175,9 +169,7 @@ An diesem Punkt haben Sie die benötigte(n) *Callback-Pfadoperation(en)* (diejen Verwenden Sie nun den Parameter `callbacks` im *Pfadoperation-Dekorator Ihrer API*, um das Attribut `.routes` (das ist eigentlich nur eine `list`e von Routen/*Pfadoperationen*) dieses Callback-Routers zu übergeben: -```Python hl_lines="35" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *} /// tip | Tipp diff --git a/docs/de/docs/advanced/openapi-webhooks.md b/docs/de/docs/advanced/openapi-webhooks.md index 9f1bb6959..50b95eaf8 100644 --- a/docs/de/docs/advanced/openapi-webhooks.md +++ b/docs/de/docs/advanced/openapi-webhooks.md @@ -32,9 +32,7 @@ Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.9 Wenn Sie eine **FastAPI**-Anwendung erstellen, gibt es ein `webhooks`-Attribut, mit dem Sie *Webhooks* definieren können, genauso wie Sie *Pfadoperationen* definieren würden, zum Beispiel mit `@app.webhooks.post()`. -```Python hl_lines="9-13 36-53" -{!../../docs_src/openapi_webhooks/tutorial001.py!} -``` +{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *} Die von Ihnen definierten Webhooks landen im **OpenAPI**-Schema und der automatischen **Dokumentations-Oberfläche**. diff --git a/docs/de/docs/advanced/path-operation-advanced-configuration.md b/docs/de/docs/advanced/path-operation-advanced-configuration.md index 53d395724..b6e88d2c9 100644 --- a/docs/de/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/de/docs/advanced/path-operation-advanced-configuration.md @@ -12,9 +12,7 @@ Mit dem Parameter `operation_id` können Sie die OpenAPI `operationId` festlegen Sie müssten sicherstellen, dass sie für jede Operation eindeutig ist. -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### Verwendung des Namens der *Pfadoperation-Funktion* als operationId @@ -22,9 +20,7 @@ Wenn Sie die Funktionsnamen Ihrer API als `operationId`s verwenden möchten, kö Sie sollten dies tun, nachdem Sie alle Ihre *Pfadoperationen* hinzugefügt haben. -```Python hl_lines="2 12-21 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *} /// tip | Tipp @@ -44,9 +40,7 @@ Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden. Um eine *Pfadoperation* aus dem generierten OpenAPI-Schema (und damit aus den automatischen Dokumentationssystemen) auszuschließen, verwenden Sie den Parameter `include_in_schema` und setzen Sie ihn auf `False`: -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## Fortgeschrittene Beschreibung mittels Docstring @@ -56,9 +50,7 @@ Das Hinzufügen eines `\f` (ein maskiertes „Form Feed“-Zeichen) führt dazu, Sie wird nicht in der Dokumentation angezeigt, aber andere Tools (z. B. Sphinx) können den Rest verwenden. -```Python hl_lines="19-29" -{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} ## Zusätzliche Responses @@ -100,9 +92,7 @@ Sie können das OpenAPI-Schema für eine *Pfadoperation* erweitern, indem Sie de Dieses `openapi_extra` kann beispielsweise hilfreich sein, um OpenAPI-Erweiterungen zu deklarieren: -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} Wenn Sie die automatische API-Dokumentation öffnen, wird Ihre Erweiterung am Ende der spezifischen *Pfadoperation* angezeigt. @@ -149,9 +139,7 @@ Sie könnten sich beispielsweise dafür entscheiden, den Request mit Ihrem eigen Das könnte man mit `openapi_extra` machen: -```Python hl_lines="20-37 39-40" -{!../../docs_src/path_operation_advanced_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[20:37,39:40] *} In diesem Beispiel haben wir kein Pydantic-Modell deklariert. Tatsächlich wird der Requestbody nicht einmal als JSON geparst, sondern direkt als `bytes` gelesen und die Funktion `magic_data_reader ()` wäre dafür verantwortlich, ihn in irgendeiner Weise zu parsen. @@ -167,17 +155,13 @@ In der folgenden Anwendung verwenden wir beispielsweise weder die integrierte Fu //// tab | Pydantic v2 -```Python hl_lines="17-22 24" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *} //// //// tab | Pydantic v1 -```Python hl_lines="17-22 24" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[17:22,24] *} //// @@ -195,17 +179,13 @@ Und dann parsen wir in unserem Code diesen YAML-Inhalt direkt und verwenden dann //// tab | Pydantic v2 -```Python hl_lines="26-33" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} //// //// tab | Pydantic v1 -```Python hl_lines="26-33" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[26:33] *} //// diff --git a/docs/de/docs/advanced/response-change-status-code.md b/docs/de/docs/advanced/response-change-status-code.md index 202df0d87..0aac32f4e 100644 --- a/docs/de/docs/advanced/response-change-status-code.md +++ b/docs/de/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* Anschließend können Sie den `status_code` in diesem *vorübergehenden* Response-Objekt festlegen. -```Python hl_lines="1 9 12" -{!../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} Und dann können Sie wie gewohnt jedes benötigte Objekt zurückgeben (ein `dict`, ein Datenbankmodell usw.). diff --git a/docs/de/docs/advanced/response-cookies.md b/docs/de/docs/advanced/response-cookies.md index 6f9d66e07..5fe2cf7e3 100644 --- a/docs/de/docs/advanced/response-cookies.md +++ b/docs/de/docs/advanced/response-cookies.md @@ -6,9 +6,7 @@ Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* Und dann können Sie Cookies in diesem *vorübergehenden* Response-Objekt setzen. -```Python hl_lines="1 8-9" -{!../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} Anschließend können Sie wie gewohnt jedes gewünschte Objekt zurückgeben (ein `dict`, ein Datenbankmodell, usw.). @@ -26,9 +24,7 @@ Dazu können Sie eine Response erstellen, wie unter [Eine Response direkt zurüc Setzen Sie dann Cookies darin und geben Sie sie dann zurück: -```Python hl_lines="10-12" -{!../../docs_src/response_cookies/tutorial001.py!} -``` +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} /// tip | Tipp diff --git a/docs/de/docs/advanced/response-directly.md b/docs/de/docs/advanced/response-directly.md index fab2e3965..b84aa8ab9 100644 --- a/docs/de/docs/advanced/response-directly.md +++ b/docs/de/docs/advanced/response-directly.md @@ -34,9 +34,7 @@ Sie können beispielsweise kein Pydantic-Modell in eine `JSONResponse` einfügen In diesen Fällen können Sie den `jsonable_encoder` verwenden, um Ihre Daten zu konvertieren, bevor Sie sie an eine Response übergeben: -```Python hl_lines="6-7 21-22" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} /// note | Technische Details @@ -56,9 +54,7 @@ Nehmen wir an, Sie möchten eine ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[4,8,12,46,64,105,107:115,121:124,128:134,139,155] *} Sehen wir uns diese Änderungen nun Schritt für Schritt an. @@ -136,71 +72,7 @@ Die erste Änderung ist, dass wir jetzt das OAuth2-Sicherheitsschema mit zwei ve Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und dessen Beschreibung als Wert: -//// tab | Python 3.10+ - -```Python hl_lines="62-65" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="62-65" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="61-64" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="62-65" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="62-65" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[62:65] *} Da wir diese Scopes jetzt deklarieren, werden sie in der API-Dokumentation angezeigt, wenn Sie sich einloggen/autorisieren. @@ -226,71 +98,7 @@ Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwe /// -//// tab | Python 3.10+ - -```Python hl_lines="155" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="155" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="154" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="155" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="155" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[155] *} ## Scopes in *Pfadoperationen* und Abhängigkeiten deklarieren @@ -316,71 +124,7 @@ Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen /// -//// tab | Python 3.10+ - -```Python hl_lines="4 139 170" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 139 170" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 140 171" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="3 138 167" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="4 139 168" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="4 139 168" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[4,139,170] *} /// info | Technische Details @@ -406,71 +150,7 @@ Wir deklarieren auch einen speziellen Parameter vom Typ `SecurityScopes`, der au Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um das Request-Objekt direkt zu erhalten). -//// tab | Python 3.10+ - -```Python hl_lines="8 105" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8 105" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 106" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7 104" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8 105" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8 105" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[8,105] *} ## Die `scopes` verwenden @@ -484,71 +164,7 @@ Wir erstellen eine `HTTPException`, die wir später an mehreren Stellen wiederve In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als durch Leerzeichen getrennten String ein (unter Verwendung von `scope_str`). Wir fügen diesen String mit den Scopes in den Header `WWW-Authenticate` ein (das ist Teil der Spezifikation). -//// tab | Python 3.10+ - -```Python hl_lines="105 107-115" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="105 107-115" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="104 106-114" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="105 107-115" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="105 107-115" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[105,107:115] *} ## Den `username` und das Format der Daten überprüfen @@ -564,71 +180,7 @@ Anstelle beispielsweise eines `dict`s oder etwas anderem, was später in der Anw Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, und wenn nicht, lösen wir dieselbe Exception aus, die wir zuvor erstellt haben. -//// tab | Python 3.10+ - -```Python hl_lines="46 116-127" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="46 116-127" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="45 115-126" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="46 116-127" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="46 116-127" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[46,116:127] *} ## Die `scopes` verifizieren @@ -636,71 +188,7 @@ Wir überprüfen nun, ob das empfangenen Token alle Scopes enthält, die von die Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen Scopes als `str` enthält. -//// tab | Python 3.10+ - -```Python hl_lines="128-134" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="128-134" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="127-133" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="128-134" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="128-134" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[128:134] *} ## Abhängigkeitsbaum und Scopes diff --git a/docs/de/docs/advanced/settings.md b/docs/de/docs/advanced/settings.md index c90f74844..00cc2ac37 100644 --- a/docs/de/docs/advanced/settings.md +++ b/docs/de/docs/advanced/settings.md @@ -180,9 +180,7 @@ Sie können dieselben Validierungs-Funktionen und -Tools verwenden, die Sie für //// tab | Pydantic v2 -```Python hl_lines="2 5-8 11" -{!> ../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} //// @@ -194,9 +192,7 @@ In Pydantic v1 würden Sie `BaseSettings` direkt von `pydantic` statt von `pydan /// -```Python hl_lines="2 5-8 11" -{!> ../../docs_src/settings/tutorial001_pv1.py!} -``` +{* ../../docs_src/settings/tutorial001_pv1.py hl[2,5:8,11] *} //// @@ -214,9 +210,7 @@ Als Nächstes werden die Daten konvertiert und validiert. Wenn Sie also dieses ` Dann können Sie das neue `settings`-Objekt in Ihrer Anwendung verwenden: -```Python hl_lines="18-20" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} ### Den Server ausführen @@ -250,15 +244,11 @@ Sie könnten diese Einstellungen in eine andere Moduldatei einfügen, wie Sie in Sie könnten beispielsweise eine Datei `config.py` haben mit: -```Python -{!../../docs_src/settings/app01/config.py!} -``` +{* ../../docs_src/settings/app01/config.py *} Und dann verwenden Sie diese in einer Datei `main.py`: -```Python hl_lines="3 11-13" -{!../../docs_src/settings/app01/main.py!} -``` +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} /// tip | Tipp @@ -276,9 +266,7 @@ Dies könnte besonders beim Testen nützlich sein, da es sehr einfach ist, eine Ausgehend vom vorherigen Beispiel könnte Ihre Datei `config.py` so aussehen: -```Python hl_lines="10" -{!../../docs_src/settings/app02/config.py!} -``` +{* ../../docs_src/settings/app02/config.py hl[10] *} Beachten Sie, dass wir jetzt keine Standardinstanz `settings = Settings()` erstellen. @@ -286,35 +274,7 @@ Beachten Sie, dass wir jetzt keine Standardinstanz `settings = Settings()` erste Jetzt erstellen wir eine Abhängigkeit, die ein neues `config.Settings()` zurückgibt. -//// tab | Python 3.9+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="5 11-12" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *} /// tip | Tipp @@ -326,43 +286,13 @@ Im Moment nehmen Sie an, dass `get_settings()` eine normale Funktion ist. Und dann können wir das von der *Pfadoperation-Funktion* als Abhängigkeit einfordern und es überall dort verwenden, wo wir es brauchen. -//// tab | Python 3.9+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="16 18-20" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *} ### Einstellungen und Tests Dann wäre es sehr einfach, beim Testen ein anderes Einstellungsobjekt bereitzustellen, indem man eine Abhängigkeitsüberschreibung für `get_settings` erstellt: -```Python hl_lines="9-10 13 21" -{!../../docs_src/settings/app02/test_main.py!} -``` +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} Bei der Abhängigkeitsüberschreibung legen wir einen neuen Wert für `admin_email` fest, wenn wir das neue `Settings`-Objekt erstellen, und geben dann dieses neue Objekt zurück. @@ -405,9 +335,7 @@ Und dann aktualisieren Sie Ihre `config.py` mit: //// tab | Pydantic v2 -```Python hl_lines="9" -{!> ../../docs_src/settings/app03_an/config.py!} -``` +{* ../../docs_src/settings/app03_an/config.py hl[9] *} /// tip | Tipp @@ -419,9 +347,7 @@ Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. //// tab | Pydantic v1 -```Python hl_lines="9-10" -{!> ../../docs_src/settings/app03_an/config_pv1.py!} -``` +{* ../../docs_src/settings/app03_an/config_pv1.py hl[9:10] *} /// tip | Tipp @@ -462,35 +388,7 @@ würden wir dieses Objekt für jeden Request erstellen und die `.env`-Datei für Da wir jedoch den `@lru_cache`-Dekorator oben verwenden, wird das `Settings`-Objekt nur einmal erstellt, nämlich beim ersten Aufruf. ✔️ -//// tab | Python 3.9+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1 10" -{!> ../../docs_src/settings/app03/main.py!} -``` - -//// +{* ../../docs_src/settings/app03_an_py39/main.py hl[1,11] *} Dann wird bei allen nachfolgenden Aufrufen von `get_settings()`, in den Abhängigkeiten für darauffolgende Requests, dasselbe Objekt zurückgegeben, das beim ersten Aufruf zurückgegeben wurde, anstatt den Code von `get_settings()` erneut auszuführen und ein neues `Settings`-Objekt zu erstellen. diff --git a/docs/de/docs/advanced/sub-applications.md b/docs/de/docs/advanced/sub-applications.md index 172b8d3c1..f123147b3 100644 --- a/docs/de/docs/advanced/sub-applications.md +++ b/docs/de/docs/advanced/sub-applications.md @@ -10,9 +10,7 @@ Wenn Sie zwei unabhängige FastAPI-Anwendungen mit deren eigenen unabhängigen O Erstellen Sie zunächst die Hauptanwendung **FastAPI** und deren *Pfadoperationen*: -```Python hl_lines="3 6-8" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[3,6:8] *} ### Unteranwendung @@ -20,9 +18,7 @@ Erstellen Sie dann Ihre Unteranwendung und deren *Pfadoperationen*. Diese Unteranwendung ist nur eine weitere Standard-FastAPI-Anwendung, aber diese wird „gemountet“: -```Python hl_lines="11 14-16" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,14:16] *} ### Die Unteranwendung mounten @@ -30,9 +26,7 @@ Mounten Sie in Ihrer Top-Level-Anwendung `app` die Unteranwendung `subapi`. In diesem Fall wird sie im Pfad `/subapi` gemountet: -```Python hl_lines="11 19" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,19] *} ### Es in der automatischen API-Dokumentation betrachten diff --git a/docs/de/docs/advanced/templates.md b/docs/de/docs/advanced/templates.md index 658a2592e..136ce6027 100644 --- a/docs/de/docs/advanced/templates.md +++ b/docs/de/docs/advanced/templates.md @@ -27,9 +27,7 @@ $ pip install jinja2 * Deklarieren Sie einen `Request`-Parameter in der *Pfadoperation*, welcher ein Template zurückgibt. * Verwenden Sie die von Ihnen erstellten `templates`, um eine `TemplateResponse` zu rendern und zurückzugeben, übergeben Sie den Namen des Templates, das Requestobjekt und ein „Kontext“-Dictionary mit Schlüssel-Wert-Paaren, die innerhalb des Jinja2-Templates verwendet werden sollen. -```Python hl_lines="4 11 15-18" -{!../../docs_src/templates/tutorial001.py!} -``` +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *} /// note | Hinweis diff --git a/docs/de/docs/advanced/testing-dependencies.md b/docs/de/docs/advanced/testing-dependencies.md index 3b4604da3..8299d6dd7 100644 --- a/docs/de/docs/advanced/testing-dependencies.md +++ b/docs/de/docs/advanced/testing-dependencies.md @@ -28,57 +28,7 @@ Um eine Abhängigkeit für das Testen zu überschreiben, geben Sie als Schlüsse Und dann ruft **FastAPI** diese Überschreibung anstelle der ursprünglichen Abhängigkeit auf. -//// tab | Python 3.10+ - -```Python hl_lines="26-27 30" -{!> ../../docs_src/dependency_testing/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="28-29 32" -{!> ../../docs_src/dependency_testing/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="29-30 33" -{!> ../../docs_src/dependency_testing/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="24-25 28" -{!> ../../docs_src/dependency_testing/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="28-29 32" -{!> ../../docs_src/dependency_testing/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependency_testing/tutorial001_an_py310.py hl[26:27,30] *} /// tip | Tipp diff --git a/docs/de/docs/advanced/testing-events.md b/docs/de/docs/advanced/testing-events.md index 3e63791c6..05d6bcb2b 100644 --- a/docs/de/docs/advanced/testing-events.md +++ b/docs/de/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ Wenn Sie in Ihren Tests Ihre Event-Handler (`startup` und `shutdown`) ausführen wollen, können Sie den `TestClient` mit einer `with`-Anweisung verwenden: -```Python hl_lines="9-12 20-24" -{!../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/de/docs/advanced/testing-websockets.md b/docs/de/docs/advanced/testing-websockets.md index 5122e1f33..5932e6d6a 100644 --- a/docs/de/docs/advanced/testing-websockets.md +++ b/docs/de/docs/advanced/testing-websockets.md @@ -4,9 +4,7 @@ Sie können den schon bekannten `TestClient` zum Testen von WebSockets verwenden Dazu verwenden Sie den `TestClient` in einer `with`-Anweisung, eine Verbindung zum WebSocket herstellend: -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} /// note | Hinweis diff --git a/docs/de/docs/advanced/websockets.md b/docs/de/docs/advanced/websockets.md index 5bc5f6902..020c20bc0 100644 --- a/docs/de/docs/advanced/websockets.md +++ b/docs/de/docs/advanced/websockets.md @@ -38,17 +38,13 @@ In der Produktion hätten Sie eine der oben genannten Optionen. Aber es ist die einfachste Möglichkeit, sich auf die Serverseite von WebSockets zu konzentrieren und ein funktionierendes Beispiel zu haben: -```Python hl_lines="2 6-38 41-43" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} ## Einen `websocket` erstellen Erstellen Sie in Ihrer **FastAPI**-Anwendung einen `websocket`: -```Python hl_lines="1 46-47" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} /// note | Technische Details @@ -62,9 +58,7 @@ Sie können auch `from starlette.websockets import WebSocket` verwenden. In Ihrer WebSocket-Route können Sie Nachrichten `await`en und Nachrichten senden. -```Python hl_lines="48-52" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} Sie können Binär-, Text- und JSON-Daten empfangen und senden. @@ -115,57 +109,7 @@ In WebSocket-Endpunkten können Sie Folgendes aus `fastapi` importieren und verw Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfadoperationen*: -//// tab | Python 3.10+ - -```Python hl_lines="68-69 82" -{!> ../../docs_src/websockets/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="68-69 82" -{!> ../../docs_src/websockets/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="69-70 83" -{!> ../../docs_src/websockets/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="66-67 79" -{!> ../../docs_src/websockets/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="68-69 81" -{!> ../../docs_src/websockets/tutorial002.py!} -``` - -//// +{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *} /// info @@ -210,21 +154,7 @@ Damit können Sie den WebSocket verbinden und dann Nachrichten senden und empfan Wenn eine WebSocket-Verbindung geschlossen wird, löst `await websocket.receive_text()` eine `WebSocketDisconnect`-Exception aus, die Sie dann wie in folgendem Beispiel abfangen und behandeln können. -//// tab | Python 3.9+ - -```Python hl_lines="79-81" -{!> ../../docs_src/websockets/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="81-83" -{!> ../../docs_src/websockets/tutorial003.py!} -``` - -//// +{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *} Zum Ausprobieren: diff --git a/docs/de/docs/advanced/wsgi.md b/docs/de/docs/advanced/wsgi.md index 50abc84d1..c0998a621 100644 --- a/docs/de/docs/advanced/wsgi.md +++ b/docs/de/docs/advanced/wsgi.md @@ -12,9 +12,7 @@ Wrappen Sie dann die WSGI-Anwendung (z. B. Flask) mit der Middleware. Und dann mounten Sie das auf einem Pfad. -```Python hl_lines="2-3 23" -{!../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,23] *} ## Es ansehen diff --git a/docs/de/docs/how-to/custom-docs-ui-assets.md b/docs/de/docs/how-to/custom-docs-ui-assets.md index a292be69b..ab8cd9f6b 100644 --- a/docs/de/docs/how-to/custom-docs-ui-assets.md +++ b/docs/de/docs/how-to/custom-docs-ui-assets.md @@ -18,9 +18,7 @@ Der erste Schritt besteht darin, die automatischen Dokumentationen zu deaktivier Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: -```Python hl_lines="8" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} ### Die benutzerdefinierten Dokumentationen hinzufügen @@ -36,9 +34,7 @@ Sie können die internen Funktionen von FastAPI wiederverwenden, um die HTML-Sei Und genau so für ReDoc ... -```Python hl_lines="2-6 11-19 22-24 27-33" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} /// tip | Tipp @@ -54,9 +50,7 @@ Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „U Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: -```Python hl_lines="36-38" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} ### Es ausprobieren @@ -124,9 +118,7 @@ Danach könnte Ihre Dateistruktur wie folgt aussehen: * Importieren Sie `StaticFiles`. * „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad. -```Python hl_lines="7 11" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} ### Die statischen Dateien testen @@ -158,9 +150,7 @@ Wie bei der Verwendung eines benutzerdefinierten CDN besteht der erste Schritt d Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: -```Python hl_lines="9" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} ### Die benutzerdefinierten Dokumentationen, mit statischen Dateien, hinzufügen @@ -176,9 +166,7 @@ Auch hier können Sie die internen Funktionen von FastAPI wiederverwenden, um di Und genau so für ReDoc ... -```Python hl_lines="2-6 14-22 25-27 30-36" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} /// tip | Tipp @@ -194,9 +182,7 @@ Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „U Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: -```Python hl_lines="39-41" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} ### Benutzeroberfläche, mit statischen Dateien, testen diff --git a/docs/de/docs/how-to/custom-request-and-route.md b/docs/de/docs/how-to/custom-request-and-route.md index ef71d96dc..3e6f709b6 100644 --- a/docs/de/docs/how-to/custom-request-and-route.md +++ b/docs/de/docs/how-to/custom-request-and-route.md @@ -42,9 +42,7 @@ Wenn der Header kein `gzip` enthält, wird nicht versucht, den Body zu dekomprim Auf diese Weise kann dieselbe Routenklasse gzip-komprimierte oder unkomprimierte Requests verarbeiten. -```Python hl_lines="8-15" -{!../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[8:15] *} ### Eine benutzerdefinierte `GzipRoute`-Klasse erstellen @@ -56,9 +54,7 @@ Diese Methode gibt eine Funktion zurück. Und diese Funktion empfängt einen Req Hier verwenden wir sie, um aus dem ursprünglichen Request einen `GzipRequest` zu erstellen. -```Python hl_lines="18-26" -{!../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[18:26] *} /// note | Technische Details @@ -96,26 +92,18 @@ Wir können denselben Ansatz auch verwenden, um in einem Exceptionhandler auf de Alles, was wir tun müssen, ist, den Request innerhalb eines `try`/`except`-Blocks zu handhaben: -```Python hl_lines="13 15" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[13,15] *} Wenn eine Exception auftritt, befindet sich die `Request`-Instanz weiterhin im Gültigkeitsbereich, sodass wir den Requestbody lesen und bei der Fehlerbehandlung verwenden können: -```Python hl_lines="16-18" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[16:18] *} ## Benutzerdefinierte `APIRoute`-Klasse in einem Router Sie können auch den Parameter `route_class` eines `APIRouter` festlegen: -```Python hl_lines="26" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[26] *} In diesem Beispiel verwenden die *Pfadoperationen* unter dem `router` die benutzerdefinierte `TimedRoute`-Klasse und haben in der Response einen zusätzlichen `X-Response-Time`-Header mit der Zeit, die zum Generieren der Response benötigt wurde: -```Python hl_lines="13-20" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[13:20] *} diff --git a/docs/de/docs/how-to/extending-openapi.md b/docs/de/docs/how-to/extending-openapi.md index c895fb860..3b1459364 100644 --- a/docs/de/docs/how-to/extending-openapi.md +++ b/docs/de/docs/how-to/extending-openapi.md @@ -43,25 +43,19 @@ Fügen wir beispielsweise Strawberry-Dokumentation. diff --git a/docs/de/docs/how-to/separate-openapi-schemas.md b/docs/de/docs/how-to/separate-openapi-schemas.md index 974341dd2..4f6911e79 100644 --- a/docs/de/docs/how-to/separate-openapi-schemas.md +++ b/docs/de/docs/how-to/separate-openapi-schemas.md @@ -10,123 +10,13 @@ Sehen wir uns an, wie das funktioniert und wie Sie es bei Bedarf ändern können Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} - -# Code unterhalb weggelassen 👇 -``` - -
-👀 Vollständige Dateivorschau - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -
- -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} - -# Code unterhalb weggelassen 👇 -``` - -
-👀 Vollständige Dateivorschau - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -
- -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} - -# Code unterhalb weggelassen 👇 -``` - -
-👀 Vollständige Dateivorschau - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -
- -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *} ### Modell für Eingabe Wenn Sie dieses Modell wie hier als Eingabe verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="14" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} - -# Code unterhalb weggelassen 👇 -``` - -
-👀 Vollständige Dateivorschau - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -
- -//// - -//// tab | Python 3.9+ - -```Python hl_lines="16" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} - -# Code unterhalb weggelassen 👇 -``` - -
-👀 Vollständige Dateivorschau - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -
- -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} - -# Code unterhalb weggelassen 👇 -``` - -
-👀 Vollständige Dateivorschau - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -
- -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *} ... dann ist das Feld `description` **nicht erforderlich**. Weil es den Defaultwert `None` hat. @@ -142,29 +32,7 @@ Sie können überprüfen, dass das Feld `description` in der Dokumentation kein Wenn Sie jedoch dasselbe Modell als Ausgabe verwenden, wie hier: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="21" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py hl[19] *} ... dann, weil `description` einen Defaultwert hat, wird es, wenn Sie für dieses Feld **nichts zurückgeben**, immer noch diesen **Defaultwert** haben. @@ -223,29 +91,7 @@ Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` h /// -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/separate_openapi_schemas/tutorial002.py!} -``` - -//// +{* ../../docs_src/separate_openapi_schemas/tutorial002_py310.py hl[10] *} ### Gleiches Schema für Eingabe- und Ausgabemodelle in der Dokumentation diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md index fc699daf4..05779e12c 100644 --- a/docs/de/docs/tutorial/background-tasks.md +++ b/docs/de/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ Hierzu zählen beispielsweise: Importieren Sie zunächst `BackgroundTasks` und definieren Sie einen Parameter in Ihrer *Pfadoperation-Funktion* mit der Typdeklaration `BackgroundTasks`: -```Python hl_lines="1 13" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** erstellt für Sie das Objekt vom Typ `BackgroundTasks` und übergibt es als diesen Parameter. @@ -33,17 +31,13 @@ In diesem Fall schreibt die Taskfunktion in eine Datei (den Versand einer E-Mail Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir die Funktion mit normalem `def`: -```Python hl_lines="6-9" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## Den Hintergrundtask hinzufügen Übergeben Sie innerhalb Ihrer *Pfadoperation-Funktion* Ihre Taskfunktion mit der Methode `.add_task()` an das *Hintergrundtasks*-Objekt: -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` erhält als Argumente: @@ -57,57 +51,7 @@ Die Verwendung von `BackgroundTasks` funktioniert auch mit dem ../../docs_src/background_tasks/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14 16 23 26" -{!> ../../docs_src/background_tasks/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11 13 20 23" -{!> ../../docs_src/background_tasks/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002.py!} -``` - -//// +{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *} In obigem Beispiel werden die Nachrichten, *nachdem* die Response gesendet wurde, in die Datei `log.txt` geschrieben. diff --git a/docs/de/docs/tutorial/body-fields.md b/docs/de/docs/tutorial/body-fields.md index df3d7f939..9fddfb1f0 100644 --- a/docs/de/docs/tutorial/body-fields.md +++ b/docs/de/docs/tutorial/body-fields.md @@ -6,57 +6,7 @@ So wie Sie zusätzliche Validation und Metadaten in Parametern der **Pfadoperati Importieren Sie es zuerst: -//// tab | Python 3.10+ - -```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+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="2" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} /// warning | Achtung @@ -68,57 +18,7 @@ Beachten Sie, dass `Field` direkt von `pydantic` importiert wird, nicht von `fas Dann können Sie `Field` mit Modellattributen deklarieren: -//// tab | Python 3.10+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} -``` - -//// - -//// 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+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9-12" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} `Field` funktioniert genauso wie `Query`, `Path` und `Body`, es hat die gleichen Parameter, usw. diff --git a/docs/de/docs/tutorial/body-nested-models.md b/docs/de/docs/tutorial/body-nested-models.md index 478064a8b..6287490c6 100644 --- a/docs/de/docs/tutorial/body-nested-models.md +++ b/docs/de/docs/tutorial/body-nested-models.md @@ -6,21 +6,7 @@ Mit **FastAPI** können Sie (dank Pydantic) beliebig tief verschachtelte Modelle Sie können ein Attribut als Kindtyp definieren, zum Beispiel eine Python-`list`e. -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} Das bewirkt, dass `tags` eine Liste ist, wenngleich es nichts über den Typ der Elemente der Liste aussagt. @@ -34,9 +20,7 @@ In Python 3.9 oder darüber können Sie einfach `list` verwenden, um diese Typan In Python-Versionen vor 3.9 (3.6 und darüber), müssen Sie zuerst `List` von Pythons Standardmodul `typing` importieren. -```Python hl_lines="1" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### Eine `list`e mit einem Typ-Parameter deklarieren @@ -65,29 +49,7 @@ Verwenden Sie dieselbe Standardsyntax für Modellattribute mit inneren Typen. In unserem Beispiel können wir also bewirken, dass `tags` spezifisch eine „Liste von Strings“ ist: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} ## Set-Typen @@ -97,29 +59,7 @@ Python hat einen Datentyp speziell für Mengen eindeutiger Dinge: das ../../docs_src/body_nested_models/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 14" -{!> ../../docs_src/body_nested_models/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} Jetzt, selbst wenn Sie einen Request mit duplizierten Daten erhalten, werden diese zu einem Set eindeutiger Dinge konvertiert. @@ -141,57 +81,13 @@ Alles das beliebig tief verschachtelt. Wir können zum Beispiel ein `Image`-Modell definieren. -//// tab | Python 3.10+ - -```Python hl_lines="7-9" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} ### Das Kindmodell als Typ verwenden Und dann können wir es als Typ eines Attributes verwenden. -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} Das würde bedeuten, dass **FastAPI** einen Body erwartet wie: @@ -224,29 +120,7 @@ Um alle Optionen kennenzulernen, die Sie haben, schauen Sie sich ../../docs_src/body_nested_models/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} Es wird getestet, ob der String eine gültige URL ist, und als solche wird er in JSON Schema / OpenAPI dokumentiert. @@ -254,29 +128,7 @@ Es wird getestet, ob der String eine gültige URL ist, und als solche wird er in Sie können Pydantic-Modelle auch als Typen innerhalb von `list`, `set`, usw. verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} Das wird einen JSON-Body erwarten (konvertieren, validieren, dokumentieren), wie: @@ -314,29 +166,7 @@ Beachten Sie, dass der `images`-Schlüssel jetzt eine Liste von Bild-Objekten ha Sie können beliebig tief verschachtelte Modelle definieren: -//// tab | Python 3.10+ - -```Python hl_lines="7 12 18 21 25" -{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} /// info @@ -360,21 +190,7 @@ images: list[Image] so wie in: -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/body_nested_models/tutorial008.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} ## Editor-Unterstützung überall @@ -404,21 +220,7 @@ Das schauen wir uns mal an. Im folgenden Beispiel akzeptieren Sie irgendein `dict`, solange es `int`-Schlüssel und `float`-Werte hat. -//// tab | Python 3.9+ - -```Python hl_lines="7" -{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/body_nested_models/tutorial009.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} /// tip | Tipp diff --git a/docs/de/docs/tutorial/body-updates.md b/docs/de/docs/tutorial/body-updates.md index 01a534a23..574016c58 100644 --- a/docs/de/docs/tutorial/body-updates.md +++ b/docs/de/docs/tutorial/body-updates.md @@ -6,29 +6,7 @@ Um einen Artikel zu aktualisieren, können Sie die ../../docs_src/body_updates/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *} `PUT` wird verwendet, um Daten zu empfangen, die die existierenden Daten ersetzen sollen. @@ -84,29 +62,7 @@ Das wird ein `dict` erstellen, mit nur den Daten, die gesetzt wurden als das `it Sie können das verwenden, um ein `dict` zu erstellen, das nur die (im Request) gesendeten Daten enthält, ohne Defaultwerte: -//// tab | Python 3.10+ - -```Python hl_lines="32" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *} ### Pydantics `update`-Parameter verwenden @@ -122,29 +78,7 @@ Die Beispiele hier verwenden `.copy()` für die Kompatibilität mit Pydantic v1, Wie in `stored_item_model.model_copy(update=update_data)`: -//// tab | Python 3.10+ - -```Python hl_lines="33" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *} ### Rekapitulation zum teilweisen Ersetzen @@ -161,29 +95,7 @@ Zusammengefasst, um Teil-Ersetzungen vorzunehmen: * Speichern Sie die Daten in Ihrer Datenbank. * Geben Sie das aktualisierte Modell zurück. -//// tab | Python 3.10+ - -```Python hl_lines="28-35" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *} /// tip | Tipp diff --git a/docs/de/docs/tutorial/body.md b/docs/de/docs/tutorial/body.md index 1038ebe91..e25323786 100644 --- a/docs/de/docs/tutorial/body.md +++ b/docs/de/docs/tutorial/body.md @@ -22,21 +22,7 @@ Da aber davon abgeraten wird, zeigt die interaktive Dokumentation mit Swagger-Be Zuerst müssen Sie `BaseModel` von `pydantic` importieren: -//// 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] *} ## Erstellen Sie Ihr Datenmodell @@ -44,21 +30,7 @@ Dann deklarieren Sie Ihr Datenmodell als eine Klasse, die von `BaseModel` erbt. Verwenden Sie Standard-Python-Typen für die Klassenattribute: -//// tab | Python 3.10+ - -```Python hl_lines="5-9" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7-11" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *} Wie auch bei Query-Parametern gilt, wenn ein Modellattribut einen Defaultwert hat, ist das Attribut nicht erforderlich. Ansonsten ist es erforderlich. Verwenden Sie `None`, um es als optional zu kennzeichnen. @@ -86,21 +58,7 @@ Da `description` und `tax` optional sind (mit `None` als Defaultwert), wäre fol Um es zu Ihrer *Pfadoperation* hinzuzufügen, deklarieren Sie es auf die gleiche Weise, wie Sie Pfad- und Query-Parameter deklariert haben: -//// 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] *} ... und deklarieren Sie seinen Typ als das Modell, welches Sie erstellt haben, `Item`. @@ -167,21 +125,7 @@ Es verbessert die Editor-Unterstützung für Pydantic-Modelle, mit: Innerhalb der Funktion können Sie alle Attribute des Modells direkt verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/body/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/body/tutorial002.py!} -``` - -//// +{* ../../docs_src/body/tutorial002_py310.py hl[19] *} ## Requestbody- + Pfad-Parameter @@ -189,21 +133,7 @@ Sie können Pfad- und Requestbody-Parameter gleichzeitig deklarieren. **FastAPI** erkennt, dass Funktionsparameter, die mit Pfad-Parametern übereinstimmen, **vom Pfad genommen** werden sollen, und dass Funktionsparameter, welche Pydantic-Modelle sind, **vom Requestbody genommen** werden sollen. -//// tab | Python 3.10+ - -```Python hl_lines="15-16" -{!> ../../docs_src/body/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17-18" -{!> ../../docs_src/body/tutorial003.py!} -``` - -//// +{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *} ## Requestbody- + Pfad- + Query-Parameter @@ -211,21 +141,7 @@ Sie können auch zur gleichen Zeit **Body-**, **Pfad-** und **Query-Parameter** **FastAPI** wird jeden Parameter korrekt erkennen und die Daten vom richtigen Ort holen. -//// 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] *} Die Funktionsparameter werden wie folgt erkannt: diff --git a/docs/de/docs/tutorial/cookie-params.md b/docs/de/docs/tutorial/cookie-params.md index ecb14ad03..711c8c8e9 100644 --- a/docs/de/docs/tutorial/cookie-params.md +++ b/docs/de/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ So wie `Query`- und `Path`-Parameter können Sie auch ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} ### Deklarieren der Abhängigkeit im „Dependant“ So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ihrer *Pfadoperation-Funktion*: -//// 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+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} Obwohl Sie `Depends` in den Parametern Ihrer Funktion genauso verwenden wie `Body`, `Query`, usw., funktioniert `Depends` etwas anders. @@ -275,29 +125,7 @@ commons: Annotated[dict, Depends(common_parameters)] Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in einer Variablen speichern und an mehreren Stellen verwenden: -//// 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 | Tipp diff --git a/docs/de/docs/tutorial/dependencies/sub-dependencies.md b/docs/de/docs/tutorial/dependencies/sub-dependencies.md index 6da7c64de..66bdc7043 100644 --- a/docs/de/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/de/docs/tutorial/dependencies/sub-dependencies.md @@ -10,57 +10,7 @@ Diese können so **tief** verschachtelt sein, wie nötig. Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen: -//// tab | Python 3.10+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-10" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *} Diese deklariert einen optionalen Abfrageparameter `q` vom Typ `str` und gibt ihn dann einfach zurück. @@ -70,57 +20,7 @@ Das ist recht einfach (nicht sehr nützlich), hilft uns aber dabei, uns auf die Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erstellen, die gleichzeitig eine eigene Abhängigkeit deklariert (also auch ein „Dependant“ ist): -//// tab | Python 3.10+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *} Betrachten wir die deklarierten Parameter: @@ -133,57 +33,7 @@ Betrachten wir die deklarierten Parameter: Diese Abhängigkeit verwenden wir nun wie folgt: -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *} /// info diff --git a/docs/de/docs/tutorial/encoder.md b/docs/de/docs/tutorial/encoder.md index 428eee287..5678d7b8f 100644 --- a/docs/de/docs/tutorial/encoder.md +++ b/docs/de/docs/tutorial/encoder.md @@ -20,21 +20,7 @@ Sie können für diese Fälle `jsonable_encoder` verwenden. Es nimmt ein Objekt entgegen, wie etwa ein Pydantic-Modell, und gibt eine JSON-kompatible Version zurück: -//// 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 diesem Beispiel wird das Pydantic-Modell in ein `dict`, und das `datetime`-Objekt in ein `str` konvertiert. diff --git a/docs/de/docs/tutorial/extra-data-types.md b/docs/de/docs/tutorial/extra-data-types.md index 7581b4f87..334f32f7b 100644 --- a/docs/de/docs/tutorial/extra-data-types.md +++ b/docs/de/docs/tutorial/extra-data-types.md @@ -55,108 +55,8 @@ Hier sind einige der zusätzlichen Datentypen, die Sie verwenden können: Hier ist ein Beispiel für eine *Pfadoperation* mit Parametern, die einige der oben genannten Typen verwenden. -//// tab | Python 3.10+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 3 13-17" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1 2 11-15" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1 2 12-16" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Datentyp haben und Sie beispielsweise normale Datumsmanipulationen durchführen können, wie zum Beispiel: -//// tab | Python 3.10+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-20" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="17-18" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/de/docs/tutorial/extra-models.md b/docs/de/docs/tutorial/extra-models.md index 4c2c158db..6aad1c0f4 100644 --- a/docs/de/docs/tutorial/extra-models.md +++ b/docs/de/docs/tutorial/extra-models.md @@ -20,21 +20,7 @@ Falls Ihnen das nichts sagt, in den [Sicherheits-Kapiteln](security/simple-oauth Hier der generelle Weg, wie die Modelle mit ihren Passwort-Feldern aussehen könnten, und an welchen Orten sie verwendet werden würden. -//// tab | Python 3.10+ - -```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../docs_src/extra_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../docs_src/extra_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *} /// info @@ -176,21 +162,7 @@ Die ganze Datenkonvertierung, -validierung, -dokumentation, usw. wird immer noch Auf diese Weise beschreiben wir nur noch die Unterschiede zwischen den Modellen (mit Klartext-`password`, mit `hashed_password`, und ohne Passwort): -//// tab | Python 3.10+ - -```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../docs_src/extra_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../docs_src/extra_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *} ## `Union`, oder `anyOf` @@ -206,21 +178,7 @@ Listen Sie, wenn Sie eine ../../docs_src/extra_models/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *} ### `Union` in Python 3.10 @@ -242,21 +200,7 @@ Genauso können Sie eine Response deklarieren, die eine Liste von Objekten ist. Verwenden Sie dafür Pythons Standard `typing.List` (oder nur `list` in Python 3.9 und darüber): -//// tab | Python 3.9+ - -```Python hl_lines="18" -{!> ../../docs_src/extra_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 20" -{!> ../../docs_src/extra_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *} ## Response mit beliebigem `dict` @@ -266,21 +210,7 @@ Das ist nützlich, wenn Sie die gültigen Feld-/Attribut-Namen von vorneherein n In diesem Fall können Sie `typing.Dict` verwenden (oder nur `dict` in Python 3.9 und darüber): -//// tab | Python 3.9+ - -```Python hl_lines="6" -{!> ../../docs_src/extra_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 8" -{!> ../../docs_src/extra_models/tutorial005.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *} ## Zusammenfassung diff --git a/docs/de/docs/tutorial/first-steps.md b/docs/de/docs/tutorial/first-steps.md index debefb156..3104c8d61 100644 --- a/docs/de/docs/tutorial/first-steps.md +++ b/docs/de/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Die einfachste FastAPI-Datei könnte wie folgt aussehen: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Kopieren Sie dies in eine Datei `main.py`. @@ -133,9 +131,7 @@ Ebenfalls können Sie es verwenden, um automatisch Code für Clients zu generier ### Schritt 1: Importieren von `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` ist eine Python-Klasse, die die gesamte Funktionalität für Ihre API bereitstellt. @@ -149,9 +145,7 @@ Sie können alle Literal `...` setzen: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial006b_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006b.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py hl[9] *} /// info @@ -573,57 +337,7 @@ Sie können deklarieren, dass ein Parameter `None` akzeptiert, aber dennoch erfo Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwenden Sie dennoch `...` als Default: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} /// tip | Tipp @@ -643,71 +357,7 @@ Wenn Sie einen Query-Parameter explizit mit `Query` auszeichnen, können Sie ihn Um zum Beispiel einen Query-Parameter `q` zu deklarieren, der mehrere Male in der URL vorkommen kann, schreiben Sie: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *} Dann, mit einer URL wie: @@ -742,49 +392,7 @@ Die interaktive API-Dokumentation wird entsprechend aktualisiert und erlaubt jet Und Sie können auch eine Default-`list`e von Werten definieren, wenn keine übergeben werden: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *} Wenn Sie auf: @@ -807,35 +415,7 @@ gehen, wird der Default für `q` verwendet: `["foo", "bar"]`, und als Response e Sie können auch `list` direkt verwenden, anstelle von `List[str]` (oder `list[str]` in Python 3.9+): -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial013_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial013.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *} /// note | Hinweis @@ -861,111 +441,11 @@ Einige könnten noch nicht alle zusätzlichen Informationen anzeigen, die Sie de Sie können einen Titel hinzufügen – `title`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *} Und eine Beschreibung – `description`: -//// tab | Python 3.10+ - -```Python hl_lines="14" -{!> ../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/query_params_str_validations/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/query_params_str_validations/tutorial008.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *} ## Alias-Parameter @@ -985,57 +465,7 @@ Aber Sie möchten dennoch exakt `item-query` verwenden. Dann können Sie einen `alias` deklarieren, und dieser Alias wird verwendet, um den Parameter-Wert zu finden: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial009_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *} ## Parameter als deprecated ausweisen @@ -1045,57 +475,7 @@ Sie müssen ihn eine Weile dort belassen, weil Clients ihn benutzen, aber Sie m In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu. -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/query_params_str_validations/tutorial010_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="16" -{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="18" -{!> ../../docs_src/query_params_str_validations/tutorial010.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *} Die Dokumentation wird das so anzeigen: @@ -1105,57 +485,7 @@ Die Dokumentation wird das so anzeigen: Um einen Query-Parameter vom generierten OpenAPI-Schema auszuschließen (und daher von automatischen Dokumentations-Systemen), setzen Sie den Parameter `include_in_schema` in `Query` auf `False`. -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *} ## Zusammenfassung diff --git a/docs/de/docs/tutorial/query-params.md b/docs/de/docs/tutorial/query-params.md index e67fef79d..0b0f473e2 100644 --- a/docs/de/docs/tutorial/query-params.md +++ b/docs/de/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ Wenn Sie in ihrer Funktion Parameter deklarieren, die nicht Teil der Pfad-Parameter sind, dann werden diese automatisch als „Query“-Parameter interpretiert. -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} Query-Parameter (Deutsch: Abfrage-Parameter) sind die Schlüssel-Wert-Paare, die nach dem `?` in einer URL aufgelistet sind, getrennt durch `&`-Zeichen. @@ -63,21 +61,7 @@ gehen, werden die Parameter-Werte Ihrer Funktion sein: Auf die gleiche Weise können Sie optionale Query-Parameter deklarieren, indem Sie deren Defaultwert auf `None` setzen: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} In diesem Fall wird der Funktionsparameter `q` optional, und standardmäßig `None` sein. @@ -91,21 +75,7 @@ Beachten Sie auch, dass **FastAPI** intelligent genug ist, um zu erkennen, dass Sie können auch `bool`-Typen deklarieren und sie werden konvertiert: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} Wenn Sie nun zu: @@ -147,21 +117,7 @@ Und Sie müssen sie auch nicht in einer spezifischen Reihenfolge deklarieren. Parameter werden anhand ihres Namens erkannt: -//// tab | Python 3.10+ - -```Python hl_lines="6 8" -{!> ../../docs_src/query_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 10" -{!> ../../docs_src/query_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Erforderliche Query-Parameter @@ -171,9 +127,7 @@ Wenn Sie keinen spezifischen Wert haben wollen, sondern der Parameter einfach op Aber wenn Sie wollen, dass ein Query-Parameter erforderlich ist, vergeben Sie einfach keinen Defaultwert: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Hier ist `needy` ein erforderlicher Query-Parameter vom Typ `str`. @@ -219,21 +173,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Und natürlich können Sie einige Parameter als erforderlich, einige mit Defaultwert, und einige als vollständig optional definieren: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params/tutorial006.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} In diesem Fall gibt es drei Query-Parameter: diff --git a/docs/de/docs/tutorial/request-files.md b/docs/de/docs/tutorial/request-files.md index cbfb4271f..1f01b0d1e 100644 --- a/docs/de/docs/tutorial/request-files.md +++ b/docs/de/docs/tutorial/request-files.md @@ -16,69 +16,13 @@ Das, weil hochgeladene Dateien als „Formulardaten“ gesendet werden. Importieren Sie `File` und `UploadFile` von `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} ## `File`-Parameter definieren Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen würden: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} /// info @@ -106,35 +50,7 @@ Aber es gibt viele Fälle, in denen Sie davon profitieren, `UploadFile` zu verwe Definieren Sie einen Datei-Parameter mit dem Typ `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="13" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} `UploadFile` zu verwenden, hat mehrere Vorzüge gegenüber `bytes`: @@ -217,91 +133,13 @@ Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwenden und den Defaultwert auf `None` setzen: -//// tab | Python 3.10+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 18" -{!> ../../docs_src/request_files/tutorial001_02_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7 15" -{!> ../../docs_src/request_files/tutorial001_02_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} ## `UploadFile` mit zusätzlichen Metadaten Sie können auch `File()` zusammen mit `UploadFile` verwenden, um zum Beispiel zusätzliche Metadaten zu setzen: -//// tab | Python 3.9+ - -```Python hl_lines="9 15" -{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 14" -{!> ../../docs_src/request_files/tutorial001_03_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7 13" -{!> ../../docs_src/request_files/tutorial001_03.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} ## Mehrere Datei-Uploads @@ -311,49 +149,7 @@ Diese werden demselben Formularfeld zugeordnet, welches mit den Formulardaten ge Um das zu machen, deklarieren Sie eine Liste von `bytes` oder `UploadFile`s: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11 16" -{!> ../../docs_src/request_files/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/request_files/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} Sie erhalten, wie deklariert, eine `list`e von `bytes` oder `UploadFile`s. @@ -369,49 +165,7 @@ Sie können auch `from starlette.responses import HTMLResponse` verwenden. Und so wie zuvor können Sie `File()` verwenden, um zusätzliche Parameter zu setzen, sogar für `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="11 18-20" -{!> ../../docs_src/request_files/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12 19-21" -{!> ../../docs_src/request_files/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9 16" -{!> ../../docs_src/request_files/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11 18" -{!> ../../docs_src/request_files/tutorial003.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} ## Zusammenfassung diff --git a/docs/de/docs/tutorial/request-forms-and-files.md b/docs/de/docs/tutorial/request-forms-and-files.md index bdd1e0fac..3c5e11adf 100644 --- a/docs/de/docs/tutorial/request-forms-and-files.md +++ b/docs/de/docs/tutorial/request-forms-and-files.md @@ -12,69 +12,13 @@ Z. B. `pip install python-multipart`. ## `File` und `Form` importieren -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms_and_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *} ## `File` und `Form`-Parameter definieren Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` und `Query` machen würden: -//// tab | Python 3.9+ - -```Python hl_lines="10-12" -{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11" -{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/request_forms_and_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *} Die Datei- und Formularfelder werden als Formulardaten hochgeladen, und Sie erhalten diese Dateien und Formularfelder. diff --git a/docs/de/docs/tutorial/request-forms.md b/docs/de/docs/tutorial/request-forms.md index 2b6aeb41c..2f88caaba 100644 --- a/docs/de/docs/tutorial/request-forms.md +++ b/docs/de/docs/tutorial/request-forms.md @@ -14,69 +14,13 @@ Z. B. `pip install python-multipart`. Importieren Sie `Form` von `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} ## `Form`-Parameter definieren Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` machen würden: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} Zum Beispiel stellt eine der Möglichkeiten, die OAuth2 Spezifikation zu verwenden (genannt „password flow“), die Bedingung, einen `username` und ein `password` als Formularfelder zu senden. diff --git a/docs/de/docs/tutorial/response-model.md b/docs/de/docs/tutorial/response-model.md index aa27e0726..faf9be516 100644 --- a/docs/de/docs/tutorial/response-model.md +++ b/docs/de/docs/tutorial/response-model.md @@ -4,29 +4,7 @@ Sie können den Typ der ../../docs_src/response_model/tutorial001_01_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *} FastAPI wird diesen Rückgabetyp verwenden, um: @@ -59,29 +37,7 @@ Sie können `response_model` in jeder möglichen *Pfadoperation* verwenden: * `@app.delete()` * usw. -//// tab | Python 3.10+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *} /// note | Hinweis @@ -113,21 +69,7 @@ Sie können auch `response_model=None` verwenden, um das Erstellen eines Respons Im Folgenden deklarieren wir ein `UserIn`-Modell; es enthält ein Klartext-Passwort: -//// tab | Python 3.10+ - -```Python hl_lines="7 9" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *} /// info @@ -140,21 +82,7 @@ oder `pip install pydantic[email]`. Wir verwenden dieses Modell, um sowohl unsere Eingabe- als auch Ausgabedaten zu deklarieren: -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *} Immer wenn jetzt ein Browser einen Benutzer mit Passwort erzeugt, gibt die API dasselbe Passwort in der Response zurück. @@ -172,57 +100,15 @@ Speichern Sie niemals das Klartext-Passwort eines Benutzers, oder versenden Sie Wir können stattdessen ein Eingabemodell mit dem Klartext-Passwort, und ein Ausgabemodell ohne das Passwort erstellen: -//// tab | Python 3.10+ - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *} Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zurückgibt, der das Passwort enthält: -//// tab | Python 3.10+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *} ... haben wir deklariert, dass `response_model` das Modell `UserOut` ist, welches das Passwort nicht enthält: -//// tab | Python 3.10+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *} Darum wird **FastAPI** sich darum kümmern, dass alle Daten, die nicht im Ausgabemodell deklariert sind, herausgefiltert werden (mittels Pydantic). @@ -246,21 +132,7 @@ Aber in den meisten Fällen, wenn wir so etwas machen, wollen wir nur, dass das Und in solchen Fällen können wir Klassen und Vererbung verwenden, um Vorteil aus den Typannotationen in der Funktion zu ziehen, was vom Editor und von Tools besser unterstützt wird, während wir gleichzeitig FastAPIs **Datenfilterung** behalten. -//// tab | Python 3.10+ - -```Python hl_lines="7-10 13-14 18" -{!> ../../docs_src/response_model/tutorial003_01_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-13 15-16 20" -{!> ../../docs_src/response_model/tutorial003_01.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *} Damit erhalten wir Tool-Unterstützung, vom Editor und mypy, da dieser Code hinsichtlich der Typen korrekt ist, aber wir erhalten auch die Datenfilterung von FastAPI. @@ -302,9 +174,7 @@ Es kann Fälle geben, bei denen Sie etwas zurückgeben, das kein gültiges Pydan Der häufigste Anwendungsfall ist, wenn Sie [eine Response direkt zurückgeben, wie es später im Handbuch für fortgeschrittene Benutzer erläutert wird](../advanced/response-directly.md){.internal-link target=_blank}. -```Python hl_lines="8 10-11" -{!> ../../docs_src/response_model/tutorial003_02.py!} -``` +{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *} Dieser einfache Anwendungsfall wird automatisch von FastAPI gehandhabt, weil die Annotation des Rückgabetyps die Klasse (oder eine Unterklasse von) `Response` ist. @@ -314,9 +184,7 @@ Und Tools werden auch glücklich sein, weil sowohl `RedirectResponse` als auch ` Sie können auch eine Unterklasse von `Response` in der Typannotation verwenden. -```Python hl_lines="8-9" -{!> ../../docs_src/response_model/tutorial003_03.py!} -``` +{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *} Das wird ebenfalls funktionieren, weil `RedirectResponse` eine Unterklasse von `Response` ist, und FastAPI sich um diesen einfachen Anwendungsfall automatisch kümmert. @@ -326,21 +194,7 @@ Aber wenn Sie ein beliebiges anderes Objekt zurückgeben, das kein gültiger Pyd Das gleiche wird passieren, wenn Sie eine Union mehrerer Typen haben, und einer oder mehrere sind nicht gültige Pydantic-Typen. Zum Beispiel funktioniert folgendes nicht 💥: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/response_model/tutorial003_04_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/response_model/tutorial003_04.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *} ... das scheitert, da die Typannotation kein Pydantic-Typ ist, und auch keine einzelne `Response`-Klasse, oder -Unterklasse, es ist eine Union (eines von beiden) von `Response` und `dict`. @@ -352,21 +206,7 @@ Aber Sie möchten dennoch den Rückgabetyp in der Funktion annotieren, um Unters In diesem Fall können Sie die Generierung des Responsemodells abschalten, indem Sie `response_model=None` setzen: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/response_model/tutorial003_05_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/response_model/tutorial003_05.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *} Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und damit können Sie jede gewünschte Rückgabetyp-Annotation haben, ohne dass es Ihre FastAPI-Anwendung beeinflusst. 🤓 @@ -374,29 +214,7 @@ Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und d Ihr Responsemodell könnte Defaultwerte haben, wie: -//// tab | Python 3.10+ - -```Python hl_lines="9 11-12" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *} * `description: Union[str, None] = None` (oder `str | None = None` in Python 3.10) hat einen Defaultwert `None`. * `tax: float = 10.5` hat einen Defaultwert `10.5`. @@ -410,29 +228,7 @@ Wenn Sie zum Beispiel Modelle mit vielen optionalen Attributen in einer NoSQL-Da Sie können den *Pfadoperation-Dekorator*-Parameter `response_model_exclude_unset=True` setzen: -//// tab | Python 3.10+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *} Die Defaultwerte werden dann nicht in der Response enthalten sein, sondern nur die tatsächlich gesetzten Werte. @@ -529,21 +325,7 @@ Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert. /// -//// tab | Python 3.10+ - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial005.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *} /// tip | Tipp @@ -557,21 +339,7 @@ Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten. Wenn Sie vergessen, ein `set` zu verwenden, und stattdessen eine `list`e oder ein `tuple` übergeben, wird FastAPI die dennoch in ein `set` konvertieren, und es wird korrekt funktionieren: -//// tab | Python 3.10+ - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial006.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *} ## Zusammenfassung diff --git a/docs/de/docs/tutorial/security/first-steps.md b/docs/de/docs/tutorial/security/first-steps.md index 935b8ecca..8fa33db7e 100644 --- a/docs/de/docs/tutorial/security/first-steps.md +++ b/docs/de/docs/tutorial/security/first-steps.md @@ -20,35 +20,7 @@ Lassen Sie uns zunächst einfach den Code verwenden und sehen, wie er funktionie Kopieren Sie das Beispiel in eine Datei `main.py`: -//// tab | Python 3.9+ - -```Python -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py *} ## Ausführen @@ -154,35 +126,7 @@ In dem Fall gibt Ihnen **FastAPI** ebenfalls die Tools, die Sie zum Erstellen br Wenn wir eine Instanz der Klasse `OAuth2PasswordBearer` erstellen, übergeben wir den Parameter `tokenUrl`. Dieser Parameter enthält die URL, die der Client (das Frontend, das im Browser des Benutzers ausgeführt wird) verwendet, wenn er den `username` und das `password` sendet, um einen Token zu erhalten. -//// tab | Python 3.9+ - -```Python hl_lines="8" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="6" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *} /// tip | Tipp @@ -220,35 +164,7 @@ Es kann also mit `Depends` verwendet werden. Jetzt können Sie dieses `oauth2_scheme` als Abhängigkeit `Depends` übergeben. -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} Diese Abhängigkeit stellt einen `str` bereit, der dem Parameter `token` der *Pfadoperation-Funktion* zugewiesen wird. diff --git a/docs/de/docs/tutorial/security/get-current-user.md b/docs/de/docs/tutorial/security/get-current-user.md index 5f28f231f..38f7ffcbf 100644 --- a/docs/de/docs/tutorial/security/get-current-user.md +++ b/docs/de/docs/tutorial/security/get-current-user.md @@ -2,35 +2,7 @@ Im vorherigen Kapitel hat das Sicherheitssystem (das auf dem Dependency Injection System basiert) der *Pfadoperation-Funktion* einen `token` vom Typ `str` überreicht: -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} Aber das ist immer noch nicht so nützlich. @@ -42,57 +14,7 @@ Erstellen wir zunächst ein Pydantic-Benutzermodell. So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch überall sonst verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 13-17" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="3 10-14" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:16] *} ## Eine `get_current_user`-Abhängigkeit erstellen @@ -104,169 +26,19 @@ Erinnern Sie sich, dass Abhängigkeiten Unterabhängigkeiten haben können? So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere neue Abhängigkeit `get_current_user` von der Unterabhängigkeit `oauth2_scheme` einen `token` vom Typ `str`: -//// tab | Python 3.10+ - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="26" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="23" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *} ## Den Benutzer holen `get_current_user` wird eine von uns erstellte (gefakte) Hilfsfunktion verwenden, welche einen Token vom Typ `str` entgegennimmt und unser Pydantic-`User`-Modell zurückgibt: -//// tab | Python 3.10+ - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20-23 27-28" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="17-20 24-25" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *} ## Den aktuellen Benutzer einfügen Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der *Pfadoperation* verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="32" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="29" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *} Beachten Sie, dass wir als Typ von `current_user` das Pydantic-Modell `User` deklarieren. @@ -320,57 +92,7 @@ Und alle (oder beliebige Teile davon) können Vorteil ziehen aus der Wiederverwe Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein: -//// tab | Python 3.10+ - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31-33" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="28-30" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *} ## Zusammenfassung diff --git a/docs/de/docs/tutorial/security/oauth2-jwt.md b/docs/de/docs/tutorial/security/oauth2-jwt.md index 25c1e1c97..178a95d81 100644 --- a/docs/de/docs/tutorial/security/oauth2-jwt.md +++ b/docs/de/docs/tutorial/security/oauth2-jwt.md @@ -118,57 +118,7 @@ Und eine weitere, um zu überprüfen, ob ein empfangenes Passwort mit dem gespei Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben. -//// tab | Python 3.10+ - -```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7 49 56-57 60-61 70-76" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="6 47 54-55 58-59 68-74" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[7,48,55:56,59:60,69:75] *} /// note | Hinweis @@ -204,57 +154,7 @@ Definieren Sie ein Pydantic-Modell, das im Token-Endpunkt für die Response verw Erstellen Sie eine Hilfsfunktion, um einen neuen Zugriffstoken zu generieren. -//// tab | Python 3.10+ - -```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="6 13-15 29-31 79-87" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="5 11-13 27-29 77-85" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[6,12:14,28:30,78:86] *} ## Die Abhängigkeiten aktualisieren @@ -264,57 +164,7 @@ Dekodieren Sie den empfangenen Token, validieren Sie ihn und geben Sie den aktue Wenn der Token ungültig ist, geben Sie sofort einen HTTP-Fehler zurück. -//// tab | Python 3.10+ - -```Python hl_lines="89-106" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="89-106" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="90-107" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="88-105" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="89-106" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[89:106] *} ## Die *Pfadoperation* `/token` aktualisieren @@ -322,57 +172,7 @@ Erstellen Sie ein `timedelta` mit der Ablaufz Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück. -//// tab | Python 3.10+ - -```Python hl_lines="117-132" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="117-132" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="118-133" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="114-129" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="115-130" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[117:132] *} ### Technische Details zum JWT-„Subjekt“ `sub` diff --git a/docs/de/docs/tutorial/security/simple-oauth2.md b/docs/de/docs/tutorial/security/simple-oauth2.md index 2fa1385b0..c0c93cd26 100644 --- a/docs/de/docs/tutorial/security/simple-oauth2.md +++ b/docs/de/docs/tutorial/security/simple-oauth2.md @@ -52,57 +52,7 @@ Lassen Sie uns nun die von **FastAPI** bereitgestellten Werkzeuge verwenden, um Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als Abhängigkeit mit `Depends` in der *Pfadoperation* für `/token`: -//// tab | Python 3.10+ - -```Python hl_lines="4 78" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 78" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 79" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="2 74" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="4 76" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *} `OAuth2PasswordRequestForm` ist eine Klassenabhängigkeit, die einen Formularbody deklariert mit: @@ -150,57 +100,7 @@ Wenn es keinen solchen Benutzer gibt, geben wir die Fehlermeldung „Incorrect u Für den Fehler verwenden wir die Exception `HTTPException`: -//// tab | Python 3.10+ - -```Python hl_lines="3 79-81" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3 79-81" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3 80-82" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1 75-77" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="3 77-79" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *} ### Das Passwort überprüfen @@ -226,57 +126,7 @@ Wenn Ihre Datenbank gestohlen wird, hat der Dieb nicht die Klartext-Passwörter Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen System zu verwenden (da viele Benutzer überall das gleiche Passwort verwenden, wäre dies gefährlich). -//// tab | Python 3.10+ - -```Python hl_lines="82-85" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="82-85" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="83-86" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="78-81" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="80-83" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *} #### Über `**user_dict` @@ -318,57 +168,7 @@ Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benö /// -//// tab | Python 3.10+ - -```Python hl_lines="87" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="87" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="88" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="83" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="85" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *} /// tip | Tipp @@ -394,57 +194,7 @@ Beide Abhängigkeiten geben nur dann einen HTTP-Error zurück, wenn der Benutzer In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer existiert, korrekt authentifiziert wurde und aktiv ist: -//// tab | Python 3.10+ - -```Python hl_lines="58-66 69-74 94" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="58-66 69-74 94" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="59-67 70-75 95" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="56-64 67-70 88" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="58-66 69-72 90" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *} /// info diff --git a/docs/de/docs/tutorial/static-files.md b/docs/de/docs/tutorial/static-files.md index aa44e3f4e..50e86d68e 100644 --- a/docs/de/docs/tutorial/static-files.md +++ b/docs/de/docs/tutorial/static-files.md @@ -7,9 +7,7 @@ Mit `StaticFiles` können Sie statische Dateien aus einem Verzeichnis automatisc * Importieren Sie `StaticFiles`. * „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad. -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} /// note | Technische Details diff --git a/docs/de/docs/tutorial/testing.md b/docs/de/docs/tutorial/testing.md index 53459342b..e7c1dda95 100644 --- a/docs/de/docs/tutorial/testing.md +++ b/docs/de/docs/tutorial/testing.md @@ -26,9 +26,7 @@ Verwenden Sie das `TestClient`-Objekt auf die gleiche Weise wie `httpx`. Schreiben Sie einfache `assert`-Anweisungen mit den Standard-Python-Ausdrücken, die Sie überprüfen müssen (wiederum, Standard-`pytest`). -```Python hl_lines="2 12 15-18" -{!../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} /// tip | Tipp @@ -74,9 +72,8 @@ Nehmen wir an, Sie haben eine Dateistruktur wie in [Größere Anwendungen](bigge In der Datei `main.py` haben Sie Ihre **FastAPI**-Anwendung: -```Python -{!../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} + ### Testdatei @@ -92,9 +89,8 @@ Dann könnten Sie eine Datei `test_main.py` mit Ihren Tests haben. Sie könnte s Da sich diese Datei im selben Package befindet, können Sie relative Importe verwenden, um das Objekt `app` aus dem `main`-Modul (`main.py`) zu importieren: -```Python hl_lines="3" -{!../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py hl[3] *} + ... und haben den Code für die Tests wie zuvor. @@ -178,9 +174,8 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. Anschließend könnten Sie `test_main.py` mit den erweiterten Tests aktualisieren: -```Python -{!> ../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} + Wenn Sie möchten, dass der Client Informationen im Request übergibt und Sie nicht wissen, wie das geht, können Sie suchen (googeln), wie es mit `httpx` gemacht wird, oder sogar, wie es mit `requests` gemacht wird, da das Design von HTTPX auf dem Design von Requests basiert. diff --git a/docs/em/docs/advanced/additional-responses.md b/docs/em/docs/advanced/additional-responses.md index e4442135e..655fc7ab6 100644 --- a/docs/em/docs/advanced/additional-responses.md +++ b/docs/em/docs/advanced/additional-responses.md @@ -26,9 +26,7 @@ 🖼, 📣 ➕1️⃣ 📨 ⏮️ 👔 📟 `404` & Pydantic 🏷 `Message`, 👆 💪 ✍: -```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 @@ 🖼, 👆 💪 🚮 🌖 📻 🆎 `image/png`, 📣 👈 👆 *➡ 🛠️* 💪 📨 🎻 🎚 (⏮️ 📻 🆎 `application/json`) ⚖️ 🇩🇴 🖼: -```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 @@ & 📨 ⏮️ 👔 📟 `200` 👈 ⚙️ 👆 `response_model`, ✋️ 🔌 🛃 `example`: -```Python hl_lines="20-31" -{!../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} ⚫️ 🔜 🌐 🌀 & 🔌 👆 🗄, & 🎦 🛠️ 🩺: @@ -243,9 +237,7 @@ new_dict = {**old_dict, "new key": "new value"} 🖼: -```Python hl_lines="13-17 26" -{!../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## 🌖 ℹ 🔃 🗄 📨 diff --git a/docs/em/docs/advanced/additional-status-codes.md b/docs/em/docs/advanced/additional-status-codes.md index 5eb2ec90e..907c7e68e 100644 --- a/docs/em/docs/advanced/additional-status-codes.md +++ b/docs/em/docs/advanced/additional-status-codes.md @@ -14,9 +14,7 @@ 🏆 👈, 🗄 `JSONResponse`, & 📨 👆 🎚 📤 🔗, ⚒ `status_code` 👈 👆 💚: -```Python hl_lines="4 25" -{!../../docs_src/additional_status_codes/tutorial001.py!} -``` +{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *} /// warning diff --git a/docs/em/docs/advanced/advanced-dependencies.md b/docs/em/docs/advanced/advanced-dependencies.md index 721428ce4..3404c2687 100644 --- a/docs/em/docs/advanced/advanced-dependencies.md +++ b/docs/em/docs/advanced/advanced-dependencies.md @@ -18,9 +18,7 @@ 👈, 👥 📣 👩‍🔬 `__call__`: -```Python hl_lines="10" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[10] *} 👉 💼, 👉 `__call__` ⚫️❔ **FastAPI** 🔜 ⚙️ ✅ 🌖 🔢 & 🎧-🔗, & 👉 ⚫️❔ 🔜 🤙 🚶‍♀️ 💲 🔢 👆 *➡ 🛠️ 🔢* ⏪. @@ -28,9 +26,7 @@ & 🔜, 👥 💪 ⚙️ `__init__` 📣 🔢 👐 👈 👥 💪 ⚙️ "🔗" 🔗: -```Python hl_lines="7" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[7] *} 👉 💼, **FastAPI** 🏆 🚫 ⏱ 👆 ⚖️ 💅 🔃 `__init__`, 👥 🔜 ⚙️ ⚫️ 🔗 👆 📟. @@ -38,9 +34,7 @@ 👥 💪 ✍ 👐 👉 🎓 ⏮️: -```Python hl_lines="16" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[16] *} & 👈 🌌 👥 💪 "🔗" 👆 🔗, 👈 🔜 ✔️ `"bar"` 🔘 ⚫️, 🔢 `checker.fixed_content`. @@ -56,9 +50,7 @@ checker(q="somequery") ...& 🚶‍♀️ ⚫️❔ 👈 📨 💲 🔗 👆 *➡ 🛠️ 🔢* 🔢 `fixed_content_included`: -```Python hl_lines="20" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[20] *} /// tip diff --git a/docs/em/docs/advanced/async-tests.md b/docs/em/docs/advanced/async-tests.md index 4d468acd4..283d4aa09 100644 --- a/docs/em/docs/advanced/async-tests.md +++ b/docs/em/docs/advanced/async-tests.md @@ -32,15 +32,11 @@ 📁 `main.py` 🔜 ✔️: -```Python -{!../../docs_src/async_tests/main.py!} -``` +{* ../../docs_src/async_tests/main.py *} 📁 `test_main.py` 🔜 ✔️ 💯 `main.py`, ⚫️ 💪 👀 💖 👉 🔜: -```Python -{!../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py *} ## 🏃 ⚫️ @@ -60,9 +56,7 @@ $ pytest 📑 `@pytest.mark.anyio` 💬 ✳ 👈 👉 💯 🔢 🔜 🤙 🔁: -```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 @@ $ pytest ⤴️ 👥 💪 ✍ `AsyncClient` ⏮️ 📱, & 📨 🔁 📨 ⚫️, ⚙️ `await`. -```Python hl_lines="9-12" -{!../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} 👉 🌓: diff --git a/docs/em/docs/advanced/behind-a-proxy.md b/docs/em/docs/advanced/behind-a-proxy.md index 36aa2e6b3..8b14152c9 100644 --- a/docs/em/docs/advanced/behind-a-proxy.md +++ b/docs/em/docs/advanced/behind-a-proxy.md @@ -94,9 +94,7 @@ $ uvicorn main:app --root-path /api/v1 📥 👥 ✅ ⚫️ 📧 🎦 🎯. -```Python hl_lines="8" -{!../../docs_src/behind_a_proxy/tutorial001.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *} ⤴️, 🚥 👆 ▶️ Uvicorn ⏮️: @@ -123,9 +121,7 @@ $ uvicorn main:app --root-path /api/v1 👐, 🚥 👆 🚫 ✔️ 🌌 🚚 📋 ⏸ 🎛 💖 `--root-path` ⚖️ 🌓, 👆 💪 ⚒ `root_path` 🔢 🕐❔ 🏗 👆 FastAPI 📱: -```Python hl_lines="3" -{!../../docs_src/behind_a_proxy/tutorial002.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *} 🚶‍♀️ `root_path` `FastAPI` 🔜 🌓 🚶‍♀️ `--root-path` 📋 ⏸ 🎛 Uvicorn ⚖️ Hypercorn. @@ -305,9 +301,7 @@ $ uvicorn main:app --root-path /api/v1 🖼: -```Python hl_lines="4-7" -{!../../docs_src/behind_a_proxy/tutorial003.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *} 🔜 🏗 🗄 🔗 💖: @@ -354,9 +348,7 @@ $ uvicorn main:app --root-path /api/v1 🚥 👆 🚫 💚 **FastAPI** 🔌 🏧 💽 ⚙️ `root_path`, 👆 💪 ⚙️ 🔢 `root_path_in_servers=False`: -```Python hl_lines="9" -{!../../docs_src/behind_a_proxy/tutorial004.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *} & ⤴️ ⚫️ 🏆 🚫 🔌 ⚫️ 🗄 🔗. diff --git a/docs/em/docs/advanced/custom-response.md b/docs/em/docs/advanced/custom-response.md index 301f99957..ab95b3e7b 100644 --- a/docs/em/docs/advanced/custom-response.md +++ b/docs/em/docs/advanced/custom-response.md @@ -30,9 +30,7 @@ ✋️ 🚥 👆 🎯 👈 🎚 👈 👆 🛬 **🎻 ⏮️ 🎻**, 👆 💪 🚶‍♀️ ⚫️ 🔗 📨 🎓 & ❎ ➕ 🌥 👈 FastAPI 🔜 ✔️ 🚶‍♀️ 👆 📨 🎚 🔘 `jsonable_encoder` ⏭ 🚶‍♀️ ⚫️ 📨 🎓. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} /// info @@ -57,9 +55,7 @@ * 🗄 `HTMLResponse`. * 🚶‍♀️ `HTMLResponse` 🔢 `response_class` 👆 *➡ 🛠️ 👨‍🎨*. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial002.py!} -``` +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} /// info @@ -77,9 +73,7 @@ 🎏 🖼 ⚪️➡️ 🔛, 🛬 `HTMLResponse`, 💪 👀 💖: -```Python hl_lines="2 7 19" -{!../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} /// warning @@ -103,9 +97,7 @@ 🖼, ⚫️ 💪 🕳 💖: -```Python hl_lines="7 21 23" -{!../../docs_src/custom_response/tutorial004.py!} -``` +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} 👉 🖼, 🔢 `generate_html_response()` ⏪ 🏗 & 📨 `Response` ↩️ 🛬 🕸 `str`. @@ -144,9 +136,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🎚, ⚓️ 🔛 = & 🔁 = ✍ 🆎. -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ### `HTMLResponse` @@ -156,9 +146,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 ✊ ✍ ⚖️ 🔢 & 📨 ✅ ✍ 📨. -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial005.py!} -``` +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} ### `JSONResponse` @@ -180,9 +168,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 /// -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001.py!} -``` +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} /// tip @@ -196,18 +182,14 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👆 💪 📨 `RedirectResponse` 🔗: -```Python hl_lines="2 9" -{!../../docs_src/custom_response/tutorial006.py!} -``` +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} --- ⚖️ 👆 💪 ⚙️ ⚫️ `response_class` 🔢: -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial006b.py!} -``` +{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *} 🚥 👆 👈, ⤴️ 👆 💪 📨 📛 🔗 ⚪️➡️ 👆 *➡ 🛠️* 🔢. @@ -217,17 +199,13 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👆 💪 ⚙️ `status_code` 🔢 🌀 ⏮️ `response_class` 🔢: -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial006c.py!} -``` +{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *} ### `StreamingResponse` ✊ 🔁 🚂 ⚖️ 😐 🚂/🎻 & 🎏 📨 💪. -```Python hl_lines="2 14" -{!../../docs_src/custom_response/tutorial007.py!} -``` +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} #### ⚙️ `StreamingResponse` ⏮️ 📁-💖 🎚 @@ -268,15 +246,11 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 📁 📨 🔜 🔌 ☑ `Content-Length`, `Last-Modified` & `ETag` 🎚. -```Python hl_lines="2 10" -{!../../docs_src/custom_response/tutorial009.py!} -``` +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} 👆 💪 ⚙️ `response_class` 🔢: -```Python hl_lines="2 8 10" -{!../../docs_src/custom_response/tutorial009b.py!} -``` +{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *} 👉 💼, 👆 💪 📨 📁 ➡ 🔗 ⚪️➡️ 👆 *➡ 🛠️* 🔢. @@ -290,9 +264,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👆 💪 ✍ `CustomORJSONResponse`. 👑 👜 👆 ✔️ ✍ `Response.render(content)` 👩‍🔬 👈 📨 🎚 `bytes`: -```Python hl_lines="9-14 17" -{!../../docs_src/custom_response/tutorial009c.py!} -``` +{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *} 🔜 ↩️ 🛬: @@ -318,9 +290,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🖼 🔛, **FastAPI** 🔜 ⚙️ `ORJSONResponse` 🔢, 🌐 *➡ 🛠️*, ↩️ `JSONResponse`. -```Python hl_lines="2 4" -{!../../docs_src/custom_response/tutorial010.py!} -``` +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} /// tip diff --git a/docs/em/docs/advanced/dataclasses.md b/docs/em/docs/advanced/dataclasses.md index ab76e5083..4dd597262 100644 --- a/docs/em/docs/advanced/dataclasses.md +++ b/docs/em/docs/advanced/dataclasses.md @@ -4,9 +4,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda ✋️ FastAPI 🐕‍🦺 ⚙️ `dataclasses` 🎏 🌌: -```Python hl_lines="1 7-12 19-20" -{!../../docs_src/dataclasses/tutorial001.py!} -``` +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} 👉 🐕‍🦺 👏 **Pydantic**, ⚫️ ✔️ 🔗 🐕‍🦺 `dataclasses`. @@ -34,9 +32,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda 👆 💪 ⚙️ `dataclasses` `response_model` 🔢: -```Python hl_lines="1 7-13 19" -{!../../docs_src/dataclasses/tutorial002.py!} -``` +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} 🎻 🔜 🔁 🗜 Pydantic 🎻. diff --git a/docs/em/docs/advanced/events.md b/docs/em/docs/advanced/events.md index 2eae2b366..68adb6d65 100644 --- a/docs/em/docs/advanced/events.md +++ b/docs/em/docs/advanced/events.md @@ -30,9 +30,7 @@ 👥 ✍ 🔁 🔢 `lifespan()` ⏮️ `yield` 💖 👉: -```Python hl_lines="16 19" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[16,19] *} 📥 👥 ⚖ 😥 *🕴* 🛠️ 🚚 🏷 🚮 (❌) 🏷 🔢 📖 ⏮️ 🎰 🏫 🏷 ⏭ `yield`. 👉 📟 🔜 🛠️ **⏭** 🈸 **▶️ ✊ 📨**, ⏮️ *🕴*. @@ -50,9 +48,7 @@ 🥇 👜 👀, 👈 👥 ⚖ 🔁 🔢 ⏮️ `yield`. 👉 📶 🎏 🔗 ⏮️ `yield`. -```Python hl_lines="14-19" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[14:19] *} 🥇 🍕 🔢, ⏭ `yield`, 🔜 🛠️ **⏭** 🈸 ▶️. @@ -64,9 +60,7 @@ 👈 🗜 🔢 🔘 🕳 🤙 "**🔁 🔑 👨‍💼**". -```Python hl_lines="1 13" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[1,13] *} **🔑 👨‍💼** 🐍 🕳 👈 👆 💪 ⚙️ `with` 📄, 🖼, `open()` 💪 ⚙️ 🔑 👨‍💼: @@ -88,9 +82,7 @@ async with lifespan(app): `lifespan` 🔢 `FastAPI` 📱 ✊ **🔁 🔑 👨‍💼**, 👥 💪 🚶‍♀️ 👆 🆕 `lifespan` 🔁 🔑 👨‍💼 ⚫️. -```Python hl_lines="22" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[22] *} ## 🎛 🎉 (😢) @@ -112,9 +104,7 @@ async with lifespan(app): 🚮 🔢 👈 🔜 🏃 ⏭ 🈸 ▶️, 📣 ⚫️ ⏮️ 🎉 `"startup"`: -```Python hl_lines="8" -{!../../docs_src/events/tutorial001.py!} -``` +{* ../../docs_src/events/tutorial001.py hl[8] *} 👉 💼, `startup` 🎉 🐕‍🦺 🔢 🔜 🔢 🏬 "💽" ( `dict`) ⏮️ 💲. @@ -126,9 +116,7 @@ async with lifespan(app): 🚮 🔢 👈 🔜 🏃 🕐❔ 🈸 🤫 🔽, 📣 ⚫️ ⏮️ 🎉 `"shutdown"`: -```Python hl_lines="6" -{!../../docs_src/events/tutorial002.py!} -``` +{* ../../docs_src/events/tutorial002.py hl[6] *} 📥, `shutdown` 🎉 🐕‍🦺 🔢 🔜 ✍ ✍ ⏸ `"Application shutdown"` 📁 `log.txt`. diff --git a/docs/em/docs/advanced/generate-clients.md b/docs/em/docs/advanced/generate-clients.md index f09d75623..a680c9051 100644 --- a/docs/em/docs/advanced/generate-clients.md +++ b/docs/em/docs/advanced/generate-clients.md @@ -16,21 +16,7 @@ ➡️ ▶️ ⏮️ 🙅 FastAPI 🈸: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../docs_src/generate_clients/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="7-9 12-13 16-17 21" -{!> ../../docs_src/generate_clients/tutorial001_py39.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial001.py hl[9:11,14:15,18,19,23] *} 👀 👈 *➡ 🛠️* 🔬 🏷 👫 ⚙️ 📨 🚀 & 📨 🚀, ⚙️ 🏷 `Item` & `ResponseMessage`. @@ -136,21 +122,7 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app 🖼, 👆 💪 ✔️ 📄 **🏬** & ➕1️⃣ 📄 **👩‍💻**, & 👫 💪 👽 🔖: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="23 28 36" -{!> ../../docs_src/generate_clients/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="21 26 34" -{!> ../../docs_src/generate_clients/tutorial002_py39.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial002.py hl[23,28,36] *} ### 🏗 📕 👩‍💻 ⏮️ 🔖 @@ -197,21 +169,7 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** 👆 💪 ⤴️ 🚶‍♀️ 👈 🛃 🔢 **FastAPI** `generate_unique_id_function` 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="8-9 12" -{!> ../../docs_src/generate_clients/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="6-7 10" -{!> ../../docs_src/generate_clients/tutorial003_py39.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial003.py hl[8:9,12] *} ### 🏗 📕 👩‍💻 ⏮️ 🛃 🛠️ 🆔 @@ -233,9 +191,7 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** 👥 💪 ⏬ 🗄 🎻 📁 `openapi.json` & ⤴️ 👥 💪 **❎ 👈 🔡 🔖** ⏮️ ✍ 💖 👉: -```Python -{!../../docs_src/generate_clients/tutorial004.py!} -``` +{* ../../docs_src/generate_clients/tutorial004.py *} ⏮️ 👈, 🛠️ 🆔 🔜 📁 ⚪️➡️ 👜 💖 `items-get_items` `get_items`, 👈 🌌 👩‍💻 🚂 💪 🏗 🙅 👩‍🔬 📛. diff --git a/docs/em/docs/advanced/middleware.md b/docs/em/docs/advanced/middleware.md index 914ce4a30..cb04fa3fb 100644 --- a/docs/em/docs/advanced/middleware.md +++ b/docs/em/docs/advanced/middleware.md @@ -57,17 +57,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 🙆 📨 📨 `http` ⚖️ `ws` 🔜 ❎ 🔐 ⚖ ↩️. -```Python hl_lines="2 6" -{!../../docs_src/advanced_middleware/tutorial001.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} ## `TrustedHostMiddleware` 🛠️ 👈 🌐 📨 📨 ✔️ ☑ ⚒ `Host` 🎚, ✔ 💂‍♂ 🛡 🇺🇸🔍 🦠 🎚 👊. -```Python hl_lines="2 6-8" -{!../../docs_src/advanced_middleware/tutorial002.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} 📄 ❌ 🐕‍🦺: @@ -81,9 +77,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 🛠️ 🔜 🍵 👯‍♂️ 🐩 & 🎥 📨. -```Python hl_lines="2 6" -{!../../docs_src/advanced_middleware/tutorial003.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} 📄 ❌ 🐕‍🦺: diff --git a/docs/em/docs/advanced/openapi-callbacks.md b/docs/em/docs/advanced/openapi-callbacks.md index f7b5e7ed9..b0a821668 100644 --- a/docs/em/docs/advanced/openapi-callbacks.md +++ b/docs/em/docs/advanced/openapi-callbacks.md @@ -31,9 +31,7 @@ 👉 🍕 📶 😐, 🌅 📟 🎲 ⏪ 😰 👆: -```Python hl_lines="9-13 36-53" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *} /// tip @@ -92,9 +90,7 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) 🥇 ✍ 🆕 `APIRouter` 👈 🔜 🔌 1️⃣ ⚖️ 🌅 ⏲. -```Python hl_lines="3 25" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *} ### ✍ ⏲ *➡ 🛠️* @@ -105,9 +101,7 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) * ⚫️ 🔜 🎲 ✔️ 📄 💪 ⚫️ 🔜 📨, ✅ `body: InvoiceEvent`. * & ⚫️ 💪 ✔️ 📄 📨 ⚫️ 🔜 📨, ✅ `response_model=InvoiceEventReceived`. -```Python hl_lines="16-18 21-22 28-32" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *} 📤 2️⃣ 👑 🔺 ⚪️➡️ 😐 *➡ 🛠️*: @@ -175,9 +169,7 @@ https://www.external.org/events/invoices/2expen51ve 🔜 ⚙️ 🔢 `callbacks` *👆 🛠️ ➡ 🛠️ 👨‍🎨* 🚶‍♀️ 🔢 `.routes` (👈 🤙 `list` 🛣/*➡ 🛠️*) ⚪️➡️ 👈 ⏲ 📻: -```Python hl_lines="35" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *} /// tip diff --git a/docs/em/docs/advanced/path-operation-advanced-configuration.md b/docs/em/docs/advanced/path-operation-advanced-configuration.md index 47e89a90f..9d9d5fa8d 100644 --- a/docs/em/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/em/docs/advanced/path-operation-advanced-configuration.md @@ -12,9 +12,7 @@ 👆 🔜 ✔️ ⚒ 💭 👈 ⚫️ 😍 🔠 🛠️. -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### ⚙️ *➡ 🛠️ 🔢* 📛 { @@ -22,9 +20,7 @@ 👆 🔜 ⚫️ ⏮️ ❎ 🌐 👆 *➡ 🛠️*. -```Python hl_lines="2 12-21 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *} /// tip @@ -44,9 +40,7 @@ 🚫 *➡ 🛠️* ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚙️ 🔢 `include_in_schema` & ⚒ ⚫️ `False`: -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## 🏧 📛 ⚪️➡️ #️⃣ @@ -56,9 +50,7 @@ ⚫️ 🏆 🚫 🎦 🆙 🧾, ✋️ 🎏 🧰 (✅ 🐉) 🔜 💪 ⚙️ 🎂. -```Python hl_lines="19-29" -{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} ## 🌖 📨 @@ -100,9 +92,7 @@ 👉 `openapi_extra` 💪 👍, 🖼, 📣 [🗄 ↔](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions): -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} 🚥 👆 📂 🏧 🛠️ 🩺, 👆 ↔ 🔜 🎦 🆙 🔝 🎯 *➡ 🛠️*. @@ -149,9 +139,7 @@ 👆 💪 👈 ⏮️ `openapi_extra`: -```Python hl_lines="20-37 39-40" -{!../../docs_src/path_operation_advanced_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[20:37,39:40] *} 👉 🖼, 👥 🚫 📣 🙆 Pydantic 🏷. 👐, 📨 💪 🚫 🎻 🎻, ⚫️ ✍ 🔗 `bytes`, & 🔢 `magic_data_reader()` 🔜 🈚 🎻 ⚫️ 🌌. @@ -165,9 +153,7 @@ 🖼, 👉 🈸 👥 🚫 ⚙️ FastAPI 🛠️ 🛠️ ⚗ 🎻 🔗 ⚪️➡️ Pydantic 🏷 🚫 🏧 🔬 🎻. 👐, 👥 📣 📨 🎚 🆎 📁, 🚫 🎻: -```Python hl_lines="17-22 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *} 👐, 👐 👥 🚫 ⚙️ 🔢 🛠️ 🛠️, 👥 ⚙️ Pydantic 🏷 ❎ 🏗 🎻 🔗 💽 👈 👥 💚 📨 📁. @@ -175,9 +161,7 @@ & ⤴️ 👆 📟, 👥 🎻 👈 📁 🎚 🔗, & ⤴️ 👥 🔄 ⚙️ 🎏 Pydantic 🏷 ✔ 📁 🎚: -```Python hl_lines="26-33" -{!../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} /// tip diff --git a/docs/em/docs/advanced/response-change-status-code.md b/docs/em/docs/advanced/response-change-status-code.md index 7f2e8c157..4933484dd 100644 --- a/docs/em/docs/advanced/response-change-status-code.md +++ b/docs/em/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ & ⤴️ 👆 💪 ⚒ `status_code` 👈 *🔀* 📨 🎚. -```Python hl_lines="1 9 12" -{!../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} & ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️). diff --git a/docs/em/docs/advanced/response-cookies.md b/docs/em/docs/advanced/response-cookies.md index 0fe47baec..d9fdbaa87 100644 --- a/docs/em/docs/advanced/response-cookies.md +++ b/docs/em/docs/advanced/response-cookies.md @@ -6,9 +6,7 @@ & ⤴️ 👆 💪 ⚒ 🍪 👈 *🔀* 📨 🎚. -```Python hl_lines="1 8-9" -{!../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} & ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️). @@ -26,9 +24,7 @@ ⤴️ ⚒ 🍪 ⚫️, & ⤴️ 📨 ⚫️: -```Python hl_lines="10-12" -{!../../docs_src/response_cookies/tutorial001.py!} -``` +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} /// tip diff --git a/docs/em/docs/advanced/response-directly.md b/docs/em/docs/advanced/response-directly.md index 335c381c7..29819a205 100644 --- a/docs/em/docs/advanced/response-directly.md +++ b/docs/em/docs/advanced/response-directly.md @@ -34,9 +34,7 @@ 📚 💼, 👆 💪 ⚙️ `jsonable_encoder` 🗜 👆 📊 ⏭ 🚶‍♀️ ⚫️ 📨: -```Python hl_lines="6-7 21-22" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} /// note | 📡 ℹ @@ -56,9 +54,7 @@ 👆 💪 🚮 👆 📂 🎚 🎻, 🚮 ⚫️ `Response`, & 📨 ⚫️: -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ## 🗒 diff --git a/docs/em/docs/advanced/response-headers.md b/docs/em/docs/advanced/response-headers.md index d577347fe..e9e1b62d2 100644 --- a/docs/em/docs/advanced/response-headers.md +++ b/docs/em/docs/advanced/response-headers.md @@ -6,9 +6,7 @@ & ⤴️ 👆 💪 ⚒ 🎚 👈 *🔀* 📨 🎚. -```Python hl_lines="1 7-8" -{!../../docs_src/response_headers/tutorial002.py!} -``` +{* ../../docs_src/response_headers/tutorial002.py hl[1,7:8] *} & ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️). @@ -24,9 +22,7 @@ ✍ 📨 🔬 [📨 📨 🔗](response-directly.md){.internal-link target=_blank} & 🚶‍♀️ 🎚 🌖 🔢: -```Python hl_lines="10-12" -{!../../docs_src/response_headers/tutorial001.py!} -``` +{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *} /// note | 📡 ℹ diff --git a/docs/em/docs/advanced/security/http-basic-auth.md b/docs/em/docs/advanced/security/http-basic-auth.md index e6fe3e32c..73736f3b3 100644 --- a/docs/em/docs/advanced/security/http-basic-auth.md +++ b/docs/em/docs/advanced/security/http-basic-auth.md @@ -20,9 +20,7 @@ * ⚫️ 📨 🎚 🆎 `HTTPBasicCredentials`: * ⚫️ 🔌 `username` & `password` 📨. -```Python hl_lines="2 6 10" -{!../../docs_src/security/tutorial006.py!} -``` +{* ../../docs_src/security/tutorial006.py hl[2,6,10] *} 🕐❔ 👆 🔄 📂 📛 🥇 🕰 (⚖️ 🖊 "🛠️" 🔼 🩺) 🖥 🔜 💭 👆 👆 🆔 & 🔐: @@ -42,9 +40,7 @@ ⤴️ 👥 💪 ⚙️ `secrets.compare_digest()` 🚚 👈 `credentials.username` `"stanleyjobson"`, & 👈 `credentials.password` `"swordfish"`. -```Python hl_lines="1 11-21" -{!../../docs_src/security/tutorial007.py!} -``` +{* ../../docs_src/security/tutorial007.py hl[1,11:21] *} 👉 🔜 🎏: @@ -108,6 +104,4 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": ⏮️ 🔍 👈 🎓 ❌, 📨 `HTTPException` ⏮️ 👔 📟 4️⃣0️⃣1️⃣ (🎏 📨 🕐❔ 🙅‍♂ 🎓 🚚) & 🚮 🎚 `WWW-Authenticate` ⚒ 🖥 🎦 💳 📋 🔄: -```Python hl_lines="23-27" -{!../../docs_src/security/tutorial007.py!} -``` +{* ../../docs_src/security/tutorial007.py hl[23:27] *} diff --git a/docs/em/docs/advanced/security/oauth2-scopes.md b/docs/em/docs/advanced/security/oauth2-scopes.md index f4d1a3b82..b8c49bd11 100644 --- a/docs/em/docs/advanced/security/oauth2-scopes.md +++ b/docs/em/docs/advanced/security/oauth2-scopes.md @@ -62,9 +62,7 @@ Oauth2️⃣ 👫 🎻. 🥇, ➡️ 🔜 👀 🍕 👈 🔀 ⚪️➡️ 🖼 👑 **🔰 - 👩‍💻 🦮** [Oauth2️⃣ ⏮️ 🔐 (& 🔁), 📨 ⏮️ 🥙 🤝](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. 🔜 ⚙️ Oauth2️⃣ ↔: -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[2,4,8,12,46,64,105,107:115,121:124,128:134,139,155] *} 🔜 ➡️ 📄 👈 🔀 🔁 🔁. @@ -74,9 +72,7 @@ Oauth2️⃣ 👫 🎻. `scopes` 🔢 📨 `dict` ⏮️ 🔠 ↔ 🔑 & 📛 💲: -```Python hl_lines="62-65" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[62:65] *} ↩️ 👥 🔜 📣 📚 ↔, 👫 🔜 🎦 🆙 🛠️ 🩺 🕐❔ 👆 🕹-/✔. @@ -102,9 +98,7 @@ Oauth2️⃣ 👫 🎻. /// -```Python hl_lines="155" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[155] *} ## 📣 ↔ *➡ 🛠️* & 🔗 @@ -130,9 +124,7 @@ Oauth2️⃣ 👫 🎻. /// -```Python hl_lines="4 139 168" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[4,139,168] *} /// info | 📡 ℹ @@ -158,9 +150,7 @@ Oauth2️⃣ 👫 🎻. 👉 `SecurityScopes` 🎓 🎏 `Request` (`Request` ⚙️ 🤚 📨 🎚 🔗). -```Python hl_lines="8 105" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[8,105] *} ## ⚙️ `scopes` @@ -174,9 +164,7 @@ Oauth2️⃣ 👫 🎻. 👉 ⚠, 👥 🔌 ↔ 🚚 (🚥 🙆) 🎻 👽 🚀 (⚙️ `scope_str`). 👥 🚮 👈 🎻 ⚗ ↔ `WWW-Authenticate` 🎚 (👉 🍕 🔌). -```Python hl_lines="105 107-115" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[105,107:115] *} ## ✔ `username` & 💽 💠 @@ -192,9 +180,7 @@ Oauth2️⃣ 👫 🎻. 👥 ✔ 👈 👥 ✔️ 👩‍💻 ⏮️ 👈 🆔, & 🚥 🚫, 👥 🤚 👈 🎏 ⚠ 👥 ✍ ⏭. -```Python hl_lines="46 116-127" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[46,116:127] *} ## ✔ `scopes` @@ -202,9 +188,7 @@ Oauth2️⃣ 👫 🎻. 👉, 👥 ⚙️ `security_scopes.scopes`, 👈 🔌 `list` ⏮️ 🌐 👫 ↔ `str`. -```Python hl_lines="128-134" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[128:134] *} ## 🔗 🌲 & ↔ diff --git a/docs/em/docs/advanced/settings.md b/docs/em/docs/advanced/settings.md index 59fb71d73..7fdd0d68a 100644 --- a/docs/em/docs/advanced/settings.md +++ b/docs/em/docs/advanced/settings.md @@ -148,9 +148,7 @@ Hello World from Python 👆 💪 ⚙️ 🌐 🎏 🔬 ⚒ & 🧰 👆 ⚙️ Pydantic 🏷, 💖 🎏 📊 🆎 & 🌖 🔬 ⏮️ `Field()`. -```Python hl_lines="2 5-8 11" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} /// tip @@ -166,9 +164,7 @@ Hello World from Python ⤴️ 👆 💪 ⚙️ 🆕 `settings` 🎚 👆 🈸: -```Python hl_lines="18-20" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} ### 🏃 💽 @@ -202,15 +198,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 🖼, 👆 💪 ✔️ 📁 `config.py` ⏮️: -```Python -{!../../docs_src/settings/app01/config.py!} -``` +{* ../../docs_src/settings/app01/config.py *} & ⤴️ ⚙️ ⚫️ 📁 `main.py`: -```Python hl_lines="3 11-13" -{!../../docs_src/settings/app01/main.py!} -``` +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} /// tip @@ -228,9 +220,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 👟 ⚪️➡️ ⏮️ 🖼, 👆 `config.py` 📁 💪 👀 💖: -```Python hl_lines="10" -{!../../docs_src/settings/app02/config.py!} -``` +{* ../../docs_src/settings/app02/config.py hl[10] *} 👀 👈 🔜 👥 🚫 ✍ 🔢 👐 `settings = Settings()`. @@ -238,9 +228,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 🔜 👥 ✍ 🔗 👈 📨 🆕 `config.Settings()`. -```Python hl_lines="5 11-12" -{!../../docs_src/settings/app02/main.py!} -``` +{* ../../docs_src/settings/app02/main.py hl[5,11:12] *} /// tip @@ -252,17 +240,13 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app & ⤴️ 👥 💪 🚚 ⚫️ ⚪️➡️ *➡ 🛠️ 🔢* 🔗 & ⚙️ ⚫️ 🙆 👥 💪 ⚫️. -```Python hl_lines="16 18-20" -{!../../docs_src/settings/app02/main.py!} -``` +{* ../../docs_src/settings/app02/main.py hl[16,18:20] *} ### ⚒ & 🔬 ⤴️ ⚫️ 🔜 📶 ⏩ 🚚 🎏 ⚒ 🎚 ⏮️ 🔬 🏗 🔗 🔐 `get_settings`: -```Python hl_lines="9-10 13 21" -{!../../docs_src/settings/app02/test_main.py!} -``` +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} 🔗 🔐 👥 ⚒ 🆕 💲 `admin_email` 🕐❔ 🏗 🆕 `Settings` 🎚, & ⤴️ 👥 📨 👈 🆕 🎚. @@ -303,9 +287,7 @@ APP_NAME="ChimichangApp" & ⤴️ ℹ 👆 `config.py` ⏮️: -```Python hl_lines="9-10" -{!../../docs_src/settings/app03/config.py!} -``` +{* ../../docs_src/settings/app03/config.py hl[9:10] *} 📥 👥 ✍ 🎓 `Config` 🔘 👆 Pydantic `Settings` 🎓, & ⚒ `env_file` 📁 ⏮️ 🇨🇻 📁 👥 💚 ⚙️. @@ -338,9 +320,7 @@ def get_settings(): ✋️ 👥 ⚙️ `@lru_cache` 👨‍🎨 🔛 🔝, `Settings` 🎚 🔜 ✍ 🕴 🕐, 🥇 🕰 ⚫️ 🤙. 👶 👶 -```Python hl_lines="1 10" -{!../../docs_src/settings/app03/main.py!} -``` +{* ../../docs_src/settings/app03/main.py hl[1,10] *} ⤴️ 🙆 🏁 🤙 `get_settings()` 🔗 ⏭ 📨, ↩️ 🛠️ 🔗 📟 `get_settings()` & 🏗 🆕 `Settings` 🎚, ⚫️ 🔜 📨 🎏 🎚 👈 📨 🔛 🥇 🤙, 🔄 & 🔄. diff --git a/docs/em/docs/advanced/sub-applications.md b/docs/em/docs/advanced/sub-applications.md index e19f3f234..7a802cd77 100644 --- a/docs/em/docs/advanced/sub-applications.md +++ b/docs/em/docs/advanced/sub-applications.md @@ -10,9 +10,7 @@ 🥇, ✍ 👑, 🔝-🎚, **FastAPI** 🈸, & 🚮 *➡ 🛠️*: -```Python hl_lines="3 6-8" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[3,6:8] *} ### 🎧-🈸 @@ -20,9 +18,7 @@ 👉 🎧-🈸 ➕1️⃣ 🐩 FastAPI 🈸, ✋️ 👉 1️⃣ 👈 🔜 "🗻": -```Python hl_lines="11 14-16" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,14:16] *} ### 🗻 🎧-🈸 @@ -30,9 +26,7 @@ 👉 💼, ⚫️ 🔜 📌 ➡ `/subapi`: -```Python hl_lines="11 19" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,19] *} ### ✅ 🏧 🛠️ 🩺 diff --git a/docs/em/docs/advanced/templates.md b/docs/em/docs/advanced/templates.md index 53428151d..ad4d4fc71 100644 --- a/docs/em/docs/advanced/templates.md +++ b/docs/em/docs/advanced/templates.md @@ -27,9 +27,7 @@ $ pip install jinja2 * 📣 `Request` 🔢 *➡ 🛠️* 👈 🔜 📨 📄. * ⚙️ `templates` 👆 ✍ ✍ & 📨 `TemplateResponse`, 🚶‍♀️ `request` 1️⃣ 🔑-💲 👫 Jinja2️⃣ "🔑". -```Python hl_lines="4 11 15-18" -{!../../docs_src/templates/tutorial001.py!} -``` +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *} /// note diff --git a/docs/em/docs/advanced/testing-dependencies.md b/docs/em/docs/advanced/testing-dependencies.md index 027767df1..b2b4b480d 100644 --- a/docs/em/docs/advanced/testing-dependencies.md +++ b/docs/em/docs/advanced/testing-dependencies.md @@ -28,9 +28,7 @@ & ⤴️ **FastAPI** 🔜 🤙 👈 🔐 ↩️ ⏮️ 🔗. -```Python hl_lines="28-29 32" -{!../../docs_src/dependency_testing/tutorial001.py!} -``` +{* ../../docs_src/dependency_testing/tutorial001.py hl[28:29,32] *} /// tip diff --git a/docs/em/docs/advanced/testing-events.md b/docs/em/docs/advanced/testing-events.md index 071d49c21..f62e9e069 100644 --- a/docs/em/docs/advanced/testing-events.md +++ b/docs/em/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ 🕐❔ 👆 💪 👆 🎉 🐕‍🦺 (`startup` & `shutdown`) 🏃 👆 💯, 👆 💪 ⚙️ `TestClient` ⏮️ `with` 📄: -```Python hl_lines="9-12 20-24" -{!../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/em/docs/advanced/testing-websockets.md b/docs/em/docs/advanced/testing-websockets.md index 62939c343..2a01de629 100644 --- a/docs/em/docs/advanced/testing-websockets.md +++ b/docs/em/docs/advanced/testing-websockets.md @@ -4,9 +4,7 @@ 👉, 👆 ⚙️ `TestClient` `with` 📄, 🔗*️⃣: -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} /// note diff --git a/docs/em/docs/advanced/using-request-directly.md b/docs/em/docs/advanced/using-request-directly.md index 3eb0067ad..9530d49bc 100644 --- a/docs/em/docs/advanced/using-request-directly.md +++ b/docs/em/docs/advanced/using-request-directly.md @@ -29,9 +29,7 @@ 👈 👆 💪 🔐 📨 🔗. -```Python hl_lines="1 7-8" -{!../../docs_src/using_request_directly/tutorial001.py!} -``` +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} 📣 *➡ 🛠️ 🔢* 🔢 ⏮️ 🆎 ➖ `Request` **FastAPI** 🔜 💭 🚶‍♀️ `Request` 👈 🔢. diff --git a/docs/em/docs/advanced/websockets.md b/docs/em/docs/advanced/websockets.md index 4b260e20a..cc6e5c5f0 100644 --- a/docs/em/docs/advanced/websockets.md +++ b/docs/em/docs/advanced/websockets.md @@ -38,17 +38,13 @@ $ pip install websockets ✋️ ⚫️ 🙅 🌌 🎯 🔛 💽-🚄 *️⃣ & ✔️ 👷 🖼: -```Python hl_lines="2 6-38 41-43" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} ## ✍ `websocket` 👆 **FastAPI** 🈸, ✍ `websocket`: -```Python hl_lines="1 46-47" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} /// note | 📡 ℹ @@ -62,9 +58,7 @@ $ pip install websockets 👆 *️⃣ 🛣 👆 💪 `await` 📧 & 📨 📧. -```Python hl_lines="48-52" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} 👆 💪 📨 & 📨 💱, ✍, & 🎻 💽. @@ -115,9 +109,7 @@ $ uvicorn main:app --reload 👫 👷 🎏 🌌 🎏 FastAPI 🔗/*➡ 🛠️*: -```Python hl_lines="66-77 76-91" -{!../../docs_src/websockets/tutorial002.py!} -``` +{* ../../docs_src/websockets/tutorial002.py hl[66:77,76:91] *} /// info @@ -162,9 +154,7 @@ $ uvicorn main:app --reload 🕐❔ *️⃣ 🔗 📪, `await websocket.receive_text()` 🔜 🤚 `WebSocketDisconnect` ⚠, ❔ 👆 💪 ⤴️ ✊ & 🍵 💖 👉 🖼. -```Python hl_lines="81-83" -{!../../docs_src/websockets/tutorial003.py!} -``` +{* ../../docs_src/websockets/tutorial003.py hl[81:83] *} 🔄 ⚫️ 👅: diff --git a/docs/em/docs/advanced/wsgi.md b/docs/em/docs/advanced/wsgi.md index 8c0008c74..d923347d5 100644 --- a/docs/em/docs/advanced/wsgi.md +++ b/docs/em/docs/advanced/wsgi.md @@ -12,9 +12,7 @@ & ⤴️ 🗻 👈 🔽 ➡. -```Python hl_lines="2-3 22" -{!../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,22] *} ## ✅ ⚫️ diff --git a/docs/em/docs/how-to/conditional-openapi.md b/docs/em/docs/how-to/conditional-openapi.md index a5932933a..e47ea0c35 100644 --- a/docs/em/docs/how-to/conditional-openapi.md +++ b/docs/em/docs/how-to/conditional-openapi.md @@ -29,9 +29,7 @@ 🖼: -```Python hl_lines="6 11" -{!../../docs_src/conditional_openapi/tutorial001.py!} -``` +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} 📥 👥 📣 ⚒ `openapi_url` ⏮️ 🎏 🔢 `"/openapi.json"`. diff --git a/docs/em/docs/how-to/custom-request-and-route.md b/docs/em/docs/how-to/custom-request-and-route.md index cd8811d4e..8974e7d95 100644 --- a/docs/em/docs/how-to/custom-request-and-route.md +++ b/docs/em/docs/how-to/custom-request-and-route.md @@ -42,9 +42,7 @@ 👈 🌌, 🎏 🛣 🎓 💪 🍵 🗜 🗜 ⚖️ 🗜 📨. -```Python hl_lines="8-15" -{!../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[8:15] *} ### ✍ 🛃 `GzipRoute` 🎓 @@ -56,9 +54,7 @@ 📥 👥 ⚙️ ⚫️ ✍ `GzipRequest` ⚪️➡️ ⏮️ 📨. -```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 | 📡 ℹ @@ -96,26 +92,18 @@ 🌐 👥 💪 🍵 📨 🔘 `try`/`except` 🍫: -```Python hl_lines="13 15" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[13,15] *} 🚥 ⚠ 📉, `Request` 👐 🔜 ↔, 👥 💪 ✍ & ⚒ ⚙️ 📨 💪 🕐❔ 🚚 ❌: -```Python hl_lines="16-18" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[16:18] *} ## 🛃 `APIRoute` 🎓 📻 👆 💪 ⚒ `route_class` 🔢 `APIRouter`: -```Python hl_lines="26" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[26] *} 👉 🖼, *➡ 🛠️* 🔽 `router` 🔜 ⚙️ 🛃 `TimedRoute` 🎓, & 🔜 ✔️ ➕ `X-Response-Time` 🎚 📨 ⏮️ 🕰 ⚫️ ✊ 🏗 📨: -```Python hl_lines="13-20" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[13:20] *} diff --git a/docs/em/docs/how-to/extending-openapi.md b/docs/em/docs/how-to/extending-openapi.md index 698c78ec1..c3e6c7f66 100644 --- a/docs/em/docs/how-to/extending-openapi.md +++ b/docs/em/docs/how-to/extending-openapi.md @@ -46,25 +46,19 @@ 🥇, ✍ 🌐 👆 **FastAPI** 🈸 🛎: -```Python hl_lines="1 4 7-9" -{!../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[1,4,7:9] *} ### 🏗 🗄 🔗 ⤴️, ⚙️ 🎏 🚙 🔢 🏗 🗄 🔗, 🔘 `custom_openapi()` 🔢: -```Python hl_lines="2 15-20" -{!../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[2,15:20] *} ### 🔀 🗄 🔗 🔜 👆 💪 🚮 📄 ↔, ❎ 🛃 `x-logo` `info` "🎚" 🗄 🔗: -```Python hl_lines="21-23" -{!../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[21:23] *} ### 💾 🗄 🔗 @@ -74,17 +68,13 @@ ⚫️ 🔜 🏗 🕴 🕐, & ⤴️ 🎏 💾 🔗 🔜 ⚙️ ⏭ 📨. -```Python hl_lines="13-14 24-25" -{!../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[13:14,24:25] *} ### 🔐 👩‍🔬 🔜 👆 💪 ❎ `.openapi()` 👩‍🔬 ⏮️ 👆 🆕 🔢. -```Python hl_lines="28" -{!../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[28] *} ### ✅ ⚫️ diff --git a/docs/em/docs/how-to/graphql.md b/docs/em/docs/how-to/graphql.md index 5d0d95567..083e9ebd2 100644 --- a/docs/em/docs/how-to/graphql.md +++ b/docs/em/docs/how-to/graphql.md @@ -35,9 +35,7 @@ 📥 🤪 🎮 ❔ 👆 💪 🛠️ 🍓 ⏮️ FastAPI: -```Python hl_lines="3 22 25-26" -{!../../docs_src/graphql/tutorial001.py!} -``` +{* ../../docs_src/graphql/tutorial001.py hl[3,22,25:26] *} 👆 💪 💡 🌅 🔃 🍓 🍓 🧾. diff --git a/docs/em/docs/tutorial/background-tasks.md b/docs/em/docs/tutorial/background-tasks.md index 6b14c6135..aed60c754 100644 --- a/docs/em/docs/tutorial/background-tasks.md +++ b/docs/em/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ 🥇, 🗄 `BackgroundTasks` & 🔬 🔢 👆 *➡ 🛠️ 🔢* ⏮️ 🆎 📄 `BackgroundTasks`: -```Python hl_lines="1 13" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** 🔜 ✍ 🎚 🆎 `BackgroundTasks` 👆 & 🚶‍♀️ ⚫️ 👈 🔢. @@ -33,17 +31,13 @@ & ✍ 🛠️ 🚫 ⚙️ `async` & `await`, 👥 🔬 🔢 ⏮️ 😐 `def`: -```Python hl_lines="6-9" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## 🚮 🖥 📋 🔘 👆 *➡ 🛠️ 🔢*, 🚶‍♀️ 👆 📋 🔢 *🖥 📋* 🎚 ⏮️ 👩‍🔬 `.add_task()`: -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` 📨 ❌: @@ -57,21 +51,7 @@ **FastAPI** 💭 ⚫️❔ 🔠 💼 & ❔ 🏤-⚙️ 🎏 🎚, 👈 🌐 🖥 📋 🔗 👯‍♂️ & 🏃 🖥 ⏮️: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="11 13 20 23" -{!> ../../docs_src/background_tasks/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *} 👉 🖼, 📧 🔜 ✍ `log.txt` 📁 *⏮️* 📨 📨. diff --git a/docs/em/docs/tutorial/body-fields.md b/docs/em/docs/tutorial/body-fields.md index be39b4a9a..f202284b5 100644 --- a/docs/em/docs/tutorial/body-fields.md +++ b/docs/em/docs/tutorial/body-fields.md @@ -6,21 +6,7 @@ 🥇, 👆 ✔️ 🗄 ⚫️: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="2" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001.py hl[4] *} /// warning @@ -32,21 +18,7 @@ 👆 💪 ⤴️ ⚙️ `Field` ⏮️ 🏷 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="9-12" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001.py hl[11:14] *} `Field` 👷 🎏 🌌 `Query`, `Path` & `Body`, ⚫️ ✔️ 🌐 🎏 🔢, ♒️. diff --git a/docs/em/docs/tutorial/body-multiple-params.md b/docs/em/docs/tutorial/body-multiple-params.md index 2e20c83f9..3a2f2bd54 100644 --- a/docs/em/docs/tutorial/body-multiple-params.md +++ b/docs/em/docs/tutorial/body-multiple-params.md @@ -8,21 +8,7 @@ & 👆 💪 📣 💪 🔢 📦, ⚒ 🔢 `None`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17-19" -{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial001.py hl[19:21] *} /// note @@ -45,21 +31,7 @@ ✋️ 👆 💪 📣 💗 💪 🔢, ✅ `item` & `user`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial002.py hl[22] *} 👉 💼, **FastAPI** 🔜 👀 👈 📤 🌅 🌘 1️⃣ 💪 🔢 🔢 (2️⃣ 🔢 👈 Pydantic 🏷). @@ -100,21 +72,7 @@ ✋️ 👆 💪 💡 **FastAPI** 😥 ⚫️ ➕1️⃣ 💪 🔑 ⚙️ `Body`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial003.py hl[22] *} 👉 💼, **FastAPI** 🔜 ⌛ 💪 💖: @@ -154,21 +112,7 @@ q: str | None = None 🖼: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="26" -{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial004.py hl[27] *} /// info @@ -190,21 +134,7 @@ item: Item = Body(embed=True) : -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="15" -{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial005.py hl[17] *} 👉 💼 **FastAPI** 🔜 ⌛ 💪 💖: diff --git a/docs/em/docs/tutorial/body-nested-models.md b/docs/em/docs/tutorial/body-nested-models.md index 3b56b7a07..6c8d5a610 100644 --- a/docs/em/docs/tutorial/body-nested-models.md +++ b/docs/em/docs/tutorial/body-nested-models.md @@ -6,21 +6,7 @@ 👆 💪 🔬 🔢 🏾. 🖼, 🐍 `list`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial001.py hl[14] *} 👉 🔜 ⚒ `tags` 📇, 👐 ⚫️ 🚫 📣 🆎 🔣 📇. @@ -34,9 +20,7 @@ ✋️ 🐍 ⏬ ⏭ 3️⃣.9️⃣ (3️⃣.6️⃣ & 🔛), 👆 🥇 💪 🗄 `List` ⚪️➡️ 🐩 🐍 `typing` 🕹: -```Python hl_lines="1" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### 📣 `list` ⏮️ 🆎 🔢 @@ -65,29 +49,7 @@ my_list: List[str] , 👆 🖼, 👥 💪 ⚒ `tags` 🎯 "📇 🎻": -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial002.py hl[14] *} ## ⚒ 🆎 @@ -97,29 +59,7 @@ my_list: List[str] ⤴️ 👥 💪 📣 `tags` ⚒ 🎻: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="1 14" -{!> ../../docs_src/body_nested_models/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial003.py hl[1,14] *} ⏮️ 👉, 🚥 👆 📨 📨 ⏮️ ❎ 📊, ⚫️ 🔜 🗜 ⚒ 😍 🏬. @@ -141,57 +81,13 @@ my_list: List[str] 🖼, 👥 💪 🔬 `Image` 🏷: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7-9" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004.py hl[9:11] *} ### ⚙️ 📊 🆎 & ⤴️ 👥 💪 ⚙️ ⚫️ 🆎 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004.py hl[20] *} 👉 🔜 ⛓ 👈 **FastAPI** 🔜 ⌛ 💪 🎏: @@ -224,29 +120,7 @@ my_list: List[str] 🖼, `Image` 🏷 👥 ✔️ `url` 🏑, 👥 💪 📣 ⚫️ ↩️ `str`, Pydantic `HttpUrl`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="2 8" -{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial005.py hl[4,10] *} 🎻 🔜 ✅ ☑ 📛, & 📄 🎻 🔗 / 🗄 ✅. @@ -254,29 +128,7 @@ my_list: List[str] 👆 💪 ⚙️ Pydantic 🏷 🏾 `list`, `set`, ♒️: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial006.py hl[20] *} 👉 🔜 ⌛ (🗜, ✔, 📄, ♒️) 🎻 💪 💖: @@ -314,29 +166,7 @@ my_list: List[str] 👆 💪 🔬 🎲 🙇 🐦 🏷: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7 12 18 21 25" -{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial007.py hl[9,14,20,23,27] *} /// info @@ -360,21 +190,7 @@ images: list[Image] : -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="15" -{!> ../../docs_src/body_nested_models/tutorial008.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="13" -{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial008.py hl[15] *} ## 👨‍🎨 🐕‍🦺 🌐 @@ -404,21 +220,7 @@ images: list[Image] 👉 💼, 👆 🔜 🚫 🙆 `dict` 📏 ⚫️ ✔️ `int` 🔑 ⏮️ `float` 💲: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/body_nested_models/tutorial009.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial009.py hl[9] *} /// tip diff --git a/docs/em/docs/tutorial/body.md b/docs/em/docs/tutorial/body.md index 3468fc512..09e1d7cca 100644 --- a/docs/em/docs/tutorial/body.md +++ b/docs/em/docs/tutorial/body.md @@ -22,21 +22,7 @@ 🥇, 👆 💪 🗄 `BaseModel` ⚪️➡️ `pydantic`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="4" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="2" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial001.py hl[4] *} ## ✍ 👆 💽 🏷 @@ -44,21 +30,7 @@ ⚙️ 🐩 🐍 🆎 🌐 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="7-11" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="5-9" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial001.py hl[7:11] *} 🎏 🕐❔ 📣 🔢 🔢, 🕐❔ 🏷 🔢 ✔️ 🔢 💲, ⚫️ 🚫 ✔. ⏪, ⚫️ ✔. ⚙️ `None` ⚒ ⚫️ 📦. @@ -86,21 +58,7 @@ 🚮 ⚫️ 👆 *➡ 🛠️*, 📣 ⚫️ 🎏 🌌 👆 📣 ➡ & 🔢 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial001.py hl[18] *} ...& 📣 🚮 🆎 🏷 👆 ✍, `Item`. @@ -167,21 +125,7 @@ 🔘 🔢, 👆 💪 🔐 🌐 🔢 🏷 🎚 🔗: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="21" -{!> ../../docs_src/body/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="19" -{!> ../../docs_src/body/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial002.py hl[21] *} ## 📨 💪 ➕ ➡ 🔢 @@ -189,21 +133,7 @@ **FastAPI** 🔜 🤔 👈 🔢 🔢 👈 🏏 ➡ 🔢 🔜 **✊ ⚪️➡️ ➡**, & 👈 🔢 🔢 👈 📣 Pydantic 🏷 🔜 **✊ ⚪️➡️ 📨 💪**. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="17-18" -{!> ../../docs_src/body/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="15-16" -{!> ../../docs_src/body/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial003.py hl[17:18] *} ## 📨 💪 ➕ ➡ ➕ 🔢 🔢 @@ -211,21 +141,7 @@ **FastAPI** 🔜 🤔 🔠 👫 & ✊ 📊 ⚪️➡️ ☑ 🥉. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial004.py hl[18] *} 🔢 🔢 🔜 🤔 ⏩: diff --git a/docs/em/docs/tutorial/cookie-params.md b/docs/em/docs/tutorial/cookie-params.md index 5126eab0a..4699fe2a5 100644 --- a/docs/em/docs/tutorial/cookie-params.md +++ b/docs/em/docs/tutorial/cookie-params.md @@ -6,21 +6,7 @@ 🥇 🗄 `Cookie`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001.py hl[3] *} ## 📣 `Cookie` 🔢 @@ -28,21 +14,7 @@ 🥇 💲 🔢 💲, 👆 💪 🚶‍♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001.py hl[9] *} /// note | 📡 ℹ diff --git a/docs/em/docs/tutorial/cors.md b/docs/em/docs/tutorial/cors.md index 801d66fdd..44ab4adc5 100644 --- a/docs/em/docs/tutorial/cors.md +++ b/docs/em/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * 🎯 🇺🇸🔍 👩‍🔬 (`POST`, `PUT`) ⚖️ 🌐 👫 ⏮️ 🃏 `"*"`. * 🎯 🇺🇸🔍 🎚 ⚖️ 🌐 👫 ⏮️ 🃏 `"*"`. -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} 🔢 🔢 ⚙️ `CORSMiddleware` 🛠️ 🚫 🔢, 👆 🔜 💪 🎯 🛠️ 🎯 🇨🇳, 👩‍🔬, ⚖️ 🎚, ✔ 🖥 ✔ ⚙️ 👫 ✖️-🆔 🔑. diff --git a/docs/em/docs/tutorial/debugging.md b/docs/em/docs/tutorial/debugging.md index 9320370d6..97e61a763 100644 --- a/docs/em/docs/tutorial/debugging.md +++ b/docs/em/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ 👆 FastAPI 🈸, 🗄 & 🏃 `uvicorn` 🔗: -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### 🔃 `__name__ == "__main__"` diff --git a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md index 3e58d506c..41938bc7b 100644 --- a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,21 +6,7 @@ ⏮️ 🖼, 👥 🛬 `dict` ⚪️➡️ 👆 🔗 ("☑"): -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} ✋️ ⤴️ 👥 🤚 `dict` 🔢 `commons` *➡ 🛠️ 🔢*. @@ -83,57 +69,15 @@ fluffy = Cat(name="Mr Fluffy") ⤴️, 👥 💪 🔀 🔗 "☑" `common_parameters` ⚪️➡️ 🔛 🎓 `CommonQueryParams`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="9-13" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002.py hl[11:15] *} 💸 🙋 `__init__` 👩‍🔬 ⚙️ ✍ 👐 🎓: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002.py hl[12] *} ...⚫️ ✔️ 🎏 🔢 👆 ⏮️ `common_parameters`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="6" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} 📚 🔢 ⚫️❔ **FastAPI** 🔜 ⚙️ "❎" 🔗. @@ -149,21 +93,7 @@ fluffy = Cat(name="Mr Fluffy") 🔜 👆 💪 📣 👆 🔗 ⚙️ 👉 🎓. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002.py hl[19] *} **FastAPI** 🤙 `CommonQueryParams` 🎓. 👉 ✍ "👐" 👈 🎓 & 👐 🔜 🚶‍♀️ 🔢 `commons` 👆 🔢. @@ -203,21 +133,7 @@ commons = Depends(CommonQueryParams) ...: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial003.py hl[19] *} ✋️ 📣 🆎 💡 👈 🌌 👆 👨‍🎨 🔜 💭 ⚫️❔ 🔜 🚶‍♀️ 🔢 `commons`, & ⤴️ ⚫️ 💪 ℹ 👆 ⏮️ 📟 🛠️, 🆎 ✅, ♒️: @@ -251,21 +167,7 @@ commons: CommonQueryParams = Depends() 🎏 🖼 🔜 ⤴️ 👀 💖: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial004.py hl[19] *} ...& **FastAPI** 🔜 💭 ⚫️❔. diff --git a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index cd36ad100..ab144a497 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,9 +14,7 @@ ⚫️ 🔜 `list` `Depends()`: -```Python hl_lines="17" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[17] *} 👉 🔗 🔜 🛠️/❎ 🎏 🌌 😐 🔗. ✋️ 👫 💲 (🚥 👫 📨 🙆) 🏆 🚫 🚶‍♀️ 👆 *➡ 🛠️ 🔢*. @@ -46,17 +44,13 @@ 👫 💪 📣 📨 📄 (💖 🎚) ⚖️ 🎏 🎧-🔗: -```Python hl_lines="6 11" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[6,11] *} ### 🤚 ⚠ 👫 🔗 💪 `raise` ⚠, 🎏 😐 🔗: -```Python hl_lines="8 13" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[8,13] *} ### 📨 💲 @@ -64,9 +58,7 @@ , 👆 💪 🏤-⚙️ 😐 🔗 (👈 📨 💲) 👆 ⏪ ⚙️ 👱 🙆, & ✋️ 💲 🏆 🚫 ⚙️, 🔗 🔜 🛠️: -```Python hl_lines="9 14" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[9,14] *} ## 🔗 👪 *➡ 🛠️* diff --git a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md index 2896be39d..1b37b1cf2 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md @@ -29,21 +29,15 @@ FastAPI 🐕‍🦺 🔗 👈 ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[8:11] *} 👈 ⚫️. @@ -67,41 +53,13 @@ ### 🗄 `Depends` -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[3] *} ### 📣 🔗, "⚓️" 🎏 🌌 👆 ⚙️ `Body`, `Query`, ♒️. ⏮️ 👆 *➡ 🛠️ 🔢* 🔢, ⚙️ `Depends` ⏮️ 🆕 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[15,20] *} 👐 👆 ⚙️ `Depends` 🔢 👆 🔢 🎏 🌌 👆 ⚙️ `Body`, `Query`, ♒️, `Depends` 👷 👄 🎏. diff --git a/docs/em/docs/tutorial/dependencies/sub-dependencies.md b/docs/em/docs/tutorial/dependencies/sub-dependencies.md index a1e7be134..6d622e952 100644 --- a/docs/em/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/sub-dependencies.md @@ -10,21 +10,7 @@ 👆 💪 ✍ 🥇 🔗 ("☑") 💖: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005.py hl[8:9] *} ⚫️ 📣 📦 🔢 🔢 `q` `str`, & ⤴️ ⚫️ 📨 ⚫️. @@ -34,21 +20,7 @@ ⤴️ 👆 💪 ✍ ➕1️⃣ 🔗 🔢 ("☑") 👈 🎏 🕰 📣 🔗 🚮 👍 (⚫️ "⚓️" 💁‍♂️): -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005.py hl[13] *} ➡️ 🎯 🔛 🔢 📣: @@ -61,21 +33,7 @@ ⤴️ 👥 💪 ⚙️ 🔗 ⏮️: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005.py hl[22] *} /// info diff --git a/docs/em/docs/tutorial/encoder.md b/docs/em/docs/tutorial/encoder.md index 21419ef21..ad05f701e 100644 --- a/docs/em/docs/tutorial/encoder.md +++ b/docs/em/docs/tutorial/encoder.md @@ -20,21 +20,7 @@ ⚫️ 📨 🎚, 💖 Pydantic 🏷, & 📨 🎻 🔗 ⏬: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="5 22" -{!> ../../docs_src/encoder/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="4 21" -{!> ../../docs_src/encoder/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/encoder/tutorial001.py hl[5,22] *} 👉 🖼, ⚫️ 🔜 🗜 Pydantic 🏷 `dict`, & `datetime` `str`. diff --git a/docs/em/docs/tutorial/extra-data-types.md b/docs/em/docs/tutorial/extra-data-types.md index 1d473bd93..f15a74b4a 100644 --- a/docs/em/docs/tutorial/extra-data-types.md +++ b/docs/em/docs/tutorial/extra-data-types.md @@ -55,36 +55,8 @@ 📥 🖼 *➡ 🛠️* ⏮️ 🔢 ⚙️ 🔛 🆎. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1 2 11-15" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001.py hl[1,3,12:16] *} 🗒 👈 🔢 🔘 🔢 ✔️ 👫 🐠 💽 🆎, & 👆 💪, 🖼, 🎭 😐 📅 🎭, 💖: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17-18" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001.py hl[18:19] *} diff --git a/docs/em/docs/tutorial/extra-models.md b/docs/em/docs/tutorial/extra-models.md index 4fdf196e8..19ab5b798 100644 --- a/docs/em/docs/tutorial/extra-models.md +++ b/docs/em/docs/tutorial/extra-models.md @@ -20,21 +20,7 @@ 📥 🏢 💭 ❔ 🏷 💪 👀 💖 ⏮️ 👫 🔐 🏑 & 🥉 🌐❔ 👫 ⚙️: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../docs_src/extra_models/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../docs_src/extra_models/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial001.py hl[9,11,16,22,24,29:30,33:35,40:41] *} ### 🔃 `**user_in.dict()` @@ -168,21 +154,7 @@ UserInDB( 👈 🌌, 👥 💪 📣 🔺 🖖 🏷 (⏮️ 🔢 `password`, ⏮️ `hashed_password` & 🍵 🔐): -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../docs_src/extra_models/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../docs_src/extra_models/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial002.py hl[9,15:16,19:20,23:24] *} ## `Union` ⚖️ `anyOf` @@ -198,21 +170,7 @@ UserInDB( /// -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial003.py hl[1,14:15,18:20,33] *} ### `Union` 🐍 3️⃣.1️⃣0️⃣ @@ -234,21 +192,7 @@ some_variable: PlaneItem | CarItem 👈, ⚙️ 🐩 🐍 `typing.List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛): -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="1 20" -{!> ../../docs_src/extra_models/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/extra_models/tutorial004_py39.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial004.py hl[1,20] *} ## 📨 ⏮️ ❌ `dict` @@ -258,21 +202,7 @@ some_variable: PlaneItem | CarItem 👉 💼, 👆 💪 ⚙️ `typing.Dict` (⚖️ `dict` 🐍 3️⃣.9️⃣ & 🔛): -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="1 8" -{!> ../../docs_src/extra_models/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="6" -{!> ../../docs_src/extra_models/tutorial005_py39.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial005.py hl[1,8] *} ## 🌃 diff --git a/docs/em/docs/tutorial/first-steps.md b/docs/em/docs/tutorial/first-steps.md index d6762422e..a8f936b01 100644 --- a/docs/em/docs/tutorial/first-steps.md +++ b/docs/em/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ 🙅 FastAPI 📁 💪 👀 💖 👉: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} 📁 👈 📁 `main.py`. @@ -133,9 +131,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ### 🔁 1️⃣: 🗄 `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` 🐍 🎓 👈 🚚 🌐 🛠️ 👆 🛠️. @@ -149,9 +145,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ### 🔁 2️⃣: ✍ `FastAPI` "👐" -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} 📥 `app` 🔢 🔜 "👐" 🎓 `FastAPI`. @@ -171,9 +165,7 @@ $ uvicorn main:app --reload 🚥 👆 ✍ 👆 📱 💖: -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} & 🚮 ⚫️ 📁 `main.py`, ⤴️ 👆 🔜 🤙 `uvicorn` 💖: @@ -250,9 +242,7 @@ https://example.com/items/foo #### 🔬 *➡ 🛠️ 👨‍🎨* -```Python hl_lines="6" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} `@app.get("/")` 💬 **FastAPI** 👈 🔢 ▶️️ 🔛 🈚 🚚 📨 👈 🚶: @@ -306,9 +296,7 @@ https://example.com/items/foo * **🛠️**: `get`. * **🔢**: 🔢 🔛 "👨‍🎨" (🔛 `@app.get("/")`). -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} 👉 🐍 🔢. @@ -320,9 +308,7 @@ https://example.com/items/foo 👆 💪 🔬 ⚫️ 😐 🔢 ↩️ `async def`: -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} /// note @@ -332,9 +318,7 @@ https://example.com/items/foo ### 🔁 5️⃣: 📨 🎚 -```Python hl_lines="8" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} 👆 💪 📨 `dict`, `list`, ⭐ 💲 `str`, `int`, ♒️. diff --git a/docs/em/docs/tutorial/handling-errors.md b/docs/em/docs/tutorial/handling-errors.md index e0edae51a..d73b730e1 100644 --- a/docs/em/docs/tutorial/handling-errors.md +++ b/docs/em/docs/tutorial/handling-errors.md @@ -25,9 +25,7 @@ ### 🗄 `HTTPException` -```Python hl_lines="1" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} ### 🤚 `HTTPException` 👆 📟 @@ -41,9 +39,7 @@ 👉 🖼, 🕐❔ 👩‍💻 📨 🏬 🆔 👈 🚫 🔀, 🤚 ⚠ ⏮️ 👔 📟 `404`: -```Python hl_lines="11" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} ### 📉 📨 @@ -81,9 +77,7 @@ ✋️ 💼 👆 💪 ⚫️ 🏧 😐, 👆 💪 🚮 🛃 🎚: -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial002.py!} -``` +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} ## ❎ 🛃 ⚠ 🐕‍🦺 @@ -95,9 +89,7 @@ 👆 💪 🚮 🛃 ⚠ 🐕‍🦺 ⏮️ `@app.exception_handler()`: -```Python hl_lines="5-7 13-18 24" -{!../../docs_src/handling_errors/tutorial003.py!} -``` +{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *} 📥, 🚥 👆 📨 `/unicorns/yolo`, *➡ 🛠️* 🔜 `raise` `UnicornException`. @@ -135,9 +127,7 @@ ⚠ 🐕‍🦺 🔜 📨 `Request` & ⚠. -```Python hl_lines="2 14-16" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *} 🔜, 🚥 👆 🚶 `/items/foo`, ↩️ 💆‍♂ 🔢 🎻 ❌ ⏮️: @@ -188,9 +178,7 @@ path -> item_id 🖼, 👆 💪 💚 📨 ✅ ✍ 📨 ↩️ 🎻 👫 ❌: -```Python hl_lines="3-4 9-11 22" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *} /// note | 📡 ℹ @@ -206,9 +194,7 @@ path -> item_id 👆 💪 ⚙️ ⚫️ ⏪ 🛠️ 👆 📱 🕹 💪 & ℹ ⚫️, 📨 ⚫️ 👩‍💻, ♒️. -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial005.py!} -``` +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} 🔜 🔄 📨 ❌ 🏬 💖: @@ -266,8 +252,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException 🚥 👆 💚 ⚙️ ⚠ ⤴️ ⏮️ 🎏 🔢 ⚠ 🐕‍🦺 ⚪️➡️ **FastAPI**, 👆 💪 🗄 & 🏤-⚙️ 🔢 ⚠ 🐕‍🦺 ⚪️➡️ `fastapi.exception_handlers`: -```Python hl_lines="2-5 15 21" -{!../../docs_src/handling_errors/tutorial006.py!} -``` +{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *} 👉 🖼 👆 `print`😅 ❌ ⏮️ 📶 🎨 📧, ✋️ 👆 🤚 💭. 👆 💪 ⚙️ ⚠ & ⤴️ 🏤-⚙️ 🔢 ⚠ 🐕‍🦺. diff --git a/docs/em/docs/tutorial/header-params.md b/docs/em/docs/tutorial/header-params.md index d9eafe77e..fa5e3a22b 100644 --- a/docs/em/docs/tutorial/header-params.md +++ b/docs/em/docs/tutorial/header-params.md @@ -6,21 +6,7 @@ 🥇 🗄 `Header`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial001.py hl[3] *} ## 📣 `Header` 🔢 @@ -28,21 +14,7 @@ 🥇 💲 🔢 💲, 👆 💪 🚶‍♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial001.py hl[9] *} /// note | 📡 ℹ @@ -74,21 +46,7 @@ 🚥 🤔 👆 💪 ❎ 🏧 🛠️ 🎦 🔠, ⚒ 🔢 `convert_underscores` `Header` `False`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="8" -{!> ../../docs_src/header_params/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial002.py hl[10] *} /// warning @@ -106,29 +64,7 @@ 🖼, 📣 🎚 `X-Token` 👈 💪 😑 🌅 🌘 🕐, 👆 💪 ✍: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial003.py hl[9] *} 🚥 👆 🔗 ⏮️ 👈 *➡ 🛠️* 📨 2️⃣ 🇺🇸🔍 🎚 💖: diff --git a/docs/em/docs/tutorial/metadata.md b/docs/em/docs/tutorial/metadata.md index a30db113d..eaf605de1 100644 --- a/docs/em/docs/tutorial/metadata.md +++ b/docs/em/docs/tutorial/metadata.md @@ -17,9 +17,7 @@ 👆 💪 ⚒ 👫 ⏩: -```Python hl_lines="3-16 19-31" -{!../../docs_src/metadata/tutorial001.py!} -``` +{* ../../docs_src/metadata/tutorial001.py hl[3:16,19:31] *} /// tip @@ -51,9 +49,7 @@ ✍ 🗃 👆 🔖 & 🚶‍♀️ ⚫️ `openapi_tags` 🔢: -```Python hl_lines="3-16 18" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} 👀 👈 👆 💪 ⚙️ ✍ 🔘 📛, 🖼 "💳" 🔜 🎦 🦁 (**💳**) & "🎀" 🔜 🎦 ❕ (_🎀_). @@ -67,9 +63,7 @@ ⚙️ `tags` 🔢 ⏮️ 👆 *➡ 🛠️* (& `APIRouter`Ⓜ) 🛠️ 👫 🎏 🔖: -```Python hl_lines="21 26" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} /// info @@ -97,9 +91,7 @@ 🖼, ⚒ ⚫️ 🍦 `/api/v1/openapi.json`: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial002.py!} -``` +{* ../../docs_src/metadata/tutorial002.py hl[3] *} 🚥 👆 💚 ❎ 🗄 🔗 🍕 👆 💪 ⚒ `openapi_url=None`, 👈 🔜 ❎ 🧾 👩‍💻 🔢 👈 ⚙️ ⚫️. @@ -116,6 +108,4 @@ 🖼, ⚒ 🦁 🎚 🍦 `/documentation` & ❎ 📄: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial003.py!} -``` +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/em/docs/tutorial/middleware.md b/docs/em/docs/tutorial/middleware.md index a794ab019..d203471e8 100644 --- a/docs/em/docs/tutorial/middleware.md +++ b/docs/em/docs/tutorial/middleware.md @@ -31,9 +31,7 @@ * ⤴️ ⚫️ 📨 `response` 🏗 🔗 *➡ 🛠️*. * 👆 💪 ⤴️ 🔀 🌅 `response` ⏭ 🛬 ⚫️. -```Python hl_lines="8-9 11 14" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} /// tip @@ -59,9 +57,7 @@ 🖼, 👆 💪 🚮 🛃 🎚 `X-Process-Time` ⚗ 🕰 🥈 👈 ⚫️ ✊ 🛠️ 📨 & 🏗 📨: -```Python hl_lines="10 12-13" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} ## 🎏 🛠️ diff --git a/docs/em/docs/tutorial/path-operation-configuration.md b/docs/em/docs/tutorial/path-operation-configuration.md index deb71c807..c6030c089 100644 --- a/docs/em/docs/tutorial/path-operation-configuration.md +++ b/docs/em/docs/tutorial/path-operation-configuration.md @@ -16,29 +16,7 @@ ✋️ 🚥 👆 🚫 💭 ⚫️❔ 🔠 🔢 📟, 👆 💪 ⚙️ ⌨ 📉 `status`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1 15" -{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *} 👈 👔 📟 🔜 ⚙️ 📨 & 🔜 🚮 🗄 🔗. @@ -54,29 +32,7 @@ 👆 💪 🚮 🔖 👆 *➡ 🛠️*, 🚶‍♀️ 🔢 `tags` ⏮️ `list` `str` (🛎 1️⃣ `str`): -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="15 20 25" -{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *} 👫 🔜 🚮 🗄 🔗 & ⚙️ 🏧 🧾 🔢: @@ -90,37 +46,13 @@ **FastAPI** 🐕‍🦺 👈 🎏 🌌 ⏮️ ✅ 🎻: -```Python hl_lines="1 8-10 13 18" -{!../../docs_src/path_operation_configuration/tutorial002b.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *} ## 📄 & 📛 👆 💪 🚮 `summary` & `description`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="18-19" -{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *} ## 📛 ⚪️➡️ #️⃣ @@ -128,29 +60,7 @@ 👆 💪 ✍ #️⃣ , ⚫️ 🔜 🔬 & 🖥 ☑ (✊ 🔘 🏧 #️⃣ 📐). -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17-25" -{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *} ⚫️ 🔜 ⚙️ 🎓 🩺: @@ -160,29 +70,7 @@ 👆 💪 ✔ 📨 📛 ⏮️ 🔢 `response_description`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="19" -{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial005.py hl[21] *} /// info @@ -204,9 +92,7 @@ 🚥 👆 💪 ™ *➡ 🛠️* 😢, ✋️ 🍵 ❎ ⚫️, 🚶‍♀️ 🔢 `deprecated`: -```Python hl_lines="16" -{!../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} ⚫️ 🔜 🎯 ™ 😢 🎓 🩺: diff --git a/docs/em/docs/tutorial/path-params-numeric-validations.md b/docs/em/docs/tutorial/path-params-numeric-validations.md index 74dbb55f7..b45e0557b 100644 --- a/docs/em/docs/tutorial/path-params-numeric-validations.md +++ b/docs/em/docs/tutorial/path-params-numeric-validations.md @@ -6,21 +6,7 @@ 🥇, 🗄 `Path` ⚪️➡️ `fastapi`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[3] *} ## 📣 🗃 @@ -28,21 +14,7 @@ 🖼, 📣 `title` 🗃 💲 ➡ 🔢 `item_id` 👆 💪 🆎: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[10] *} /// note @@ -70,9 +42,7 @@ , 👆 💪 📣 👆 🔢: -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} ## ✔ 🔢 👆 💪, 🎱 @@ -82,9 +52,7 @@ 🐍 🏆 🚫 🕳 ⏮️ 👈 `*`, ✋️ ⚫️ 🔜 💭 👈 🌐 📄 🔢 🔜 🤙 🇨🇻 ❌ (🔑-💲 👫), 💭 kwargs. 🚥 👫 🚫 ✔️ 🔢 💲. -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ## 🔢 🔬: 👑 🌘 ⚖️ 🌓 @@ -92,9 +60,7 @@ 📥, ⏮️ `ge=1`, `item_id` 🔜 💪 🔢 🔢 "`g`🅾 🌘 ⚖️ `e`🅾" `1`. -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *} ## 🔢 🔬: 🌘 🌘 & 🌘 🌘 ⚖️ 🌓 @@ -103,9 +69,7 @@ * `gt`: `g`🅾 `t`👲 * `le`: `l`👭 🌘 ⚖️ `e`🅾 -```Python hl_lines="9" -{!../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *} ## 🔢 🔬: 🎈, 🌘 🌘 & 🌘 🌘 @@ -117,9 +81,7 @@ & 🎏 lt. -```Python hl_lines="11" -{!../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *} ## 🌃 diff --git a/docs/em/docs/tutorial/path-params.md b/docs/em/docs/tutorial/path-params.md index daf5417eb..a914dc905 100644 --- a/docs/em/docs/tutorial/path-params.md +++ b/docs/em/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ 👆 💪 📣 ➡ "🔢" ⚖️ "🔢" ⏮️ 🎏 ❕ ⚙️ 🐍 📁 🎻: -```Python hl_lines="6-7" -{!../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} 💲 ➡ 🔢 `item_id` 🔜 🚶‍♀️ 👆 🔢 ❌ `item_id`. @@ -18,9 +16,7 @@ 👆 💪 📣 🆎 ➡ 🔢 🔢, ⚙️ 🐩 🐍 🆎 ✍: -```Python hl_lines="7" -{!../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} 👉 💼, `item_id` 📣 `int`. @@ -121,17 +117,13 @@ ↩️ *➡ 🛠️* 🔬 ✔, 👆 💪 ⚒ 💭 👈 ➡ `/users/me` 📣 ⏭ 1️⃣ `/users/{user_id}`: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} ⏪, ➡ `/users/{user_id}` 🔜 🏏 `/users/me`, "💭" 👈 ⚫️ 📨 🔢 `user_id` ⏮️ 💲 `"me"`. ➡, 👆 🚫🔜 ↔ ➡ 🛠️: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003b.py!} -``` +{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *} 🥇 🕐 🔜 🕧 ⚙️ ↩️ ➡ 🏏 🥇. @@ -147,9 +139,7 @@ ⤴️ ✍ 🎓 🔢 ⏮️ 🔧 💲, ❔ 🔜 💪 ☑ 💲: -```Python hl_lines="1 6-9" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} /// info @@ -167,9 +157,7 @@ ⤴️ ✍ *➡ 🔢* ⏮️ 🆎 ✍ ⚙️ 🔢 🎓 👆 ✍ (`ModelName`): -```Python hl_lines="16" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### ✅ 🩺 @@ -185,17 +173,13 @@ 👆 💪 🔬 ⚫️ ⏮️ *🔢 👨‍🎓* 👆 ✍ 🔢 `ModelName`: -```Python hl_lines="17" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### 🤚 *🔢 💲* 👆 💪 🤚 ☑ 💲 ( `str` 👉 💼) ⚙️ `model_name.value`, ⚖️ 🏢, `your_enum_member.value`: -```Python hl_lines="20" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} /// tip @@ -209,9 +193,7 @@ 👫 🔜 🗜 👫 🔗 💲 (🎻 👉 💼) ⏭ 🛬 👫 👩‍💻: -```Python hl_lines="18 21 23" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} 👆 👩‍💻 👆 🔜 🤚 🎻 📨 💖: @@ -250,9 +232,7 @@ , 👆 💪 ⚙️ ⚫️ ⏮️: -```Python hl_lines="6" -{!../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} /// tip diff --git a/docs/em/docs/tutorial/query-params-str-validations.md b/docs/em/docs/tutorial/query-params-str-validations.md index f75c0a26f..dbaab5735 100644 --- a/docs/em/docs/tutorial/query-params-str-validations.md +++ b/docs/em/docs/tutorial/query-params-str-validations.md @@ -4,21 +4,7 @@ ➡️ ✊ 👉 🈸 🖼: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *} 🔢 🔢 `q` 🆎 `Union[str, None]` (⚖️ `str | None` 🐍 3️⃣.1️⃣0️⃣), 👈 ⛓ 👈 ⚫️ 🆎 `str` ✋️ 💪 `None`, & 👐, 🔢 💲 `None`, FastAPI 🔜 💭 ⚫️ 🚫 ✔. @@ -38,41 +24,13 @@ FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. 🏆 👈, 🥇 🗄 `Query` ⚪️➡️ `fastapi`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3" -{!> ../../docs_src/query_params_str_validations/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1" -{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *} ## ⚙️ `Query` 🔢 💲 & 🔜 ⚙️ ⚫️ 🔢 💲 👆 🔢, ⚒ 🔢 `max_length` 5️⃣0️⃣: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} 👥 ✔️ ❎ 🔢 💲 `None` 🔢 ⏮️ `Query()`, 👥 💪 🔜 ⚒ 🔢 💲 ⏮️ 🔢 `Query(default=None)`, ⚫️ 🍦 🎏 🎯 ⚖ 👈 🔢 💲. @@ -134,41 +92,13 @@ q: Union[str, None] = Query(default=None, max_length=50) 👆 💪 🚮 🔢 `min_length`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[10] *} ## 🚮 🥔 🧬 👆 💪 🔬 🥔 🧬 👈 🔢 🔜 🏏: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[11] *} 👉 🎯 🥔 🧬 ✅ 👈 📨 🔢 💲: @@ -186,9 +116,7 @@ q: Union[str, None] = Query(default=None, max_length=50) ➡️ 💬 👈 👆 💚 📣 `q` 🔢 🔢 ✔️ `min_length` `3`, & ✔️ 🔢 💲 `"fixedquery"`: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial005.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} /// note @@ -218,17 +146,13 @@ q: Union[str, None] = Query(default=None, min_length=3) , 🕐❔ 👆 💪 📣 💲 ✔ ⏪ ⚙️ `Query`, 👆 💪 🎯 🚫 📣 🔢 💲: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial006.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} ### ✔ ⏮️ ❕ (`...`) 📤 🎛 🌌 🎯 📣 👈 💲 ✔. 👆 💪 ⚒ `default` 🔢 🔑 💲 `...`: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial006b.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006b.py hl[7] *} /// info @@ -246,21 +170,7 @@ q: Union[str, None] = Query(default=None, min_length=3) 👈, 👆 💪 📣 👈 `None` ☑ 🆎 ✋️ ⚙️ `default=...`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006c.py hl[9] *} /// tip @@ -272,9 +182,7 @@ Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🚥 👆 💭 😬 ⚙️ `...`, 👆 💪 🗄 & ⚙️ `Required` ⚪️➡️ Pydantic: -```Python hl_lines="2 8" -{!../../docs_src/query_params_str_validations/tutorial006d.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006d.py hl[2,8] *} /// tip @@ -288,29 +196,7 @@ Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🖼, 📣 🔢 🔢 `q` 👈 💪 😑 💗 🕰 📛, 👆 💪 ✍: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} ⤴️, ⏮️ 📛 💖: @@ -345,21 +231,7 @@ http://localhost:8000/items/?q=foo&q=bar & 👆 💪 🔬 🔢 `list` 💲 🚥 👌 🚚: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} 🚥 👆 🚶: @@ -382,9 +254,7 @@ http://localhost:8000/items/ 👆 💪 ⚙️ `list` 🔗 ↩️ `List[str]` (⚖️ `list[str]` 🐍 3️⃣.9️⃣ ➕): -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} /// note @@ -410,39 +280,11 @@ http://localhost:8000/items/ 👆 💪 🚮 `title`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *} & `description`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="13" -{!> ../../docs_src/query_params_str_validations/tutorial008.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## 📛 🔢 @@ -462,21 +304,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems ⤴️ 👆 💪 📣 `alias`, & 👈 📛 ⚫️❔ 🔜 ⚙️ 🔎 🔢 💲: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} ## 😛 🔢 @@ -486,21 +314,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems ⤴️ 🚶‍♀️ 🔢 `deprecated=True` `Query`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/query_params_str_validations/tutorial010.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="16" -{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} 🩺 🔜 🎦 ⚫️ 💖 👉: @@ -510,21 +324,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 🚫 🔢 🔢 ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚒ 🔢 `include_in_schema` `Query` `False`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial014.py hl[10] *} ## 🌃 diff --git a/docs/em/docs/tutorial/query-params.md b/docs/em/docs/tutorial/query-params.md index c8432f182..5c8d868a9 100644 --- a/docs/em/docs/tutorial/query-params.md +++ b/docs/em/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ 🕐❔ 👆 📣 🎏 🔢 🔢 👈 🚫 🍕 ➡ 🔢, 👫 🔁 🔬 "🔢" 🔢. -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} 🔢 ⚒ 🔑-💲 👫 👈 🚶 ⏮️ `?` 📛, 🎏 `&` 🦹. @@ -63,21 +61,7 @@ http://127.0.0.1:8000/items/?skip=20 🎏 🌌, 👆 💪 📣 📦 🔢 🔢, ⚒ 👫 🔢 `None`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial002.py hl[9] *} 👉 💼, 🔢 🔢 `q` 🔜 📦, & 🔜 `None` 🔢. @@ -91,21 +75,7 @@ http://127.0.0.1:8000/items/?skip=20 👆 💪 📣 `bool` 🆎, & 👫 🔜 🗜: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial003.py hl[9] *} 👉 💼, 🚥 👆 🚶: @@ -148,21 +118,7 @@ http://127.0.0.1:8000/items/foo?short=yes 👫 🔜 🔬 📛: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="8 10" -{!> ../../docs_src/query_params/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="6 8" -{!> ../../docs_src/query_params/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial004.py hl[8,10] *} ## ✔ 🔢 🔢 @@ -172,9 +128,7 @@ http://127.0.0.1:8000/items/foo?short=yes ✋️ 🕐❔ 👆 💚 ⚒ 🔢 🔢 ✔, 👆 💪 🚫 📣 🙆 🔢 💲: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} 📥 🔢 🔢 `needy` ✔ 🔢 🔢 🆎 `str`. @@ -218,21 +172,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy & ↗️, 👆 💪 🔬 🔢 ✔, ✔️ 🔢 💲, & 🍕 📦: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/query_params/tutorial006.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="8" -{!> ../../docs_src/query_params/tutorial006_py310.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial006.py hl[10] *} 👉 💼, 📤 3️⃣ 🔢 🔢: diff --git a/docs/em/docs/tutorial/request-files.md b/docs/em/docs/tutorial/request-files.md index 9dcad81b4..c3bdeafd4 100644 --- a/docs/em/docs/tutorial/request-files.md +++ b/docs/em/docs/tutorial/request-files.md @@ -16,17 +16,13 @@ 🗄 `File` & `UploadFile` ⚪️➡️ `fastapi`: -```Python hl_lines="1" -{!../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[1] *} ## 🔬 `File` 🔢 ✍ 📁 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Form`: -```Python hl_lines="7" -{!../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[7] *} /// info @@ -54,9 +50,7 @@ 🔬 📁 🔢 ⏮️ 🆎 `UploadFile`: -```Python hl_lines="12" -{!../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[12] *} ⚙️ `UploadFile` ✔️ 📚 📈 🤭 `bytes`: @@ -139,29 +133,13 @@ contents = myfile.file.read() 👆 💪 ⚒ 📁 📦 ⚙️ 🐩 🆎 ✍ & ⚒ 🔢 💲 `None`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7 14" -{!> ../../docs_src/request_files/tutorial001_02_py310.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_02.py hl[9,17] *} ## `UploadFile` ⏮️ 🌖 🗃 👆 💪 ⚙️ `File()` ⏮️ `UploadFile`, 🖼, ⚒ 🌖 🗃: -```Python hl_lines="13" -{!../../docs_src/request_files/tutorial001_03.py!} -``` +{* ../../docs_src/request_files/tutorial001_03.py hl[13] *} ## 💗 📁 📂 @@ -171,21 +149,7 @@ contents = myfile.file.read() ⚙️ 👈, 📣 📇 `bytes` ⚖️ `UploadFile`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="8 13" -{!> ../../docs_src/request_files/tutorial002_py39.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial002.py hl[10,15] *} 👆 🔜 📨, 📣, `list` `bytes` ⚖️ `UploadFile`Ⓜ. @@ -201,21 +165,7 @@ contents = myfile.file.read() & 🎏 🌌 ⏭, 👆 💪 ⚙️ `File()` ⚒ 🌖 🔢, `UploadFile`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/request_files/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="16" -{!> ../../docs_src/request_files/tutorial003_py39.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial003.py hl[18] *} ## 🌃 diff --git a/docs/em/docs/tutorial/request-forms-and-files.md b/docs/em/docs/tutorial/request-forms-and-files.md index 80793dae4..680b1a96a 100644 --- a/docs/em/docs/tutorial/request-forms-and-files.md +++ b/docs/em/docs/tutorial/request-forms-and-files.md @@ -12,17 +12,13 @@ ## 🗄 `File` & `Form` -```Python hl_lines="1" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[1] *} ## 🔬 `File` & `Form` 🔢 ✍ 📁 & 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`: -```Python hl_lines="8" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[8] *} 📁 & 📨 🏑 🔜 📂 📨 📊 & 👆 🔜 📨 📁 & 📨 🏑. diff --git a/docs/em/docs/tutorial/request-forms.md b/docs/em/docs/tutorial/request-forms.md index d364d2c92..1cc1ea5dc 100644 --- a/docs/em/docs/tutorial/request-forms.md +++ b/docs/em/docs/tutorial/request-forms.md @@ -14,17 +14,13 @@ 🗄 `Form` ⚪️➡️ `fastapi`: -```Python hl_lines="1" -{!../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[1] *} ## 🔬 `Form` 🔢 ✍ 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`: -```Python hl_lines="7" -{!../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[7] *} 🖼, 1️⃣ 🌌 Oauth2️⃣ 🔧 💪 ⚙️ (🤙 "🔐 💧") ⚫️ ✔ 📨 `username` & `password` 📨 🏑. diff --git a/docs/em/docs/tutorial/response-model.md b/docs/em/docs/tutorial/response-model.md index fb5c17dd6..477376458 100644 --- a/docs/em/docs/tutorial/response-model.md +++ b/docs/em/docs/tutorial/response-model.md @@ -4,29 +4,7 @@ 👆 💪 ⚙️ **🆎 ✍** 🎏 🌌 👆 🔜 🔢 💽 🔢 **🔢**, 👆 💪 ⚙️ Pydantic 🏷, 📇, 📖, 📊 💲 💖 🔢, 🎻, ♒️. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="16 21" -{!> ../../docs_src/response_model/tutorial001_01_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001_01.py hl[18,23] *} FastAPI 🔜 ⚙️ 👉 📨 🆎: @@ -59,29 +37,7 @@ FastAPI 🔜 ⚙️ 👉 📨 🆎: * `@app.delete()` * ♒️. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001.py hl[17,22,24:27] *} /// note @@ -113,21 +69,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** 📥 👥 📣 `UserIn` 🏷, ⚫️ 🔜 🔌 🔢 🔐: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9 11" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7 9" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002.py hl[9,11] *} /// info @@ -140,21 +82,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** & 👥 ⚙️ 👉 🏷 📣 👆 🔢 & 🎏 🏷 📣 👆 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="16" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002.py hl[18] *} 🔜, 🕐❔ 🖥 🏗 👩‍💻 ⏮️ 🔐, 🛠️ 🔜 📨 🎏 🔐 📨. @@ -172,57 +100,15 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** 👥 💪 ↩️ ✍ 🔢 🏷 ⏮️ 🔢 🔐 & 🔢 🏷 🍵 ⚫️: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003.py hl[9,11,16] *} 📥, ✋️ 👆 *➡ 🛠️ 🔢* 🛬 🎏 🔢 👩‍💻 👈 🔌 🔐: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003.py hl[24] *} ...👥 📣 `response_model` 👆 🏷 `UserOut`, 👈 🚫 🔌 🔐: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003.py hl[22] *} , **FastAPI** 🔜 ✊ 💅 🖥 👅 🌐 💽 👈 🚫 📣 🔢 🏷 (⚙️ Pydantic). @@ -246,21 +132,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** & 👈 💼, 👥 💪 ⚙️ 🎓 & 🧬 ✊ 📈 🔢 **🆎 ✍** 🤚 👍 🐕‍🦺 👨‍🎨 & 🧰, & 🤚 FastAPI **💽 🖥**. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9-13 15-16 20" -{!> ../../docs_src/response_model/tutorial003_01.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7-10 13-14 18" -{!> ../../docs_src/response_model/tutorial003_01_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_01.py hl[9:13,15:16,20] *} ⏮️ 👉, 👥 🤚 🏭 🐕‍🦺, ⚪️➡️ 👨‍🎨 & ✍ 👉 📟 ☑ ⚖ 🆎, ✋️ 👥 🤚 💽 🖥 ⚪️➡️ FastAPI. @@ -302,9 +174,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 🏆 ⚠ 💼 🔜 [🛬 📨 🔗 🔬 ⏪ 🏧 🩺](../advanced/response-directly.md){.internal-link target=_blank}. -```Python hl_lines="8 10-11" -{!> ../../docs_src/response_model/tutorial003_02.py!} -``` +{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *} 👉 🙅 💼 🍵 🔁 FastAPI ↩️ 📨 🆎 ✍ 🎓 (⚖️ 🏿) `Response`. @@ -314,9 +184,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 💪 ⚙️ 🏿 `Response` 🆎 ✍: -```Python hl_lines="8-9" -{!> ../../docs_src/response_model/tutorial003_03.py!} -``` +{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *} 👉 🔜 👷 ↩️ `RedirectResponse` 🏿 `Response`, & FastAPI 🔜 🔁 🍵 👉 🙅 💼. @@ -326,21 +194,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 🎏 🔜 🔨 🚥 👆 ✔️ 🕳 💖 🇪🇺 🖖 🎏 🆎 🌐❔ 1️⃣ ⚖️ 🌅 👫 🚫 ☑ Pydantic 🆎, 🖼 👉 🔜 ❌ 👶: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/response_model/tutorial003_04.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="8" -{!> ../../docs_src/response_model/tutorial003_04_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_04.py hl[10] *} ...👉 ❌ ↩️ 🆎 ✍ 🚫 Pydantic 🆎 & 🚫 👁 `Response` 🎓 ⚖️ 🏿, ⚫️ 🇪🇺 (🙆 2️⃣) 🖖 `Response` & `dict`. @@ -352,21 +206,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👉 💼, 👆 💪 ❎ 📨 🏷 ⚡ ⚒ `response_model=None`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/response_model/tutorial003_05.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/response_model/tutorial003_05_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_05.py hl[9] *} 👉 🔜 ⚒ FastAPI 🚶 📨 🏷 ⚡ & 👈 🌌 👆 💪 ✔️ 🙆 📨 🆎 ✍ 👆 💪 🍵 ⚫️ 🤕 👆 FastAPI 🈸. 👶 @@ -374,29 +214,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 📨 🏷 💪 ✔️ 🔢 💲, 💖: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="9 11-12" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004.py hl[11,13:14] *} * `description: Union[str, None] = None` (⚖️ `str | None = None` 🐍 3️⃣.1️⃣0️⃣) ✔️ 🔢 `None`. * `tax: float = 10.5` ✔️ 🔢 `10.5`. @@ -410,29 +228,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 💪 ⚒ *➡ 🛠️ 👨‍🎨* 🔢 `response_model_exclude_unset=True`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004.py hl[24] *} & 👈 🔢 💲 🏆 🚫 🔌 📨, 🕴 💲 🤙 ⚒. @@ -521,21 +317,7 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t /// -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial005.py hl[31,37] *} /// tip @@ -549,21 +331,7 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t 🚥 👆 💭 ⚙️ `set` & ⚙️ `list` ⚖️ `tuple` ↩️, FastAPI 🔜 🗜 ⚫️ `set` & ⚫️ 🔜 👷 ☑: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial006.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial006_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial006.py hl[31,37] *} ## 🌃 diff --git a/docs/em/docs/tutorial/response-status-code.md b/docs/em/docs/tutorial/response-status-code.md index 478060326..413ceb916 100644 --- a/docs/em/docs/tutorial/response-status-code.md +++ b/docs/em/docs/tutorial/response-status-code.md @@ -8,9 +8,7 @@ * `@app.delete()` * ♒️. -```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 @@ FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅‍♂ 📨 ➡️ 👀 ⏮️ 🖼 🔄: -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201` 👔 📟 "✍". @@ -86,9 +82,7 @@ FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅‍♂ 📨 👆 💪 ⚙️ 🏪 🔢 ⚪️➡️ `fastapi.status`. -```Python hl_lines="1 6" -{!../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} 👫 🏪, 👫 🧑‍🤝‍🧑 🎏 🔢, ✋️ 👈 🌌 👆 💪 ⚙️ 👨‍🎨 📋 🔎 👫: diff --git a/docs/em/docs/tutorial/schema-extra-example.md b/docs/em/docs/tutorial/schema-extra-example.md index e4f877a8e..1bd314c51 100644 --- a/docs/em/docs/tutorial/schema-extra-example.md +++ b/docs/em/docs/tutorial/schema-extra-example.md @@ -8,21 +8,7 @@ 👆 💪 📣 `example` Pydantic 🏷 ⚙️ `Config` & `schema_extra`, 🔬 Pydantic 🩺: 🔗 🛃: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="15-23" -{!> ../../docs_src/schema_extra_example/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="13-21" -{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial001.py hl[15:23] *} 👈 ➕ ℹ 🔜 🚮-🔢 **🎻 🔗** 👈 🏷, & ⚫️ 🔜 ⚙️ 🛠️ 🩺. @@ -40,21 +26,7 @@ 👆 💪 ⚙️ 👉 🚮 `example` 🔠 🏑: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="4 10-13" -{!> ../../docs_src/schema_extra_example/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="2 8-11" -{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial002.py hl[4,10:13] *} /// warning @@ -80,21 +52,7 @@ 📥 👥 🚶‍♀️ `example` 📊 ⌛ `Body()`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="20-25" -{!> ../../docs_src/schema_extra_example/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="18-23" -{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial003.py hl[20:25] *} ### 🖼 🩺 🎚 @@ -115,21 +73,7 @@ * `value`: 👉 ☑ 🖼 🎦, ✅ `dict`. * `externalValue`: 🎛 `value`, 📛 ☝ 🖼. 👐 👉 5️⃣📆 🚫 🐕‍🦺 📚 🧰 `value`. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="21-47" -{!> ../../docs_src/schema_extra_example/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="19-45" -{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial004.py hl[21:47] *} ### 🖼 🩺 🎚 diff --git a/docs/em/docs/tutorial/security/first-steps.md b/docs/em/docs/tutorial/security/first-steps.md index 21c48757f..8fb459a65 100644 --- a/docs/em/docs/tutorial/security/first-steps.md +++ b/docs/em/docs/tutorial/security/first-steps.md @@ -20,9 +20,7 @@ 📁 🖼 📁 `main.py`: -```Python -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py *} ## 🏃 ⚫️ @@ -128,9 +126,7 @@ Oauth2️⃣ 🔧 👈 👩‍💻 ⚖️ 🛠️ 💪 🔬 💽 👈 🔓 👩 🕐❔ 👥 ✍ 👐 `OAuth2PasswordBearer` 🎓 👥 🚶‍♀️ `tokenUrl` 🔢. 👉 🔢 🔌 📛 👈 👩‍💻 (🕸 🏃 👩‍💻 🖥) 🔜 ⚙️ 📨 `username` & `password` ✔ 🤚 🤝. -```Python hl_lines="6" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[6] *} /// tip @@ -168,9 +164,7 @@ oauth2_scheme(some, parameters) 🔜 👆 💪 🚶‍♀️ 👈 `oauth2_scheme` 🔗 ⏮️ `Depends`. -```Python hl_lines="10" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} 👉 🔗 🔜 🚚 `str` 👈 🛠️ 🔢 `token` *➡ 🛠️ 🔢*. diff --git a/docs/em/docs/tutorial/security/get-current-user.md b/docs/em/docs/tutorial/security/get-current-user.md index 4e5b4ebfc..2f4a26f35 100644 --- a/docs/em/docs/tutorial/security/get-current-user.md +++ b/docs/em/docs/tutorial/security/get-current-user.md @@ -2,9 +2,7 @@ ⏮️ 📃 💂‍♂ ⚙️ (❔ 🧢 🔛 🔗 💉 ⚙️) 🤝 *➡ 🛠️ 🔢* `token` `str`: -```Python hl_lines="10" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} ✋️ 👈 🚫 👈 ⚠. @@ -16,21 +14,7 @@ 🎏 🌌 👥 ⚙️ Pydantic 📣 💪, 👥 💪 ⚙️ ⚫️ 🙆 🙆: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="3 10-14" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[5,12:16] *} ## ✍ `get_current_user` 🔗 @@ -42,61 +26,19 @@ 🎏 👥 🔨 ⏭ *➡ 🛠️* 🔗, 👆 🆕 🔗 `get_current_user` 🔜 📨 `token` `str` ⚪️➡️ 🎧-🔗 `oauth2_scheme`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="23" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[25] *} ## 🤚 👩‍💻 `get_current_user` 🔜 ⚙️ (❌) 🚙 🔢 👥 ✍, 👈 ✊ 🤝 `str` & 📨 👆 Pydantic `User` 🏷: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17-20 24-25" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[19:22,26:27] *} ## 💉 ⏮️ 👩‍💻 🔜 👥 💪 ⚙️ 🎏 `Depends` ⏮️ 👆 `get_current_user` *➡ 🛠️*: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="29" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[31] *} 👀 👈 👥 📣 🆎 `current_user` Pydantic 🏷 `User`. @@ -150,21 +92,7 @@ & 🌐 👉 💯 *➡ 🛠️* 💪 🤪 3️⃣ ⏸: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="28-30" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[30:32] *} ## 🌃 diff --git a/docs/em/docs/tutorial/security/oauth2-jwt.md b/docs/em/docs/tutorial/security/oauth2-jwt.md index 95fa58f71..ee7bc2d28 100644 --- a/docs/em/docs/tutorial/security/oauth2-jwt.md +++ b/docs/em/docs/tutorial/security/oauth2-jwt.md @@ -118,21 +118,7 @@ $ pip install "passlib[bcrypt]" & ➕1️⃣ 1️⃣ 🔓 & 📨 👩‍💻. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="6 47 54-55 58-59 68-74" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial004.py hl[7,48,55:56,59:60,69:75] *} /// note @@ -168,21 +154,7 @@ $ openssl rand -hex 32 ✍ 🚙 🔢 🏗 🆕 🔐 🤝. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="5 11-13 27-29 77-85" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial004.py hl[6,12:14,28:30,78:86] *} ## ℹ 🔗 @@ -192,21 +164,7 @@ $ openssl rand -hex 32 🚥 🤝 ❌, 📨 🇺🇸🔍 ❌ ▶️️ ↖️. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="89-106" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="88-105" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial004.py hl[89:106] *} ## ℹ `/token` *➡ 🛠️* @@ -214,21 +172,7 @@ $ openssl rand -hex 32 ✍ 🎰 🥙 🔐 🤝 & 📨 ⚫️. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="115-130" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="114-129" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial004.py hl[115:130] *} ### 📡 ℹ 🔃 🥙 "📄" `sub` diff --git a/docs/em/docs/tutorial/security/simple-oauth2.md b/docs/em/docs/tutorial/security/simple-oauth2.md index 43d928ce7..1fd513d48 100644 --- a/docs/em/docs/tutorial/security/simple-oauth2.md +++ b/docs/em/docs/tutorial/security/simple-oauth2.md @@ -52,21 +52,7 @@ Oauth2️⃣ 👫 🎻. 🥇, 🗄 `OAuth2PasswordRequestForm`, & ⚙️ ⚫️ 🔗 ⏮️ `Depends` *➡ 🛠️* `/token`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="4 76" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="2 74" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[4,76] *} `OAuth2PasswordRequestForm` 🎓 🔗 👈 📣 📨 💪 ⏮️: @@ -114,21 +100,7 @@ Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋ ❌, 👥 ⚙️ ⚠ `HTTPException`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3 77-79" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1 75-77" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[3,77:79] *} ### ✅ 🔐 @@ -154,21 +126,7 @@ Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋ , 🧙‍♀ 🏆 🚫 💪 🔄 ⚙️ 👈 🎏 🔐 ➕1️⃣ ⚙️ (📚 👩‍💻 ⚙️ 🎏 🔐 🌐, 👉 🔜 ⚠). -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="80-83" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="78-81" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[80:83] *} #### 🔃 `**user_dict` @@ -210,21 +168,7 @@ UserInDB( /// -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="85" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="83" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[85] *} /// tip @@ -250,21 +194,7 @@ UserInDB( , 👆 🔗, 👥 🔜 🕴 🤚 👩‍💻 🚥 👩‍💻 🔀, ☑ 🔓, & 🦁: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="58-66 69-72 90" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="55-64 67-70 88" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[58:66,69:72,90] *} /// info diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md deleted file mode 100644 index 49162dd62..000000000 --- a/docs/em/docs/tutorial/sql-databases.md +++ /dev/null @@ -1,900 +0,0 @@ -# 🗄 (🔗) 💽 - -**FastAPI** 🚫 🚚 👆 ⚙️ 🗄 (🔗) 💽. - -✋️ 👆 💪 ⚙️ 🙆 🔗 💽 👈 👆 💚. - -📥 👥 🔜 👀 🖼 ⚙️ 🇸🇲. - -👆 💪 💪 🛠️ ⚫️ 🙆 💽 🐕‍🦺 🇸🇲, 💖: - -* ✳ -* ✳ -* 🗄 -* 🐸 -* 🤸‍♂ 🗄 💽, ♒️. - -👉 🖼, 👥 🔜 ⚙️ **🗄**, ↩️ ⚫️ ⚙️ 👁 📁 & 🐍 ✔️ 🛠️ 🐕‍🦺. , 👆 💪 📁 👉 🖼 & 🏃 ⚫️. - -⏪, 👆 🏭 🈸, 👆 💪 💚 ⚙️ 💽 💽 💖 **✳**. - -/// tip - -📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **✳**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: https://github.com/tiangolo/full-stack-fastapi-postgresql - -/// - -/// note - -👀 👈 📚 📟 🐩 `SQLAlchemy` 📟 👆 🔜 ⚙️ ⏮️ 🙆 🛠️. - - **FastAPI** 🎯 📟 🤪 🕧. - -/// - -## 🐜 - -**FastAPI** 👷 ⏮️ 🙆 💽 & 🙆 👗 🗃 💬 💽. - -⚠ ⚓ ⚙️ "🐜": "🎚-🔗 🗺" 🗃. - -🐜 ✔️ 🧰 🗜 ("*🗺*") 🖖 *🎚* 📟 & 💽 🏓 ("*🔗*"). - -⏮️ 🐜, 👆 🛎 ✍ 🎓 👈 🎨 🏓 🗄 💽, 🔠 🔢 🎓 🎨 🏓, ⏮️ 📛 & 🆎. - -🖼 🎓 `Pet` 💪 🎨 🗄 🏓 `pets`. - -& 🔠 *👐* 🎚 👈 🎓 🎨 ⏭ 💽. - -🖼 🎚 `orion_cat` (👐 `Pet`) 💪 ✔️ 🔢 `orion_cat.type`, 🏓 `type`. & 💲 👈 🔢 💪, ✅ `"cat"`. - -👫 🐜 ✔️ 🧰 ⚒ 🔗 ⚖️ 🔗 🖖 🏓 ⚖️ 👨‍💼. - -👉 🌌, 👆 💪 ✔️ 🔢 `orion_cat.owner` & 👨‍💼 🔜 🔌 💽 👉 🐶 👨‍💼, ✊ ⚪️➡️ 🏓 *👨‍💼*. - -, `orion_cat.owner.name` 💪 📛 (⚪️➡️ `name` 🏓 `owners` 🏓) 👉 🐶 👨‍💼. - -⚫️ 💪 ✔️ 💲 💖 `"Arquilian"`. - -& 🐜 🔜 🌐 👷 🤚 ℹ ⚪️➡️ 🔗 🏓 *👨‍💼* 🕐❔ 👆 🔄 🔐 ⚫️ ⚪️➡️ 👆 🐶 🎚. - -⚠ 🐜 🖼: ✳-🐜 (🍕 ✳ 🛠️), 🇸🇲 🐜 (🍕 🇸🇲, 🔬 🛠️) & 🏒 (🔬 🛠️), 👪 🎏. - -📥 👥 🔜 👀 ❔ 👷 ⏮️ **🇸🇲 🐜**. - -🎏 🌌 👆 💪 ⚙️ 🙆 🎏 🐜. - -/// tip - -📤 🌓 📄 ⚙️ 🏒 📥 🩺. - -/// - -## 📁 📊 - -👫 🖼, ➡️ 💬 👆 ✔️ 📁 📛 `my_super_project` 👈 🔌 🎧-📁 🤙 `sql_app` ⏮️ 📊 💖 👉: - -``` -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - └── schemas.py -``` - -📁 `__init__.py` 🛁 📁, ✋️ ⚫️ 💬 🐍 👈 `sql_app` ⏮️ 🌐 🚮 🕹 (🐍 📁) 📦. - -🔜 ➡️ 👀 ⚫️❔ 🔠 📁/🕹 🔨. - -## ❎ `SQLAlchemy` - -🥇 👆 💪 ❎ `SQLAlchemy`: - -
- -```console -$ pip install sqlalchemy - ----> 100% -``` - -
- -## ✍ 🇸🇲 🍕 - -➡️ 🔗 📁 `sql_app/database.py`. - -### 🗄 🇸🇲 🍕 - -```Python hl_lines="1-3" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -### ✍ 💽 📛 🇸🇲 - -```Python hl_lines="5-6" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -👉 🖼, 👥 "🔗" 🗄 💽 (📂 📁 ⏮️ 🗄 💽). - -📁 🔜 🔎 🎏 📁 📁 `sql_app.db`. - -👈 ⚫️❔ 🏁 🍕 `./sql_app.db`. - -🚥 👆 ⚙️ **✳** 💽 ↩️, 👆 🔜 ✔️ ✍ ⏸: - -```Python -SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" -``` - -...& 🛠️ ⚫️ ⏮️ 👆 💽 📊 & 🎓 (📊 ✳, ✳ ⚖️ 🙆 🎏). - -/// tip - -👉 👑 ⏸ 👈 👆 🔜 ✔️ 🔀 🚥 👆 💚 ⚙️ 🎏 💽. - -/// - -### ✍ 🇸🇲 `engine` - -🥇 🔁 ✍ 🇸🇲 "🚒". - -👥 🔜 ⏪ ⚙️ 👉 `engine` 🎏 🥉. - -```Python hl_lines="8-10" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -#### 🗒 - -❌: - -```Python -connect_args={"check_same_thread": False} -``` - -...💪 🕴 `SQLite`. ⚫️ 🚫 💪 🎏 💽. - -/// info | 📡 ℹ - -🔢 🗄 🔜 🕴 ✔ 1️⃣ 🧵 🔗 ⏮️ ⚫️, 🤔 👈 🔠 🧵 🔜 🍵 🔬 📨. - -👉 ❎ 😫 🤝 🎏 🔗 🎏 👜 (🎏 📨). - -✋️ FastAPI, ⚙️ 😐 🔢 (`def`) 🌅 🌘 1️⃣ 🧵 💪 🔗 ⏮️ 💽 🎏 📨, 👥 💪 ⚒ 🗄 💭 👈 ⚫️ 🔜 ✔ 👈 ⏮️ `connect_args={"check_same_thread": False}`. - -, 👥 🔜 ⚒ 💭 🔠 📨 🤚 🚮 👍 💽 🔗 🎉 🔗, 📤 🙅‍♂ 💪 👈 🔢 🛠️. - -/// - -### ✍ `SessionLocal` 🎓 - -🔠 👐 `SessionLocal` 🎓 🔜 💽 🎉. 🎓 ⚫️ 🚫 💽 🎉. - -✋️ 🕐 👥 ✍ 👐 `SessionLocal` 🎓, 👉 👐 🔜 ☑ 💽 🎉. - -👥 📛 ⚫️ `SessionLocal` 🔬 ⚫️ ⚪️➡️ `Session` 👥 🏭 ⚪️➡️ 🇸🇲. - -👥 🔜 ⚙️ `Session` (1️⃣ 🗄 ⚪️➡️ 🇸🇲) ⏪. - -✍ `SessionLocal` 🎓, ⚙️ 🔢 `sessionmaker`: - -```Python hl_lines="11" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -### ✍ `Base` 🎓 - -🔜 👥 🔜 ⚙️ 🔢 `declarative_base()` 👈 📨 🎓. - -⏪ 👥 🔜 😖 ⚪️➡️ 👉 🎓 ✍ 🔠 💽 🏷 ⚖️ 🎓 (🐜 🏷): - -```Python hl_lines="13" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -## ✍ 💽 🏷 - -➡️ 🔜 👀 📁 `sql_app/models.py`. - -### ✍ 🇸🇲 🏷 ⚪️➡️ `Base` 🎓 - -👥 🔜 ⚙️ 👉 `Base` 🎓 👥 ✍ ⏭ ✍ 🇸🇲 🏷. - -/// tip - -🇸🇲 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽. - -✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐. - -/// - -🗄 `Base` ⚪️➡️ `database` (📁 `database.py` ⚪️➡️ 🔛). - -✍ 🎓 👈 😖 ⚪️➡️ ⚫️. - -👫 🎓 🇸🇲 🏷. - -```Python hl_lines="4 7-8 18-19" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -`__tablename__` 🔢 💬 🇸🇲 📛 🏓 ⚙️ 💽 🔠 👫 🏷. - -### ✍ 🏷 🔢/🏓 - -🔜 ✍ 🌐 🏷 (🎓) 🔢. - -🔠 👫 🔢 🎨 🏓 🚮 🔗 💽 🏓. - -👥 ⚙️ `Column` ⚪️➡️ 🇸🇲 🔢 💲. - -& 👥 🚶‍♀️ 🇸🇲 🎓 "🆎", `Integer`, `String`, & `Boolean`, 👈 🔬 🆎 💽, ❌. - -```Python hl_lines="1 10-13 21-24" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -### ✍ 💛 - -🔜 ✍ 💛. - -👉, 👥 ⚙️ `relationship` 🚚 🇸🇲 🐜. - -👉 🔜 ▶️️, 🌅 ⚖️ 🌘, "🎱" 🔢 👈 🔜 🔌 💲 ⚪️➡️ 🎏 🏓 🔗 👉 1️⃣. - -```Python hl_lines="2 15 26" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -🕐❔ 🔐 🔢 `items` `User`, `my_user.items`, ⚫️ 🔜 ✔️ 📇 `Item` 🇸🇲 🏷 (⚪️➡️ `items` 🏓) 👈 ✔️ 💱 🔑 ☝ 👉 ⏺ `users` 🏓. - -🕐❔ 👆 🔐 `my_user.items`, 🇸🇲 🔜 🤙 🚶 & ☕ 🏬 ⚪️➡️ 💽 `items` 🏓 & 🔗 👫 📥. - -& 🕐❔ 🔐 🔢 `owner` `Item`, ⚫️ 🔜 🔌 `User` 🇸🇲 🏷 ⚪️➡️ `users` 🏓. ⚫️ 🔜 ⚙️ `owner_id` 🔢/🏓 ⏮️ 🚮 💱 🔑 💭 ❔ ⏺ 🤚 ⚪️➡️ `users` 🏓. - -## ✍ Pydantic 🏷 - -🔜 ➡️ ✅ 📁 `sql_app/schemas.py`. - -/// tip - -❎ 😨 🖖 🇸🇲 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🇸🇲 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷. - -👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠). - -👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯‍♂️. - -/// - -### ✍ ▶️ Pydantic *🏷* / 🔗 - -✍ `ItemBase` & `UserBase` Pydantic *🏷* (⚖️ ➡️ 💬 "🔗") ✔️ ⚠ 🔢 ⏪ 🏗 ⚖️ 👂 📊. - -& ✍ `ItemCreate` & `UserCreate` 👈 😖 ⚪️➡️ 👫 (👫 🔜 ✔️ 🎏 🔢), ➕ 🙆 🌖 📊 (🔢) 💪 🏗. - -, 👩‍💻 🔜 ✔️ `password` 🕐❔ 🏗 ⚫️. - -✋️ 💂‍♂, `password` 🏆 🚫 🎏 Pydantic *🏷*, 🖼, ⚫️ 🏆 🚫 📨 ⚪️➡️ 🛠️ 🕐❔ 👂 👩‍💻. - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1 4-6 9-10 21-22 25-26" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -#### 🇸🇲 👗 & Pydantic 👗 - -👀 👈 🇸🇲 *🏷* 🔬 🔢 ⚙️ `=`, & 🚶‍♀️ 🆎 🔢 `Column`, 💖: - -```Python -name = Column(String) -``` - -⏪ Pydantic *🏷* 📣 🆎 ⚙️ `:`, 🆕 🆎 ✍ ❕/🆎 🔑: - -```Python -name: str -``` - -✔️ ⚫️ 🤯, 👆 🚫 🤚 😕 🕐❔ ⚙️ `=` & `:` ⏮️ 👫. - -### ✍ Pydantic *🏷* / 🔗 👂 / 📨 - -🔜 ✍ Pydantic *🏷* (🔗) 👈 🔜 ⚙️ 🕐❔ 👂 💽, 🕐❔ 🛬 ⚫️ ⚪️➡️ 🛠️. - -🖼, ⏭ 🏗 🏬, 👥 🚫 💭 ⚫️❔ 🔜 🆔 🛠️ ⚫️, ✋️ 🕐❔ 👂 ⚫️ (🕐❔ 🛬 ⚫️ ⚪️➡️ 🛠️) 👥 🔜 ⏪ 💭 🚮 🆔. - -🎏 🌌, 🕐❔ 👂 👩‍💻, 👥 💪 🔜 📣 👈 `items` 🔜 🔌 🏬 👈 💭 👉 👩‍💻. - -🚫 🕴 🆔 📚 🏬, ✋️ 🌐 💽 👈 👥 🔬 Pydantic *🏷* 👂 🏬: `Item`. - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="15-17 31-34" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="15-17 31-34" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="13-15 29-32" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -/// tip - -👀 👈 `User`, Pydantic *🏷* 👈 🔜 ⚙️ 🕐❔ 👂 👩‍💻 (🛬 ⚫️ ⚪️➡️ 🛠️) 🚫 🔌 `password`. - -/// - -### ⚙️ Pydantic `orm_mode` - -🔜, Pydantic *🏷* 👂, `Item` & `User`, 🚮 🔗 `Config` 🎓. - -👉 `Config` 🎓 ⚙️ 🚚 📳 Pydantic. - -`Config` 🎓, ⚒ 🔢 `orm_mode = True`. - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="15 19-20 31 36-37" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="15 19-20 31 36-37" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="13 17-18 29 34-35" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -/// tip - -👀 ⚫️ ⚖ 💲 ⏮️ `=`, 💖: - -`orm_mode = True` - -⚫️ 🚫 ⚙️ `:` 🆎 📄 ⏭. - -👉 ⚒ 📁 💲, 🚫 📣 🆎. - -/// - -Pydantic `orm_mode` 🔜 💬 Pydantic *🏷* ✍ 💽 🚥 ⚫️ 🚫 `dict`, ✋️ 🐜 🏷 (⚖️ 🙆 🎏 ❌ 🎚 ⏮️ 🔢). - -👉 🌌, ↩️ 🕴 🔄 🤚 `id` 💲 ⚪️➡️ `dict`,: - -```Python -id = data["id"] -``` - -⚫️ 🔜 🔄 🤚 ⚫️ ⚪️➡️ 🔢,: - -```Python -id = data.id -``` - -& ⏮️ 👉, Pydantic *🏷* 🔗 ⏮️ 🐜, & 👆 💪 📣 ⚫️ `response_model` ❌ 👆 *➡ 🛠️*. - -👆 🔜 💪 📨 💽 🏷 & ⚫️ 🔜 ✍ 💽 ⚪️➡️ ⚫️. - -#### 📡 ℹ 🔃 🐜 📳 - -🇸🇲 & 📚 🎏 🔢 "🙃 🚚". - -👈 ⛓, 🖼, 👈 👫 🚫 ☕ 💽 💛 ⚪️➡️ 💽 🚥 👆 🔄 🔐 🔢 👈 🔜 🔌 👈 💽. - -🖼, 🔐 🔢 `items`: - -```Python -current_user.items -``` - -🔜 ⚒ 🇸🇲 🚶 `items` 🏓 & 🤚 🏬 👉 👩‍💻, ✋️ 🚫 ⏭. - -🍵 `orm_mode`, 🚥 👆 📨 🇸🇲 🏷 ⚪️➡️ 👆 *➡ 🛠️*, ⚫️ 🚫🔜 🔌 💛 💽. - -🚥 👆 📣 📚 💛 👆 Pydantic 🏷. - -✋️ ⏮️ 🐜 📳, Pydantic ⚫️ 🔜 🔄 🔐 💽 ⚫️ 💪 ⚪️➡️ 🔢 (↩️ 🤔 `dict`), 👆 💪 📣 🎯 💽 👆 💚 📨 & ⚫️ 🔜 💪 🚶 & 🤚 ⚫️, ⚪️➡️ 🐜. - -## 💩 🇨🇻 - -🔜 ➡️ 👀 📁 `sql_app/crud.py`. - -👉 📁 👥 🔜 ✔️ ♻ 🔢 🔗 ⏮️ 💽 💽. - -**💩** 👟 ⚪️➡️: **🅱**📧, **Ⓜ**💳, **👤** = , & **🇨🇮**📧. - -...👐 👉 🖼 👥 🕴 🏗 & 👂. - -### ✍ 💽 - -🗄 `Session` ⚪️➡️ `sqlalchemy.orm`, 👉 🔜 ✔ 👆 📣 🆎 `db` 🔢 & ✔️ 👻 🆎 ✅ & 🛠️ 👆 🔢. - -🗄 `models` (🇸🇲 🏷) & `schemas` (Pydantic *🏷* / 🔗). - -✍ 🚙 🔢: - -* ✍ 👁 👩‍💻 🆔 & 📧. -* ✍ 💗 👩‍💻. -* ✍ 💗 🏬. - -```Python hl_lines="1 3 6-7 10-11 14-15 27-28" -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` - -/// tip - -🏗 🔢 👈 🕴 💡 🔗 ⏮️ 💽 (🤚 👩‍💻 ⚖️ 🏬) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 ♻ 👫 💗 🍕 & 🚮 ⚒ 💯 👫. - -/// - -### ✍ 💽 - -🔜 ✍ 🚙 🔢 ✍ 💽. - -🔁: - -* ✍ 🇸🇲 🏷 *👐* ⏮️ 👆 📊. -* `add` 👈 👐 🎚 👆 💽 🎉. -* `commit` 🔀 💽 (👈 👫 🖊). -* `refresh` 👆 👐 (👈 ⚫️ 🔌 🙆 🆕 📊 ⚪️➡️ 💽, 💖 🏗 🆔). - -```Python hl_lines="18-24 31-36" -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` - -/// tip - -🇸🇲 🏷 `User` 🔌 `hashed_password` 👈 🔜 🔌 🔐 #️⃣ ⏬ 🔐. - -✋️ ⚫️❔ 🛠️ 👩‍💻 🚚 ⏮️ 🔐, 👆 💪 ⚗ ⚫️ & 🏗 #️⃣ 🔐 👆 🈸. - - & ⤴️ 🚶‍♀️ `hashed_password` ❌ ⏮️ 💲 🖊. - -/// - -/// warning - -👉 🖼 🚫 🔐, 🔐 🚫#️⃣. - -🎰 👨‍❤‍👨 🈸 👆 🔜 💪 #️⃣ 🔐 & 🙅 🖊 👫 🔢. - -🌅 ℹ, 🚶 🔙 💂‍♂ 📄 🔰. - -📥 👥 🎯 🕴 🔛 🧰 & 👨‍🔧 💽. - -/// - -/// tip - -↩️ 🚶‍♀️ 🔠 🇨🇻 ❌ `Item` & 👂 🔠 1️⃣ 👫 ⚪️➡️ Pydantic *🏷*, 👥 🏭 `dict` ⏮️ Pydantic *🏷*'Ⓜ 📊 ⏮️: - -`item.dict()` - - & ⤴️ 👥 🚶‍♀️ `dict`'Ⓜ 🔑-💲 👫 🇨🇻 ❌ 🇸🇲 `Item`, ⏮️: - -`Item(**item.dict())` - - & ⤴️ 👥 🚶‍♀️ ➕ 🇨🇻 ❌ `owner_id` 👈 🚫 🚚 Pydantic *🏷*, ⏮️: - -`Item(**item.dict(), owner_id=user_id)` - -/// - -## 👑 **FastAPI** 📱 - -& 🔜 📁 `sql_app/main.py` ➡️ 🛠️ & ⚙️ 🌐 🎏 🍕 👥 ✍ ⏭. - -### ✍ 💽 🏓 - -📶 🙃 🌌 ✍ 💽 🏓: - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -#### ⚗ 🗒 - -🛎 👆 🔜 🎲 🔢 👆 💽 (✍ 🏓, ♒️) ⏮️ . - -& 👆 🔜 ⚙️ ⚗ "🛠️" (👈 🚮 👑 👨‍🏭). - -"🛠️" ⚒ 🔁 💪 🕐❔ 👆 🔀 📊 👆 🇸🇲 🏷, 🚮 🆕 🔢, ♒️. 🔁 👈 🔀 💽, 🚮 🆕 🏓, 🆕 🏓, ♒️. - -👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 `alembic` 📁 ℹ 📟. - -### ✍ 🔗 - -🔜 ⚙️ `SessionLocal` 🎓 👥 ✍ `sql_app/database.py` 📁 ✍ 🔗. - -👥 💪 ✔️ 🔬 💽 🎉/🔗 (`SessionLocal`) 📍 📨, ⚙️ 🎏 🎉 🔘 🌐 📨 & ⤴️ 🔐 ⚫️ ⏮️ 📨 🏁. - -& ⤴️ 🆕 🎉 🔜 ✍ ⏭ 📨. - -👈, 👥 🔜 ✍ 🆕 🔗 ⏮️ `yield`, 🔬 ⏭ 📄 🔃 [🔗 ⏮️ `yield`](dependencies/dependencies-with-yield.md){.internal-link target=_blank}. - -👆 🔗 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 👈 🔜 ⚙️ 👁 📨, & ⤴️ 🔐 ⚫️ 🕐 📨 🏁. - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="15-20" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="13-18" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -/// info - -👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. - - & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. - -👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. - -✋️ 👆 💪 🚫 🤚 ➕1️⃣ ⚠ ⚪️➡️ 🚪 📟 (⏮️ `yield`). 👀 🌖 [🔗 ⏮️ `yield` & `HTTPException`](dependencies/dependencies-with-yield.md#yield-httpexception){.internal-link target=_blank} - -/// - -& ⤴️, 🕐❔ ⚙️ 🔗 *➡ 🛠️ 🔢*, 👥 📣 ⚫️ ⏮️ 🆎 `Session` 👥 🗄 🔗 ⚪️➡️ 🇸🇲. - -👉 🔜 ⤴️ 🤝 👥 👍 👨‍🎨 🐕‍🦺 🔘 *➡ 🛠️ 🔢*, ↩️ 👨‍🎨 🔜 💭 👈 `db` 🔢 🆎 `Session`: - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="24 32 38 47 53" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="22 30 36 45 51" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -/// info | 📡 ℹ - -🔢 `db` 🤙 🆎 `SessionLocal`, ✋️ 👉 🎓 (✍ ⏮️ `sessionmaker()`) "🗳" 🇸🇲 `Session`,, 👨‍🎨 🚫 🤙 💭 ⚫️❔ 👩‍🔬 🚚. - -✋️ 📣 🆎 `Session`, 👨‍🎨 🔜 💪 💭 💪 👩‍🔬 (`.add()`, `.query()`, `.commit()`, ♒️) & 💪 🚚 👍 🐕‍🦺 (💖 🛠️). 🆎 📄 🚫 📉 ☑ 🎚. - -/// - -### ✍ 👆 **FastAPI** *➡ 🛠️* - -🔜, 😒, 📥 🐩 **FastAPI** *➡ 🛠️* 📟. - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="23-28 31-34 37-42 45-49 52-55" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="21-26 29-32 35-40 43-47 50-53" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -👥 🏗 💽 🎉 ⏭ 🔠 📨 🔗 ⏮️ `yield`, & ⤴️ 📪 ⚫️ ⏮️. - -& ⤴️ 👥 💪 ✍ 🚚 🔗 *➡ 🛠️ 🔢*, 🤚 👈 🎉 🔗. - -⏮️ 👈, 👥 💪 🤙 `crud.get_user` 🔗 ⚪️➡️ 🔘 *➡ 🛠️ 🔢* & ⚙️ 👈 🎉. - -/// tip - -👀 👈 💲 👆 📨 🇸🇲 🏷, ⚖️ 📇 🇸🇲 🏷. - -✋️ 🌐 *➡ 🛠️* ✔️ `response_model` ⏮️ Pydantic *🏷* / 🔗 ⚙️ `orm_mode`, 💽 📣 👆 Pydantic 🏷 🔜 ⚗ ⚪️➡️ 👫 & 📨 👩‍💻, ⏮️ 🌐 😐 ⛽ & 🔬. - -/// - -/// tip - -👀 👈 📤 `response_models` 👈 ✔️ 🐩 🐍 🆎 💖 `List[schemas.Item]`. - -✋️ 🎚/🔢 👈 `List` Pydantic *🏷* ⏮️ `orm_mode`, 💽 🔜 🗃 & 📨 👩‍💻 🛎, 🍵 ⚠. - -/// - -### 🔃 `def` 🆚 `async def` - -📥 👥 ⚙️ 🇸🇲 📟 🔘 *➡ 🛠️ 🔢* & 🔗, &, 🔄, ⚫️ 🔜 🚶 & 🔗 ⏮️ 🔢 💽. - -👈 💪 ⚠ 🚚 "⌛". - -✋️ 🇸🇲 🚫 ✔️ 🔗 ⚙️ `await` 🔗, 🔜 ⏮️ 🕳 💖: - -```Python -user = await db.query(User).first() -``` - -...& ↩️ 👥 ⚙️: - -```Python -user = db.query(User).first() -``` - -⤴️ 👥 🔜 📣 *➡ 🛠️ 🔢* & 🔗 🍵 `async def`, ⏮️ 😐 `def`,: - -```Python hl_lines="2" -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - ... -``` - -/// info - -🚥 👆 💪 🔗 👆 🔗 💽 🔁, 👀 [🔁 🗄 (🔗) 💽](../advanced/async-sql-databases.md){.internal-link target=_blank}. - -/// - -/// note | 📶 📡 ℹ - -🚥 👆 😟 & ✔️ ⏬ 📡 💡, 👆 💪 ✅ 📶 📡 ℹ ❔ 👉 `async def` 🆚 `def` 🍵 [🔁](../async.md#i_2){.internal-link target=_blank} 🩺. - -/// - -## 🛠️ - -↩️ 👥 ⚙️ 🇸🇲 🔗 & 👥 🚫 🚚 🙆 😇 🔌-⚫️ 👷 ⏮️ **FastAPI**, 👥 💪 🛠️ 💽 🛠️ ⏮️ 🔗. - -& 📟 🔗 🇸🇲 & 🇸🇲 🏷 🖖 🎏 🔬 📁, 👆 🔜 💪 🎭 🛠️ ⏮️ ⚗ 🍵 ✔️ ❎ FastAPI, Pydantic, ⚖️ 🕳 🙆. - -🎏 🌌, 👆 🔜 💪 ⚙️ 🎏 🇸🇲 🏷 & 🚙 🎏 🍕 👆 📟 👈 🚫 🔗 **FastAPI**. - -🖼, 🖥 📋 👨‍🏭 ⏮️ 🥒, 🅿, ⚖️ 📶. - -## 📄 🌐 📁 - - 💭 👆 🔜 ✔️ 📁 📛 `my_super_project` 👈 🔌 🎧-📁 🤙 `sql_app`. - -`sql_app` 🔜 ✔️ 📄 📁: - -* `sql_app/__init__.py`: 🛁 📁. - -* `sql_app/database.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -* `sql_app/models.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -* `sql_app/schemas.py`: - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -* `sql_app/crud.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` - -* `sql_app/main.py`: - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -## ✅ ⚫️ - -👆 💪 📁 👉 📟 & ⚙️ ⚫️. - -/// info - -👐, 📟 🎦 📥 🍕 💯. 🌅 📟 👉 🩺. - -/// - -⤴️ 👆 💪 🏃 ⚫️ ⏮️ Uvicorn: - - -
- -```console -$ uvicorn sql_app.main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -& ⤴️, 👆 💪 📂 👆 🖥 http://127.0.0.1:8000/docs. - -& 👆 🔜 💪 🔗 ⏮️ 👆 **FastAPI** 🈸, 👂 📊 ⚪️➡️ 🎰 💽: - - - -## 🔗 ⏮️ 💽 🔗 - -🚥 👆 💚 🔬 🗄 💽 (📁) 🔗, ➡ FastAPI, ℹ 🚮 🎚, 🚮 🏓, 🏓, ⏺, 🔀 📊, ♒️. 👆 💪 ⚙️ 💽 🖥 🗄. - -⚫️ 🔜 👀 💖 👉: - - - -👆 💪 ⚙️ 💳 🗄 🖥 💖 🗄 📋 ⚖️ ExtendsClass. - -## 🎛 💽 🎉 ⏮️ 🛠️ - -🚥 👆 💪 🚫 ⚙️ 🔗 ⏮️ `yield` - 🖼, 🚥 👆 🚫 ⚙️ **🐍 3️⃣.7️⃣** & 💪 🚫 ❎ "🐛" 🤔 🔛 **🐍 3️⃣.6️⃣** - 👆 💪 ⚒ 🆙 🎉 "🛠️" 🎏 🌌. - -"🛠️" 🌖 🔢 👈 🕧 🛠️ 🔠 📨, ⏮️ 📟 🛠️ ⏭, & 📟 🛠️ ⏮️ 🔗 🔢. - -### ✍ 🛠️ - -🛠️ 👥 🔜 🚮 (🔢) 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 🔠 📨, 🚮 ⚫️ 📨 & ⤴️ 🔐 ⚫️ 🕐 📨 🏁. - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="14-22" -{!> ../../docs_src/sql_databases/sql_app/alt_main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="12-20" -{!> ../../docs_src/sql_databases/sql_app_py39/alt_main.py!} -``` - -//// - -/// info - -👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. - - & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. - -👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. - -/// - -### 🔃 `request.state` - -`request.state` 🏠 🔠 `Request` 🎚. ⚫️ 📤 🏪 ❌ 🎚 📎 📨 ⚫️, 💖 💽 🎉 👉 💼. 👆 💪 ✍ 🌅 🔃 ⚫️ 💃 🩺 🔃 `Request` 🇵🇸. - -👥 👉 💼, ⚫️ ℹ 👥 🚚 👁 💽 🎉 ⚙️ 🔘 🌐 📨, & ⤴️ 🔐 ⏮️ (🛠️). - -### 🔗 ⏮️ `yield` ⚖️ 🛠️ - -❎ **🛠️** 📥 🎏 ⚫️❔ 🔗 ⏮️ `yield` 🔨, ⏮️ 🔺: - -* ⚫️ 🚚 🌖 📟 & 👄 🌅 🏗. -* 🛠️ ✔️ `async` 🔢. - * 🚥 📤 📟 ⚫️ 👈 ✔️ "⌛" 🕸, ⚫️ 💪 "🍫" 👆 🈸 📤 & 📉 🎭 🍖. - * 👐 ⚫️ 🎲 🚫 📶 ⚠ 📥 ⏮️ 🌌 `SQLAlchemy` 👷. - * ✋️ 🚥 👆 🚮 🌖 📟 🛠️ 👈 ✔️ 📚 👤/🅾 ⌛, ⚫️ 💪 ⤴️ ⚠. -* 🛠️ 🏃 *🔠* 📨. - * , 🔗 🔜 ✍ 🔠 📨. - * 🕐❔ *➡ 🛠️* 👈 🍵 👈 📨 🚫 💪 💽. - -/// tip - -⚫️ 🎲 👍 ⚙️ 🔗 ⏮️ `yield` 🕐❔ 👫 🥃 ⚙️ 💼. - -/// - -/// info - -🔗 ⏮️ `yield` 🚮 ⏳ **FastAPI**. - -⏮️ ⏬ 👉 🔰 🕴 ✔️ 🖼 ⏮️ 🛠️ & 📤 🎲 📚 🈸 ⚙️ 🛠️ 💽 🎉 🧾. - -/// diff --git a/docs/em/docs/tutorial/static-files.md b/docs/em/docs/tutorial/static-files.md index c9bb9ff6a..6ff6e37a9 100644 --- a/docs/em/docs/tutorial/static-files.md +++ b/docs/em/docs/tutorial/static-files.md @@ -7,9 +7,7 @@ * 🗄 `StaticFiles`. * "🗻" `StaticFiles()` 👐 🎯 ➡. -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} /// note | 📡 ℹ diff --git a/docs/em/docs/tutorial/testing.md b/docs/em/docs/tutorial/testing.md index 27cf9f16e..cb4a1ca21 100644 --- a/docs/em/docs/tutorial/testing.md +++ b/docs/em/docs/tutorial/testing.md @@ -26,9 +26,7 @@ ✍ 🙅 `assert` 📄 ⏮️ 🐩 🐍 🧬 👈 👆 💪 ✅ (🔄, 🐩 `pytest`). -```Python hl_lines="2 12 15-18" -{!../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} /// tip @@ -74,9 +72,7 @@ 📁 `main.py` 👆 ✔️ 👆 **FastAPI** 📱: -```Python -{!../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### 🔬 📁 @@ -92,9 +88,7 @@ ↩️ 👉 📁 🎏 📦, 👆 💪 ⚙️ ⚖ 🗄 🗄 🎚 `app` ⚪️➡️ `main` 🕹 (`main.py`): -```Python hl_lines="3" -{!../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py hl[3] *} ...& ✔️ 📟 💯 💖 ⏭. @@ -122,29 +116,13 @@ 👯‍♂️ *➡ 🛠️* 🚚 `X-Token` 🎚. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python -{!> ../../docs_src/app_testing/app_b/main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python -{!> ../../docs_src/app_testing/app_b_py310/main.py!} -``` - -//// +{* ../../docs_src/app_testing/app_b/main.py *} ### ↔ 🔬 📁 👆 💪 ⤴️ ℹ `test_main.py` ⏮️ ↔ 💯: -```Python -{!> ../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} 🕐❔ 👆 💪 👩‍💻 🚶‍♀️ ℹ 📨 & 👆 🚫 💭 ❔, 👆 💪 🔎 (🇺🇸🔍) ❔ ⚫️ `httpx`, ⚖️ ❔ ⚫️ ⏮️ `requests`, 🇸🇲 🔧 ⚓️ 🔛 📨' 🔧. diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index fe4194ac7..3b9dc83f0 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -206,13 +206,7 @@ But for the generated client we could **modify** the OpenAPI operation IDs right We could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this: -//// tab | Python - -```Python -{!> ../../docs_src/generate_clients/tutorial004.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial004.py *} //// tab | Node.js diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index 01810c438..1af19a045 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -62,9 +62,7 @@ You can use all the same validation features and tools you use for Pydantic mode //// tab | Pydantic v2 -```Python hl_lines="2 5-8 11" -{!> ../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} //// @@ -76,9 +74,7 @@ In Pydantic v1 you would import `BaseSettings` directly from `pydantic` instead /// -```Python hl_lines="2 5-8 11" -{!> ../../docs_src/settings/tutorial001_pv1.py!} -``` +{* ../../docs_src/settings/tutorial001_pv1.py hl[2,5:8,11] *} //// @@ -96,9 +92,7 @@ Next it will convert and validate the data. So, when you use that `settings` obj Then you can use the new `settings` object in your application: -```Python hl_lines="18-20" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} ### Run the server @@ -132,15 +126,11 @@ You could put those settings in another module file as you saw in [Bigger Applic For example, you could have a file `config.py` with: -```Python -{!../../docs_src/settings/app01/config.py!} -``` +{* ../../docs_src/settings/app01/config.py *} And then use it in a file `main.py`: -```Python hl_lines="3 11-13" -{!../../docs_src/settings/app01/main.py!} -``` +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} /// tip @@ -158,9 +148,7 @@ This could be especially useful during testing, as it's very easy to override a Coming from the previous example, your `config.py` file could look like: -```Python hl_lines="10" -{!../../docs_src/settings/app02/config.py!} -``` +{* ../../docs_src/settings/app02/config.py hl[10] *} Notice that now we don't create a default instance `settings = Settings()`. @@ -168,35 +156,7 @@ Notice that now we don't create a default instance `settings = Settings()`. Now we create a dependency that returns a new `config.Settings()`. -//// tab | Python 3.9+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="5 11-12" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *} /// tip @@ -208,43 +168,13 @@ For now you can assume `get_settings()` is a normal function. And then we can require it from the *path operation function* as a dependency and use it anywhere we need it. -//// tab | Python 3.9+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="16 18-20" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *} ### Settings and testing Then it would be very easy to provide a different settings object during testing by creating a dependency override for `get_settings`: -```Python hl_lines="9-10 13 21" -{!../../docs_src/settings/app02/test_main.py!} -``` +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} In the dependency override we set a new value for the `admin_email` when creating the new `Settings` object, and then we return that new object. @@ -287,9 +217,7 @@ And then update your `config.py` with: //// tab | Pydantic v2 -```Python hl_lines="9" -{!> ../../docs_src/settings/app03_an/config.py!} -``` +{* ../../docs_src/settings/app03_an/config.py hl[9] *} /// tip @@ -301,9 +229,7 @@ The `model_config` attribute is used just for Pydantic configuration. You can re //// tab | Pydantic v1 -```Python hl_lines="9-10" -{!> ../../docs_src/settings/app03_an/config_pv1.py!} -``` +{* ../../docs_src/settings/app03_an/config_pv1.py hl[9:10] *} /// tip @@ -344,35 +270,7 @@ we would create that object for each request, and we would be reading the `.env` But as we are using the `@lru_cache` decorator on top, the `Settings` object will be created only once, the first time it's called. ✔️ -//// tab | Python 3.9+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 10" -{!> ../../docs_src/settings/app03/main.py!} -``` - -//// +{* ../../docs_src/settings/app03_an_py39/main.py hl[1,11] *} Then for any subsequent call of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again. diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 76f0ef1de..d9b0ca6f1 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -27,9 +27,7 @@ $ pip install jinja2 * Declare a `Request` parameter in the *path operation* that will return a template. * Use the `templates` you created to render and return a `TemplateResponse`, pass the name of the template, the request object, and a "context" dictionary with key-value pairs to be used inside of the Jinja2 template. -```Python hl_lines="4 11 15-18" -{!../../docs_src/templates/tutorial001.py!} -``` +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *} /// note diff --git a/docs/en/docs/advanced/testing-events.md b/docs/en/docs/advanced/testing-events.md index f48907c7c..0c554c4ec 100644 --- a/docs/en/docs/advanced/testing-events.md +++ b/docs/en/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ When you need your event handlers (`startup` and `shutdown`) to run in your tests, you can use the `TestClient` with a `with` statement: -```Python hl_lines="9-12 20-24" -{!../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/en/docs/tutorial/debugging.md b/docs/en/docs/tutorial/debugging.md index 6c0177853..90dd908f7 100644 --- a/docs/en/docs/tutorial/debugging.md +++ b/docs/en/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ You can connect the debugger in your editor, for example with Visual Studio Code In your FastAPI application, import and run `uvicorn` directly: -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### About `__name__ == "__main__"` diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md index 70b5945a4..2b97ba39e 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md @@ -29,21 +29,15 @@ For example, you could use this to create a database session and close it after Only the code prior to and including the `yield` statement is executed before creating a response: -```Python hl_lines="2-4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *} The yielded value is what is injected into *path operations* and other dependencies: -```Python hl_lines="4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} The code following the `yield` statement is executed after creating the response but before sending it: -```Python hl_lines="5-6" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *} /// tip @@ -63,9 +57,7 @@ So, you can look for that specific exception inside the dependency with `except In the same way, you can use `finally` to make sure the exit steps are executed, no matter if there was an exception or not. -```Python hl_lines="3 5" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *} ## Sub-dependencies with `yield` @@ -75,35 +67,7 @@ You can have sub-dependencies and "trees" of sub-dependencies of any size and sh For example, `dependency_c` can have a dependency on `dependency_b`, and `dependency_b` on `dependency_a`: -//// tab | Python 3.9+ - -```Python hl_lines="6 14 22" -{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 13 21" -{!> ../../docs_src/dependencies/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="4 12 20" -{!> ../../docs_src/dependencies/tutorial008.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *} And all of them can use `yield`. @@ -111,35 +75,7 @@ In this case `dependency_c`, to execute its exit code, needs the value from `dep And, in turn, `dependency_b` needs the value from `dependency_a` (here named `dep_a`) to be available for its exit code. -//// tab | Python 3.9+ - -```Python hl_lines="18-19 26-27" -{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17-18 25-26" -{!> ../../docs_src/dependencies/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="16-17 24-25" -{!> ../../docs_src/dependencies/tutorial008.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *} The same way, you could have some dependencies with `yield` and some other dependencies with `return`, and have some of those depend on some of the others. @@ -171,35 +107,7 @@ But it's there for you if you need it. 🤓 /// -//// tab | Python 3.9+ - -```Python hl_lines="18-22 31" -{!> ../../docs_src/dependencies/tutorial008b_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17-21 30" -{!> ../../docs_src/dependencies/tutorial008b_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="16-20 29" -{!> ../../docs_src/dependencies/tutorial008b.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008b_an_py39.py hl[18:22,31] *} An alternative you could use to catch exceptions (and possibly also raise another `HTTPException`) is to create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. @@ -207,35 +115,7 @@ An alternative you could use to catch exceptions (and possibly also raise anothe If you catch an exception using `except` in a dependency with `yield` and you don't raise it again (or raise a new exception), FastAPI won't be able to notice there was an exception, the same way that would happen with regular Python: -//// tab | Python 3.9+ - -```Python hl_lines="15-16" -{!> ../../docs_src/dependencies/tutorial008c_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14-15" -{!> ../../docs_src/dependencies/tutorial008c_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="13-14" -{!> ../../docs_src/dependencies/tutorial008c.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *} In this case, the client will see an *HTTP 500 Internal Server Error* response as it should, given that we are not raising an `HTTPException` or similar, but the server will **not have any logs** or any other indication of what was the error. 😱 @@ -245,35 +125,7 @@ If you catch an exception in a dependency with `yield`, unless you are raising a You can re-raise the same exception using `raise`: -//// tab | Python 3.9+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial008d_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial008d_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/dependencies/tutorial008d.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *} Now the client will get the same *HTTP 500 Internal Server Error* response, but the server will have our custom `InternalError` in the logs. 😎 @@ -403,9 +255,7 @@ In Python, you can create Context Managers by ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 3 13-17" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 2 11-15" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 2 12-16" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} Note that the parameters inside the function have their natural data type, and you can, for example, perform normal date manipulations, like: -//// tab | Python 3.10+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-20" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17-18" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index 537cb3e72..4d969747f 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -25,9 +25,7 @@ To return HTTP responses with errors to the client you use `HTTPException`. ### Import `HTTPException` -```Python hl_lines="1" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} ### Raise an `HTTPException` in your code @@ -41,9 +39,7 @@ The benefit of raising an exception over `return`ing a value will be more eviden In this example, when the client requests an item by an ID that doesn't exist, raise an exception with a status code of `404`: -```Python hl_lines="11" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} ### The resulting response @@ -81,9 +77,7 @@ You probably won't need to use it directly in your code. But in case you needed it for an advanced scenario, you can add custom headers: -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial002.py!} -``` +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} ## Install custom exception handlers @@ -95,9 +89,7 @@ And you want to handle this exception globally with FastAPI. You could add a custom exception handler with `@app.exception_handler()`: -```Python hl_lines="5-7 13-18 24" -{!../../docs_src/handling_errors/tutorial003.py!} -``` +{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *} Here, if you request `/unicorns/yolo`, the *path operation* will `raise` a `UnicornException`. @@ -135,9 +127,7 @@ To override it, import the `RequestValidationError` and use it with `@app.except The exception handler will receive a `Request` and the exception. -```Python hl_lines="2 14-16" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *} Now, if you go to `/items/foo`, instead of getting the default JSON error with: @@ -188,9 +178,7 @@ The same way, you can override the `HTTPException` handler. For example, you could want to return a plain text response instead of JSON for these errors: -```Python hl_lines="3-4 9-11 22" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *} /// note | Technical Details @@ -206,9 +194,7 @@ The `RequestValidationError` contains the `body` it received with invalid data. You could use it while developing your app to log the body and debug it, return it to the user, etc. -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial005.py!} -``` +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} Now try sending an invalid item like: @@ -264,8 +250,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException If you want to use the exception along with the same default exception handlers from **FastAPI**, you can import and reuse the default exception handlers from `fastapi.exception_handlers`: -```Python hl_lines="2-5 15 21" -{!../../docs_src/handling_errors/tutorial006.py!} -``` +{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *} In this example you are just `print`ing the error with a very expressive message, but you get the idea. You can use the exception and then just reuse the default exception handlers. diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index 12778d7fe..1bf16334d 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -4,21 +4,7 @@ Let's take this application as example: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *} The query parameter `q` is of type `Union[str, None]` (or `str | None` in Python 3.10), that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required. @@ -123,21 +109,7 @@ Now let's jump to the fun stuff. 🎉 Now that we have this `Annotated` where we can put more information (in this case some additional validation), add `Query` inside of `Annotated`, and set the parameter `max_length` to `50`: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[9] *} Notice that the default value is still `None`, so the parameter is still optional. @@ -167,21 +139,7 @@ For new code and whenever possible, use `Annotated` as explained above. There ar This is how you would use `Query()` as the default value of your function parameter, setting the parameter `max_length` to 50: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002_py310.py hl[7] *} As in this case (without using `Annotated`) we have to replace the default value `None` in the function with `Query()`, we now need to set the default value with the parameter `Query(default=None)`, it serves the same purpose of defining that default value (at least for FastAPI). @@ -281,113 +239,13 @@ Because `Annotated` can have more than one metadata annotation, you could now ev You can also add a parameter `min_length`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial003_an_py310.py hl[10] *} ## Add regular expressions You can define a regular expression `pattern` that the parameter should match: -//// tab | Python 3.10+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/query_params_str_validations/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *} This specific regular expression pattern checks that the received parameter value: @@ -405,11 +263,9 @@ Before Pydantic version 2 and before FastAPI 0.100.0, the parameter was called ` You could still see some code using it: -//// tab | Python 3.10+ Pydantic v1 +//// tab | Pydantic v1 -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial004_regex_an_py310.py hl[11] *} //// @@ -421,35 +277,7 @@ You can, of course, use default values other than `None`. Let's say that you want to declare the `q` query parameter to have a `min_length` of `3`, and to have a default value of `"fixedquery"`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial005.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *} /// note @@ -491,77 +319,13 @@ q: Union[str, None] = Query(default=None, min_length=3) So, when you need to declare a value as required while using `Query`, you can simply not declare a default value: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006.py!} -``` - -/// tip - -Notice that, even though in this case the `Query()` is used as the function parameter default value, we don't pass the `default=None` to `Query()`. - -Still, probably better to use the `Annotated` version. 😉 - -/// - -//// +{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} ### Required with Ellipsis (`...`) There's an alternative way to explicitly declare that a value is required. You can set the default to the literal value `...`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial006b_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006b.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py hl[9] *} /// info @@ -579,57 +343,7 @@ You can declare that a parameter can accept `None`, but that it's still required To do that, you can declare that `None` is a valid type but still use `...` as the default: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} /// tip @@ -649,71 +363,7 @@ When you define a query parameter explicitly with `Query` you can also declare i For example, to declare a query parameter `q` that can appear multiple times in the URL, you can write: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *} Then, with a URL like: @@ -748,49 +398,7 @@ The interactive API docs will update accordingly, to allow multiple values: And you can also define a default `list` of values if none are provided: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *} If you go to: @@ -813,35 +421,7 @@ the default of `q` will be: `["foo", "bar"]` and your response will be: You can also use `list` directly instead of `List[str]` (or `list[str]` in Python 3.9+): -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial013_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial013.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *} /// note @@ -867,111 +447,11 @@ Some of them might not show all the extra information declared yet, although in You can add a `title`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *} And a `description`: -//// tab | Python 3.10+ - -```Python hl_lines="14" -{!> ../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/query_params_str_validations/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/query_params_str_validations/tutorial008.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *} ## Alias parameters @@ -991,57 +471,7 @@ But you still need it to be exactly `item-query`... Then you can declare an `alias`, and that alias is what will be used to find the parameter value: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial009_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *} ## Deprecating parameters @@ -1051,57 +481,7 @@ You have to leave it there a while because there are clients using it, but you w Then pass the parameter `deprecated=True` to `Query`: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/query_params_str_validations/tutorial010_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="16" -{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="18" -{!> ../../docs_src/query_params_str_validations/tutorial010.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *} The docs will show it like this: @@ -1111,57 +491,7 @@ The docs will show it like this: To exclude a query parameter from the generated OpenAPI schema (and thus, from the automatic documentation systems), set the parameter `include_in_schema` of `Query` to `False`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *} ## Recap diff --git a/docs/en/docs/tutorial/query-params.md b/docs/en/docs/tutorial/query-params.md index 0d31d453d..c8477387c 100644 --- a/docs/en/docs/tutorial/query-params.md +++ b/docs/en/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ When you declare other function parameters that are not part of the path parameters, they are automatically interpreted as "query" parameters. -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} The query is the set of key-value pairs that go after the `?` in a URL, separated by `&` characters. @@ -63,21 +61,7 @@ The parameter values in your function will be: The same way, you can declare optional query parameters, by setting their default to `None`: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} In this case, the function parameter `q` will be optional, and will be `None` by default. @@ -91,21 +75,7 @@ Also notice that **FastAPI** is smart enough to notice that the path parameter ` You can also declare `bool` types, and they will be converted: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} In this case, if you go to: @@ -148,21 +118,7 @@ And you don't have to declare them in any specific order. They will be detected by name: -//// tab | Python 3.10+ - -```Python hl_lines="6 8" -{!> ../../docs_src/query_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 10" -{!> ../../docs_src/query_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Required query parameters @@ -172,9 +128,7 @@ If you don't want to add a specific value but just make it optional, set the def But when you want to make a query parameter required, you can just not declare any default value: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Here the query parameter `needy` is a required query parameter of type `str`. @@ -220,21 +174,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy And of course, you can define some parameters as required, some as having a default value, and some entirely optional: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params/tutorial006.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} In this case, there are 3 query parameters: diff --git a/docs/en/docs/tutorial/request-forms-and-files.md b/docs/en/docs/tutorial/request-forms-and-files.md index d60fc4c00..21e4bbd30 100644 --- a/docs/en/docs/tutorial/request-forms-and-files.md +++ b/docs/en/docs/tutorial/request-forms-and-files.md @@ -16,69 +16,13 @@ $ pip install python-multipart ## Import `File` and `Form` -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms_and_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *} ## Define `File` and `Form` parameters Create file and form parameters the same way you would for `Body` or `Query`: -//// tab | Python 3.9+ - -```Python hl_lines="10-12" -{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11" -{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/request_forms_and_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *} The files and form fields will be uploaded as form data and you will receive the files and form fields. diff --git a/docs/en/docs/tutorial/security/simple-oauth2.md b/docs/en/docs/tutorial/security/simple-oauth2.md index dc15bef20..1b70aa811 100644 --- a/docs/en/docs/tutorial/security/simple-oauth2.md +++ b/docs/en/docs/tutorial/security/simple-oauth2.md @@ -52,57 +52,7 @@ Now let's use the utilities provided by **FastAPI** to handle this. First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depends` in the *path operation* for `/token`: -//// tab | Python 3.10+ - -```Python hl_lines="4 78" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 78" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 79" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="2 74" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="4 76" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *} `OAuth2PasswordRequestForm` is a class dependency that declares a form body with: @@ -150,57 +100,7 @@ If there is no such user, we return an error saying "Incorrect username or passw For the error, we use the exception `HTTPException`: -//// tab | Python 3.10+ - -```Python hl_lines="3 79-81" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3 79-81" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3 80-82" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 75-77" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="3 77-79" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *} ### Check the password @@ -226,57 +126,7 @@ If your database is stolen, the thief won't have your users' plaintext passwords So, the thief won't be able to try to use those same passwords in another system (as many users use the same password everywhere, this would be dangerous). -//// tab | Python 3.10+ - -```Python hl_lines="82-85" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="82-85" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="83-86" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="78-81" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="80-83" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *} #### About `**user_dict` @@ -318,57 +168,7 @@ But for now, let's focus on the specific details we need. /// -//// tab | Python 3.10+ - -```Python hl_lines="87" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="87" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="88" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="83" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="85" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *} /// tip @@ -394,57 +194,7 @@ Both of these dependencies will just return an HTTP error if the user doesn't ex So, in our endpoint, we will only get a user if the user exists, was correctly authenticated, and is active: -//// tab | Python 3.10+ - -```Python hl_lines="58-66 69-74 94" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="58-66 69-74 94" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="59-67 70-75 95" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="56-64 67-70 88" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="58-66 69-72 90" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *} /// info diff --git a/docs/en/docs/tutorial/testing.md b/docs/en/docs/tutorial/testing.md index a204f596f..35940d920 100644 --- a/docs/en/docs/tutorial/testing.md +++ b/docs/en/docs/tutorial/testing.md @@ -30,9 +30,7 @@ Use the `TestClient` object the same way as you do with `httpx`. Write simple `assert` statements with the standard Python expressions that you need to check (again, standard `pytest`). -```Python hl_lines="2 12 15-18" -{!../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} /// tip @@ -78,9 +76,7 @@ Let's say you have a file structure as described in [Bigger Applications](bigger In the file `main.py` you have your **FastAPI** app: -```Python -{!../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### Testing file @@ -96,9 +92,8 @@ Then you could have a file `test_main.py` with your tests. It could live on the Because this file is in the same package, you can use relative imports to import the object `app` from the `main` module (`main.py`): -```Python hl_lines="3" -{!../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py hl[3] *} + ...and have the code for the tests just like before. @@ -182,9 +177,8 @@ Prefer to use the `Annotated` version if possible. You could then update `test_main.py` with the extended tests: -```Python -{!> ../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} + Whenever you need the client to pass information in the request and you don't know how to, you can search (Google) how to do it in `httpx`, or even how to do it with `requests`, as HTTPX's design is based on Requests' design. diff --git a/docs/es/docs/advanced/additional-status-codes.md b/docs/es/docs/advanced/additional-status-codes.md index 4a0625c25..b72798c2b 100644 --- a/docs/es/docs/advanced/additional-status-codes.md +++ b/docs/es/docs/advanced/additional-status-codes.md @@ -14,9 +14,7 @@ Pero también quieres que acepte nuevos ítems. Cuando los ítems no existan ant Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu contenido, asignando el `status_code` que quieras: -```Python hl_lines="4 25" -{!../../docs_src/additional_status_codes/tutorial001.py!} -``` +{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *} /// warning | Advertencia diff --git a/docs/es/docs/advanced/path-operation-advanced-configuration.md b/docs/es/docs/advanced/path-operation-advanced-configuration.md index 12399d581..600e2e074 100644 --- a/docs/es/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/es/docs/advanced/path-operation-advanced-configuration.md @@ -12,9 +12,7 @@ Puedes asignar el `operationId` de OpenAPI para ser usado en tu *operación de p En este caso tendrías que asegurarte de que sea único para cada operación. -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### Usando el nombre de la *función de la operación de path* en el operationId @@ -22,9 +20,7 @@ Si quieres usar tus nombres de funciones de API como `operationId`s, puedes iter Deberías hacerlo después de adicionar todas tus *operaciones de path*. -```Python hl_lines="2 12 13 14 15 16 17 18 19 20 21 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12,13,14,15,16,17,18,19,20,21,24] *} /// tip | Consejo @@ -44,9 +40,7 @@ Incluso si están en diferentes módulos (archivos Python). Para excluir una *operación de path* del esquema OpenAPI generado (y por tanto del la documentación generada automáticamente), usa el parámetro `include_in_schema` y asigna el valor como `False`; -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## Descripción avanzada desde el docstring @@ -56,6 +50,4 @@ Agregar un `\f` (un carácter de "form feed" escapado) hace que **FastAPI** trun No será mostrado en la documentación, pero otras herramientas (como Sphinx) serán capaces de usar el resto. -```Python hl_lines="19 20 21 22 23 24 25 26 27 28 29" -{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19,20,21,22,23,24,25,26,27,28,29] *} diff --git a/docs/es/docs/advanced/response-change-status-code.md b/docs/es/docs/advanced/response-change-status-code.md index ddfd05a77..6a44ea94e 100644 --- a/docs/es/docs/advanced/response-change-status-code.md +++ b/docs/es/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ Puedes declarar un parámetro de tipo `Response` en tu *función de la operació Y luego puedes establecer el `status_code` en ese objeto de respuesta *temporal*. -```Python hl_lines="1 9 12" -{!../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} Y luego puedes retornar cualquier objeto que necesites, como normalmente lo harías (un `dict`, un modelo de base de datos, etc). diff --git a/docs/es/docs/advanced/response-directly.md b/docs/es/docs/advanced/response-directly.md index 8800d2510..3cab11d99 100644 --- a/docs/es/docs/advanced/response-directly.md +++ b/docs/es/docs/advanced/response-directly.md @@ -34,9 +34,7 @@ Por ejemplo, no puedes poner un modelo Pydantic en una `JSONResponse` sin primer Para esos casos, puedes usar el `jsonable_encoder` para convertir tus datos antes de pasarlos a la respuesta: -```Python hl_lines="4 6 20 21" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[4,6,20,21] *} /// note | Detalles Técnicos @@ -56,9 +54,7 @@ Digamos que quieres devolver una respuesta documentación de Strawberry. diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md index 156907ad1..de502314e 100644 --- a/docs/es/docs/python-types.md +++ b/docs/es/docs/python-types.md @@ -22,9 +22,8 @@ Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al s Comencemos con un ejemplo simple: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Llamar este programa nos muestra el siguiente output: @@ -38,9 +37,8 @@ La función hace lo siguiente: * Convierte la primera letra de cada uno en una letra mayúscula con `title()`. * Las concatena con un espacio en la mitad. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Edítalo @@ -82,9 +80,8 @@ Eso es todo. Esos son los "type hints": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + No es lo mismo a declarar valores por defecto, como sería con: @@ -112,9 +109,8 @@ Con esto puedes moverte hacia abajo viendo las opciones hasta que encuentras una Mira esta función que ya tiene type hints: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Como el editor conoce el tipo de las variables no solo obtienes auto-completado, si no que también obtienes chequeo de errores: @@ -122,9 +118,8 @@ Como el editor conoce el tipo de las variables no solo obtienes auto-completado, Ahora que sabes que tienes que arreglarlo convierte `age` a un string con `str(age)`: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Declarando tipos @@ -143,9 +138,8 @@ Por ejemplo, puedes usar: * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Tipos con sub-tipos @@ -161,9 +155,8 @@ Por ejemplo, vamos a definir una variable para que sea una `list` compuesta de ` De `typing`, importa `List` (con una `L` mayúscula): -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + Declara la variable con la misma sintaxis de los dos puntos (`:`). @@ -171,9 +164,8 @@ Pon `List` como el tipo. Como la lista es un tipo que permite tener un "sub-tipo" pones el sub-tipo en corchetes `[]`: -```Python hl_lines="4" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + Esto significa: la variable `items` es una `list` y cada uno de los ítems en esta lista es un `str`. @@ -191,9 +183,8 @@ El editor aún sabe que es un `str` y provee soporte para ello. Harías lo mismo para declarar `tuple`s y `set`s: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + Esto significa: @@ -208,9 +199,8 @@ El primer sub-tipo es para los keys del `dict`. El segundo sub-tipo es para los valores del `dict`: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + Esto significa: @@ -224,15 +214,13 @@ También puedes declarar una clase como el tipo de una variable. Digamos que tienes una clase `Person`con un nombre: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial009.py!} -``` +{* ../../docs_src/python_types/tutorial009.py hl[1:3] *} + Entonces puedes declarar una variable que sea de tipo `Person`: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial009.py!} -``` +{* ../../docs_src/python_types/tutorial009.py hl[6] *} + Una vez más tendrás todo el soporte del editor: @@ -252,9 +240,8 @@ Y obtienes todo el soporte del editor con el objeto resultante. Tomado de la documentación oficial de Pydantic: -```Python -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py *} + /// info | Información diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md index 68df00e64..4cc4cc11d 100644 --- a/docs/es/docs/tutorial/first-steps.md +++ b/docs/es/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Un archivo muy simple de FastAPI podría verse así: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Copia eso a un archivo `main.py`. @@ -133,9 +131,7 @@ También podrías usarlo para generar código automáticamente, para los cliente ### Paso 1: importa `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` es una clase de Python que provee toda la funcionalidad para tu API. @@ -149,9 +145,7 @@ También puedes usar toda la funcionalidad de 連結
します。 -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### 編集 @@ -82,9 +80,8 @@ John Doe それが「型ヒント」です: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + これは、以下のようにデフォルト値を宣言するのと同じではありません: @@ -112,9 +109,8 @@ John Doe この関数を見てください。すでに型ヒントを持っています: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + エディタは変数の型を知っているので、補完だけでなく、エラーチェックをすることもできます。 @@ -122,9 +118,8 @@ John Doe これで`age`を`str(age)`で文字列に変換して修正する必要があることがわかります: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## 型の宣言 @@ -143,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### 型パラメータを持つジェネリック型 @@ -161,9 +155,8 @@ John Doe `typing`から`List`をインポートします(大文字の`L`を含む): -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + 同じようにコロン(`:`)の構文で変数を宣言します。 @@ -171,9 +164,8 @@ John Doe リストはいくつかの内部の型を含む型なので、それらを角括弧で囲んでいます。 -```Python hl_lines="4" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + /// tip | 豆知識 @@ -199,9 +191,8 @@ John Doe `tuple`と`set`の宣言も同様です: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + つまり: @@ -217,9 +208,8 @@ John Doe 2番目の型パラメータは`dict`の値です。 -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + つまり: @@ -256,15 +246,13 @@ John Doe 例えば、`Person`クラスという名前のクラスがあるとしましょう: -```Python hl_lines="1 2 3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1,2,3] *} + 変数の型を`Person`として宣言することができます: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + そして、再び、すべてのエディタのサポートを得ることができます: @@ -284,9 +272,8 @@ John Doe Pydanticの公式ドキュメントから引用: -```Python -{!../../docs_src/python_types/tutorial011.py!} -``` +{* ../../docs_src/python_types/tutorial011.py *} + /// info | 情報 diff --git a/docs/ja/docs/tutorial/background-tasks.md b/docs/ja/docs/tutorial/background-tasks.md index 8a4bc161c..650a079fb 100644 --- a/docs/ja/docs/tutorial/background-tasks.md +++ b/docs/ja/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ まず初めに、`BackgroundTasks` をインポートし、` BackgroundTasks` の型宣言と共に、*path operation 関数* のパラメーターを定義します: -```Python hl_lines="1 13" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** は、`BackgroundTasks` 型のオブジェクトを作成し、そのパラメーターに渡します。 @@ -33,17 +31,13 @@ また、書き込み操作では `async` と `await` を使用しないため、通常の `def` で関数を定義します。 -```Python hl_lines="6-9" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## バックグラウンドタスクの追加 *path operations 関数* 内で、`.add_task()` メソッドを使用してタスク関数を *background tasks* オブジェクトに渡します。 -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` は以下の引数を受け取ります: @@ -57,9 +51,7 @@ **FastAPI** は、それぞれの場合の処理​​方法と同じオブジェクトの再利用方法を知っているため、すべてのバックグラウンドタスクがマージされ、バックグラウンドで後で実行されます。 -```Python hl_lines="13 15 22 25" -{!../../docs_src/background_tasks/tutorial002.py!} -``` +{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *} この例では、レスポンスが送信された *後* にメッセージが `log.txt` ファイルに書き込まれます。 diff --git a/docs/ja/docs/tutorial/body-fields.md b/docs/ja/docs/tutorial/body-fields.md index 5b3b3622b..0466320f1 100644 --- a/docs/ja/docs/tutorial/body-fields.md +++ b/docs/ja/docs/tutorial/body-fields.md @@ -6,9 +6,7 @@ まず、以下のようにインポートします: -```Python hl_lines="4" -{!../../docs_src/body_fields/tutorial001.py!} -``` +{* ../../docs_src/body_fields/tutorial001.py hl[4] *} /// warning | 注意 @@ -20,9 +18,7 @@ 以下のように`Field`をモデルの属性として使用することができます: -```Python hl_lines="11 12 13 14" -{!../../docs_src/body_fields/tutorial001.py!} -``` +{* ../../docs_src/body_fields/tutorial001.py hl[11,12,13,14] *} `Field`は`Query`や`Path`、`Body`と同じように動作し、全く同様のパラメータなどを持ちます。 diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md index 982c23565..cbfdda4b2 100644 --- a/docs/ja/docs/tutorial/body-multiple-params.md +++ b/docs/ja/docs/tutorial/body-multiple-params.md @@ -8,9 +8,7 @@ また、デフォルトの`None`を設定することで、ボディパラメータをオプションとして宣言することもできます: -```Python hl_lines="19 20 21" -{!../../docs_src/body_multiple_params/tutorial001.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial001.py hl[19,20,21] *} /// note | 備考 @@ -33,9 +31,7 @@ しかし、`item`と`user`のように複数のボディパラメータを宣言することもできます: -```Python hl_lines="22" -{!../../docs_src/body_multiple_params/tutorial002.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial002.py hl[22] *} この場合、**FastAPI**は関数内に複数のボディパラメータ(Pydanticモデルである2つのパラメータ)があることに気付きます。 @@ -77,9 +73,7 @@ しかし、`Body`を使用して、**FastAPI** に別のボディキーとして扱うように指示することができます: -```Python hl_lines="23" -{!../../docs_src/body_multiple_params/tutorial003.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial003.py hl[23] *} この場合、**FastAPI** は以下のようなボディを期待します: @@ -114,9 +108,7 @@ q: str = None 以下において: -```Python hl_lines="27" -{!../../docs_src/body_multiple_params/tutorial004.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial004.py hl[27] *} /// info | 情報 @@ -138,9 +130,7 @@ item: Item = Body(..., embed=True) 以下において: -```Python hl_lines="17" -{!../../docs_src/body_multiple_params/tutorial005.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial005.py hl[17] *} この場合、**FastAPI** は以下のようなボディを期待します: diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md index dc2d5e81a..a1680d10f 100644 --- a/docs/ja/docs/tutorial/body-nested-models.md +++ b/docs/ja/docs/tutorial/body-nested-models.md @@ -6,9 +6,7 @@ 属性をサブタイプとして定義することができます。例えば、Pythonの`list`は以下のように定義できます: -```Python hl_lines="12" -{!../../docs_src/body_nested_models/tutorial001.py!} -``` +{* ../../docs_src/body_nested_models/tutorial001.py hl[12] *} これにより、各項目の型は宣言されていませんが、`tags`はある項目のリストになります。 @@ -20,9 +18,7 @@ まず、Pythonの標準の`typing`モジュールから`List`をインポートします: -```Python hl_lines="1" -{!../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### タイプパラメータを持つ`List`の宣言 @@ -43,9 +39,7 @@ my_list: List[str] そのため、以下の例では`tags`を具体的な「文字列のリスト」にすることができます: -```Python hl_lines="14" -{!../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[14] *} ## セット型 @@ -55,9 +49,7 @@ my_list: List[str] そのため、以下のように、`Set`をインポートして`str`の`set`として`tags`を宣言することができます: -```Python hl_lines="1 14" -{!../../docs_src/body_nested_models/tutorial003.py!} -``` +{* ../../docs_src/body_nested_models/tutorial003.py hl[1,14] *} これを使えば、データが重複しているリクエストを受けた場合でも、ユニークな項目のセットに変換されます。 @@ -79,17 +71,13 @@ Pydanticモデルの各属性には型があります。 例えば、`Image`モデルを定義することができます: -```Python hl_lines="9 10 11" -{!../../docs_src/body_nested_models/tutorial004.py!} -``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[9,10,11] *} ### サブモデルを型として使用 そして、それを属性の型として使用することができます: -```Python hl_lines="20" -{!../../docs_src/body_nested_models/tutorial004.py!} -``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[20] *} これは **FastAPI** が以下のようなボディを期待することを意味します: @@ -122,9 +110,7 @@ Pydanticモデルの各属性には型があります。 例えば、`Image`モデルのように`url`フィールドがある場合、`str`の代わりにPydanticの`HttpUrl`を指定することができます: -```Python hl_lines="4 10" -{!../../docs_src/body_nested_models/tutorial005.py!} -``` +{* ../../docs_src/body_nested_models/tutorial005.py hl[4,10] *} 文字列は有効なURLであることが確認され、そのようにJSONスキーマ・OpenAPIで文書化されます。 @@ -132,9 +118,7 @@ Pydanticモデルの各属性には型があります。 Pydanticモデルを`list`や`set`などのサブタイプとして使用することもできます: -```Python hl_lines="20" -{!../../docs_src/body_nested_models/tutorial006.py!} -``` +{* ../../docs_src/body_nested_models/tutorial006.py hl[20] *} これは、次のようなJSONボディを期待します(変換、検証、ドキュメントなど): @@ -172,9 +156,7 @@ Pydanticモデルを`list`や`set`などのサブタイプとして使用する 深くネストされた任意のモデルを定義することができます: -```Python hl_lines="9 14 20 23 27" -{!../../docs_src/body_nested_models/tutorial007.py!} -``` +{* ../../docs_src/body_nested_models/tutorial007.py hl[9,14,20,23,27] *} /// info | 情報 @@ -192,9 +174,7 @@ images: List[Image] 以下のように: -```Python hl_lines="15" -{!../../docs_src/body_nested_models/tutorial008.py!} -``` +{* ../../docs_src/body_nested_models/tutorial008.py hl[15] *} ## あらゆる場所でのエディタサポート @@ -224,9 +204,7 @@ Pydanticモデルではなく、`dict`を直接使用している場合はこの この場合、`int`のキーと`float`の値を持つものであれば、どんな`dict`でも受け入れることができます: -```Python hl_lines="15" -{!../../docs_src/body_nested_models/tutorial009.py!} -``` +{* ../../docs_src/body_nested_models/tutorial009.py hl[15] *} /// tip | 豆知識 diff --git a/docs/ja/docs/tutorial/body-updates.md b/docs/ja/docs/tutorial/body-updates.md index fcaeb0d16..ffbe52e1d 100644 --- a/docs/ja/docs/tutorial/body-updates.md +++ b/docs/ja/docs/tutorial/body-updates.md @@ -6,9 +6,7 @@ `jsonable_encoder`を用いて、入力データをJSON形式で保存できるデータに変換することができます(例:NoSQLデータベース)。例えば、`datetime`を`str`に変換します。 -```Python hl_lines="30 31 32 33 34 35" -{!../../docs_src/body_updates/tutorial001.py!} -``` +{* ../../docs_src/body_updates/tutorial001.py hl[30,31,32,33,34,35] *} 既存のデータを置き換えるべきデータを受け取るために`PUT`は使用されます。 @@ -56,9 +54,7 @@ これを使うことで、デフォルト値を省略して、設定された(リクエストで送られた)データのみを含む`dict`を生成することができます: -```Python hl_lines="34" -{!../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[34] *} ### Pydanticの`update`パラメータ @@ -66,9 +62,7 @@ `stored_item_model.copy(update=update_data)`のように: -```Python hl_lines="35" -{!../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[35] *} ### 部分的更新のまとめ @@ -85,9 +79,7 @@ * データをDBに保存します。 * 更新されたモデルを返します。 -```Python hl_lines="30 31 32 33 34 35 36 37" -{!../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[30,31,32,33,34,35,36,37] *} /// tip | 豆知識 diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md index 277ee79c8..8376959d5 100644 --- a/docs/ja/docs/tutorial/body.md +++ b/docs/ja/docs/tutorial/body.md @@ -22,9 +22,7 @@ GET リクエストでボディを送信することは、仕様では未定義 ます初めに、 `pydantic` から `BaseModel` をインポートする必要があります: -```Python hl_lines="2" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[2] *} ## データモデルの作成 @@ -32,9 +30,7 @@ GET リクエストでボディを送信することは、仕様では未定義 すべての属性にpython標準の型を使用します: -```Python hl_lines="5-9" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[5:9] *} クエリパラメータの宣言と同様に、モデル属性がデフォルト値をもつとき、必須な属性ではなくなります。それ以外は必須になります。オプショナルな属性にしたい場合は `None` を使用してください。 @@ -62,9 +58,7 @@ GET リクエストでボディを送信することは、仕様では未定義 *パスオペレーション* に加えるために、パスパラメータやクエリパラメータと同じ様に宣言します: -```Python hl_lines="16" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[16] *} ...そして、作成したモデル `Item` で型を宣言します。 @@ -131,9 +125,7 @@ GET リクエストでボディを送信することは、仕様では未定義 関数内部で、モデルの全ての属性に直接アクセスできます: -```Python hl_lines="19" -{!../../docs_src/body/tutorial002.py!} -``` +{* ../../docs_src/body/tutorial002.py hl[19] *} ## リクエストボディ + パスパラメータ @@ -141,9 +133,7 @@ GET リクエストでボディを送信することは、仕様では未定義 **FastAPI** はパスパラメータである関数パラメータは**パスから受け取り**、Pydanticモデルによって宣言された関数パラメータは**リクエストボディから受け取る**ということを認識します。 -```Python hl_lines="15-16" -{!../../docs_src/body/tutorial003.py!} -``` +{* ../../docs_src/body/tutorial003.py hl[15:16] *} ## リクエストボディ + パスパラメータ + クエリパラメータ @@ -151,9 +141,7 @@ GET リクエストでボディを送信することは、仕様では未定義 **FastAPI** はそれぞれを認識し、適切な場所からデータを取得します。 -```Python hl_lines="16" -{!../../docs_src/body/tutorial004.py!} -``` +{* ../../docs_src/body/tutorial004.py hl[16] *} 関数パラメータは以下の様に認識されます: diff --git a/docs/ja/docs/tutorial/cookie-params.md b/docs/ja/docs/tutorial/cookie-params.md index 7f029b483..13af6d3c7 100644 --- a/docs/ja/docs/tutorial/cookie-params.md +++ b/docs/ja/docs/tutorial/cookie-params.md @@ -6,9 +6,7 @@ まず、`Cookie`をインポートします: -```Python hl_lines="3" -{!../../docs_src/cookie_params/tutorial001.py!} -``` +{* ../../docs_src/cookie_params/tutorial001.py hl[3] *} ## `Cookie`のパラメータを宣言 @@ -16,9 +14,7 @@ 最初の値がデフォルト値で、追加の検証パラメータや注釈パラメータをすべて渡すことができます: -```Python hl_lines="9" -{!../../docs_src/cookie_params/tutorial001.py!} -``` +{* ../../docs_src/cookie_params/tutorial001.py hl[9] *} /// note | 技術詳細 diff --git a/docs/ja/docs/tutorial/cors.md b/docs/ja/docs/tutorial/cors.md index 9834a460b..f7bd59b70 100644 --- a/docs/ja/docs/tutorial/cors.md +++ b/docs/ja/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * 特定のHTTPメソッド (`POST`、`PUT`) またはワイルドカード `"*"` を使用してすべて許可。 * 特定のHTTPヘッダー、またはワイルドカード `"*"`を使用してすべて許可。 -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} `CORSMiddleware` 実装のデフォルトのパラメータはCORSに関して制限を与えるものになっているので、ブラウザにドメインを跨いで特定のオリジン、メソッド、またはヘッダーを使用可能にするためには、それらを明示的に有効にする必要があります diff --git a/docs/ja/docs/tutorial/debugging.md b/docs/ja/docs/tutorial/debugging.md index 7413332a8..6c29679ef 100644 --- a/docs/ja/docs/tutorial/debugging.md +++ b/docs/ja/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ Visual Studio CodeやPyCharmなどを使用して、エディター上でデバ FastAPIアプリケーション上で、`uvicorn` を直接インポートして実行します: -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### `__name__ == "__main__"` について diff --git a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md index 55885a61f..80153529e 100644 --- a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,9 +6,7 @@ 前の例では、依存関係("dependable")から`dict`を返していました: -```Python hl_lines="9" -{!../../docs_src/dependencies/tutorial001.py!} -``` +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} しかし、*path operation関数*のパラメータ`commons`に`dict`が含まれています。 @@ -71,21 +69,15 @@ FastAPIが実際にチェックしているのは、それが「呼び出し可 そこで、上で紹介した依存関係の`common_parameters`を`CommonQueryParams`クラスに変更します: -```Python hl_lines="11 12 13 14 15" -{!../../docs_src/dependencies/tutorial002.py!} -``` +{* ../../docs_src/dependencies/tutorial002.py hl[11,12,13,14,15] *} クラスのインスタンスを作成するために使用される`__init__`メソッドに注目してください: -```Python hl_lines="12" -{!../../docs_src/dependencies/tutorial002.py!} -``` +{* ../../docs_src/dependencies/tutorial002.py hl[12] *} ...以前の`common_parameters`と同じパラメータを持っています: -```Python hl_lines="8" -{!../../docs_src/dependencies/tutorial001.py!} -``` +{* ../../docs_src/dependencies/tutorial001.py hl[8] *} これらのパラメータは **FastAPI** が依存関係を「解決」するために使用するものです。 @@ -101,9 +93,7 @@ FastAPIが実際にチェックしているのは、それが「呼び出し可 これで、このクラスを使用して依存関係を宣言することができます。 -```Python hl_lines="19" -{!../../docs_src/dependencies/tutorial002.py!} -``` +{* ../../docs_src/dependencies/tutorial002.py hl[19] *} **FastAPI** は`CommonQueryParams`クラスを呼び出します。これにより、そのクラスの「インスタンス」が作成され、インスタンスはパラメータ`commons`として関数に渡されます。 @@ -143,9 +133,7 @@ commons = Depends(CommonQueryParams) 以下にあるように: -```Python hl_lines="19" -{!../../docs_src/dependencies/tutorial003.py!} -``` +{* ../../docs_src/dependencies/tutorial003.py hl[19] *} しかし、型を宣言することは推奨されています。そうすれば、エディタは`commons`のパラメータとして何が渡されるかを知ることができ、コードの補完や型チェックなどを行うのに役立ちます: @@ -179,9 +167,7 @@ commons: CommonQueryParams = Depends() 同じ例では以下のようになります: -```Python hl_lines="19" -{!../../docs_src/dependencies/tutorial004.py!} -``` +{* ../../docs_src/dependencies/tutorial004.py hl[19] *} ...そして **FastAPI** は何をすべきか知っています。 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 3b78f4e0b..0fb15ae02 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,9 +14,7 @@ それは`Depends()`の`list`であるべきです: -```Python hl_lines="17" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[17] *} これらの依存関係は、通常の依存関係と同様に実行・解決されます。しかし、それらの値(何かを返す場合)は*path operation関数*には渡されません。 @@ -38,17 +36,13 @@ これらはリクエストの要件(ヘッダのようなもの)やその他のサブ依存関係を宣言することができます: -```Python hl_lines="6 11" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[6,11] *} ### 例外の発生 これらの依存関係は通常の依存関係と同じように、例外を`raise`発生させることができます: -```Python hl_lines="8 13" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[8,13] *} ### 戻り値 @@ -56,9 +50,7 @@ つまり、すでにどこかで使っている通常の依存関係(値を返すもの)を再利用することができ、値は使われなくても依存関係は実行されます: -```Python hl_lines="9 14" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[9,14] *} ## *path operations*のグループに対する依存関係 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md index bd4e689bf..35a69de0d 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md @@ -41,21 +41,15 @@ pip install async-exit-stack async-generator レスポンスを送信する前に`yield`文を含む前のコードのみが実行されます。 -```Python hl_lines="2 3 4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[2,3,4] *} 生成された値は、*path operations*や他の依存関係に注入されるものです: -```Python hl_lines="4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} `yield`文に続くコードは、レスポンスが送信された後に実行されます: -```Python hl_lines="5 6" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[5,6] *} /// tip | 豆知識 @@ -75,9 +69,7 @@ pip install async-exit-stack async-generator 同様に、`finally`を用いて例外があったかどうかにかかわらず、終了ステップを確実に実行することができます。 -```Python hl_lines="3 5" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *} ## `yield`を持つサブ依存関係 @@ -87,9 +79,7 @@ pip install async-exit-stack async-generator 例えば、`dependency_c`は`dependency_b`と`dependency_b`に依存する`dependency_a`に、依存することができます: -```Python hl_lines="4 12 20" -{!../../docs_src/dependencies/tutorial008.py!} -``` +{* ../../docs_src/dependencies/tutorial008.py hl[4,12,20] *} そして、それらはすべて`yield`を使用することができます。 @@ -97,9 +87,7 @@ pip install async-exit-stack async-generator そして、`dependency_b`は`dependency_a`(ここでは`dep_a`という名前)の値を終了コードで利用できるようにする必要があります。 -```Python hl_lines="16 17 24 25" -{!../../docs_src/dependencies/tutorial008.py!} -``` +{* ../../docs_src/dependencies/tutorial008.py hl[16,17,24,25] *} 同様に、`yield`と`return`が混在した依存関係を持つこともできます。 @@ -233,9 +221,7 @@ Pythonでは、`typing.Union`を使用します: -```Python hl_lines="1 14 15 18 19 20 33" -{!../../docs_src/extra_models/tutorial003.py!} -``` +{* ../../docs_src/extra_models/tutorial003.py hl[1,14,15,18,19,20,33] *} ## モデルのリスト @@ -178,9 +172,7 @@ OpenAPIでは`anyOf`で定義されます。 そのためには、標準のPythonの`typing.List`を使用する: -```Python hl_lines="1 20" -{!../../docs_src/extra_models/tutorial004.py!} -``` +{* ../../docs_src/extra_models/tutorial004.py hl[1,20] *} ## 任意の`dict`を持つレスポンス @@ -190,9 +182,7 @@ OpenAPIでは`anyOf`で定義されます。 この場合、`typing.Dict`を使用することができます: -```Python hl_lines="1 8" -{!../../docs_src/extra_models/tutorial005.py!} -``` +{* ../../docs_src/extra_models/tutorial005.py hl[1,8] *} ## まとめ diff --git a/docs/ja/docs/tutorial/first-steps.md b/docs/ja/docs/tutorial/first-steps.md index 3691d13d2..d14f0cbec 100644 --- a/docs/ja/docs/tutorial/first-steps.md +++ b/docs/ja/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ 最もシンプルなFastAPIファイルは以下のようになります: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} これを`main.py`にコピーします。 @@ -133,9 +131,7 @@ OpenAPIスキーマは、FastAPIに含まれている2つのインタラクテ ### Step 1: `FastAPI`をインポート -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI`は、APIのすべての機能を提供するPythonクラスです。 @@ -149,9 +145,7 @@ OpenAPIスキーマは、FastAPIに含まれている2つのインタラクテ ### Step 2: `FastAPI`の「インスタンス」を生成 -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} ここで、`app`変数が`FastAPI`クラスの「インスタンス」になります。 これが、すべてのAPIを作成するための主要なポイントになります。 @@ -170,9 +164,7 @@ $ uvicorn main:app --reload 以下のようなアプリを作成したとき: -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} そして、それを`main.py`ファイルに置き、次のように`uvicorn`を呼び出します: @@ -249,9 +241,7 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを #### *パスオペレーションデコレータ*を定義 -```Python hl_lines="6" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} `@app.get("/")`は直下の関数が下記のリクエストの処理を担当することを**FastAPI**に伝えます: * パス `/` @@ -304,9 +294,7 @@ Pythonにおける`@something`シンタックスはデコレータと呼ばれ * **オペレーション**: は`get`です。 * **関数**: 「デコレータ」の直下にある関数 (`@app.get("/")`の直下) です。 -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} これは、Pythonの関数です。 @@ -318,9 +306,7 @@ Pythonにおける`@something`シンタックスはデコレータと呼ばれ `async def`の代わりに通常の関数として定義することもできます: -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} /// note | 備考 @@ -330,9 +316,7 @@ Pythonにおける`@something`シンタックスはデコレータと呼ばれ ### Step 5: コンテンツの返信 -```Python hl_lines="8" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} `dict`、`list`、`str`、`int`などを返すことができます。 diff --git a/docs/ja/docs/tutorial/handling-errors.md b/docs/ja/docs/tutorial/handling-errors.md index d270fd75b..9a46cc738 100644 --- a/docs/ja/docs/tutorial/handling-errors.md +++ b/docs/ja/docs/tutorial/handling-errors.md @@ -25,9 +25,7 @@ HTTPレスポンスをエラーでクライアントに返すには、`HTTPExcep ### `HTTPException`のインポート -```Python hl_lines="1" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} ### コード内での`HTTPException`の発生 @@ -41,9 +39,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 この例では、クライアントが存在しないIDでアイテムを要求した場合、`404`のステータスコードを持つ例外を発生させます: -```Python hl_lines="11" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} ### レスポンス結果 @@ -81,9 +77,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 しかし、高度なシナリオのために必要な場合には、カスタムヘッダーを追加することができます: -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial002.py!} -``` +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} ## カスタム例外ハンドラのインストール @@ -95,9 +89,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 カスタム例外ハンドラを`@app.exception_handler()`で追加することができます: -```Python hl_lines="5 6 7 13 14 15 16 17 18 24" -{!../../docs_src/handling_errors/tutorial003.py!} -``` +{* ../../docs_src/handling_errors/tutorial003.py hl[5,6,7,13,14,15,16,17,18,24] *} ここで、`/unicorns/yolo`をリクエストすると、*path operation*は`UnicornException`を`raise`します。 @@ -135,9 +127,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 この例外ハンドラは`Requset`と例外を受け取ります。 -```Python hl_lines="2 14 15 16" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14,15,16] *} これで、`/items/foo`にアクセスすると、デフォルトのJSONエラーの代わりに以下が返されます: @@ -188,9 +178,7 @@ path -> item_id 例えば、これらのエラーに対しては、JSONではなくプレーンテキストを返すようにすることができます: -```Python hl_lines="3 4 9 10 11 22" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[3,4,9,10,11,22] *} /// note | 技術詳細 @@ -206,9 +194,7 @@ path -> item_id アプリ開発中に本体のログを取ってデバッグしたり、ユーザーに返したりなどに使用することができます。 -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial005.py!} -``` +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} ここで、以下のような無効な項目を送信してみてください: @@ -268,9 +254,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException デフォルトの例外ハンドラを`fastapi.exception_handlers`からインポートして再利用することができます: -```Python hl_lines="2 3 4 5 15 21" -{!../../docs_src/handling_errors/tutorial006.py!} -``` +{* ../../docs_src/handling_errors/tutorial006.py hl[2,3,4,5,15,21] *} この例では、非常に表現力のあるメッセージでエラーを`print`しています。 diff --git a/docs/ja/docs/tutorial/header-params.md b/docs/ja/docs/tutorial/header-params.md index c741005d3..ac89afbdb 100644 --- a/docs/ja/docs/tutorial/header-params.md +++ b/docs/ja/docs/tutorial/header-params.md @@ -6,9 +6,7 @@ まず、`Header`をインポートします: -```Python hl_lines="3" -{!../../docs_src/header_params/tutorial001.py!} -``` +{* ../../docs_src/header_params/tutorial001.py hl[3] *} ## `Header`のパラメータの宣言 @@ -16,9 +14,7 @@ 最初の値がデフォルト値で、追加の検証パラメータや注釈パラメータをすべて渡すことができます。 -```Python hl_lines="9" -{!../../docs_src/header_params/tutorial001.py!} -``` +{* ../../docs_src/header_params/tutorial001.py hl[9] *} /// note | 技術詳細 @@ -50,9 +46,7 @@ もしなんらかの理由でアンダースコアからハイフンへの自動変換を無効にする必要がある場合は、`Header`の`convert_underscores`に`False`を設定してください: -```Python hl_lines="9" -{!../../docs_src/header_params/tutorial002.py!} -``` +{* ../../docs_src/header_params/tutorial002.py hl[9] *} /// warning | 注意 @@ -70,9 +64,7 @@ 例えば、複数回出現する可能性のある`X-Token`のヘッダを定義するには、以下のように書くことができます: -```Python hl_lines="9" -{!../../docs_src/header_params/tutorial003.py!} -``` +{* ../../docs_src/header_params/tutorial003.py hl[9] *} もし、その*path operation*で通信する場合は、次のように2つのHTTPヘッダーを送信します: diff --git a/docs/ja/docs/tutorial/metadata.md b/docs/ja/docs/tutorial/metadata.md index 201322cb4..b93dedcb9 100644 --- a/docs/ja/docs/tutorial/metadata.md +++ b/docs/ja/docs/tutorial/metadata.md @@ -13,9 +13,7 @@ これらを設定するには、パラメータ `title`、`description`、`version` を使用します: -```Python hl_lines="4-6" -{!../../docs_src/metadata/tutorial001.py!} -``` +{* ../../docs_src/metadata/tutorial001.py hl[4:6] *} この設定では、自動APIドキュメントは以下の様になります: @@ -41,9 +39,7 @@ タグのためのメタデータを作成し、それを `openapi_tags` パラメータに渡します。 -```Python hl_lines="3-16 18" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} 説明文 (description) の中で Markdown を使用できることに注意してください。たとえば、「login」は太字 (**login**) で表示され、「fancy」は斜体 (_fancy_) で表示されます。 @@ -57,9 +53,7 @@ `tags` パラメーターを使用して、それぞれの *path operations* (および `APIRouter`) を異なるタグに割り当てます: -```Python hl_lines="21 26" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} /// info | 情報 @@ -87,9 +81,7 @@ たとえば、`/api/v1/openapi.json` で提供されるように設定するには: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial002.py!} -``` +{* ../../docs_src/metadata/tutorial002.py hl[3] *} OpenAPIスキーマを完全に無効にする場合は、`openapi_url=None` を設定できます。これにより、それを使用するドキュメントUIも無効になります。 @@ -106,6 +98,4 @@ OpenAPIスキーマを完全に無効にする場合は、`openapi_url=None` を たとえば、`/documentation` でSwagger UIが提供されるように設定し、ReDocを無効にするには: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial003.py!} -``` +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/ja/docs/tutorial/middleware.md b/docs/ja/docs/tutorial/middleware.md index 3a3d8bb22..326e9145c 100644 --- a/docs/ja/docs/tutorial/middleware.md +++ b/docs/ja/docs/tutorial/middleware.md @@ -31,9 +31,7 @@ * 次に、対応する*path operation*によって生成された `response` を返します。 * その後、`response` を返す前にさらに `response` を変更することもできます。 -```Python hl_lines="8-9 11 14" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} /// tip | 豆知識 @@ -59,9 +57,7 @@ 例えば、リクエストの処理とレスポンスの生成にかかった秒数を含むカスタムヘッダー `X-Process-Time` を追加できます: -```Python hl_lines="10 12-13" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} ## その他のミドルウェア diff --git a/docs/ja/docs/tutorial/path-operation-configuration.md b/docs/ja/docs/tutorial/path-operation-configuration.md index 36223d35d..0cc38cb25 100644 --- a/docs/ja/docs/tutorial/path-operation-configuration.md +++ b/docs/ja/docs/tutorial/path-operation-configuration.md @@ -16,9 +16,7 @@ しかし、それぞれの番号コードが何のためのものか覚えていない場合は、`status`のショートカット定数を使用することができます: -```Python hl_lines="3 17" -{!../../docs_src/path_operation_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *} そのステータスコードはレスポンスで使用され、OpenAPIスキーマに追加されます。 @@ -34,9 +32,7 @@ `tags`パラメータを`str`の`list`(通常は1つの`str`)と一緒に渡すと、*path operation*にタグを追加できます: -```Python hl_lines="17 22 27" -{!../../docs_src/path_operation_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *} これらはOpenAPIスキーマに追加され、自動ドキュメントのインターフェースで使用されます: @@ -46,9 +42,7 @@ `summary`と`description`を追加できます: -```Python hl_lines="20-21" -{!../../docs_src/path_operation_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *} ## docstringを用いた説明 @@ -56,9 +50,7 @@ docstringにMarkdownを記述すれば、正しく解釈されて表示されます。(docstringのインデントを考慮して) -```Python hl_lines="19-27" -{!../../docs_src/path_operation_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *} これは対話的ドキュメントで使用されます: @@ -68,9 +60,7 @@ docstringにdeprecated
としてマークする必要があるが、それを削除しない場合は、`deprecated`パラメータを渡します: -```Python hl_lines="16" -{!../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} 対話的ドキュメントでは非推奨と明記されます: diff --git a/docs/ja/docs/tutorial/path-params-numeric-validations.md b/docs/ja/docs/tutorial/path-params-numeric-validations.md index 7d55ad30c..13a71f72f 100644 --- a/docs/ja/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ja/docs/tutorial/path-params-numeric-validations.md @@ -6,9 +6,7 @@ まず初めに、`fastapi`から`Path`をインポートします: -```Python hl_lines="1" -{!../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[1] *} ## メタデータの宣言 @@ -16,9 +14,7 @@ 例えば、パスパラメータ`item_id`に対して`title`のメタデータを宣言するには以下のようにします: -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[8] *} /// note | 備考 @@ -46,9 +42,7 @@ Pythonは「デフォルト」を持たない値の前に「デフォルト」 そのため、以下のように関数を宣言することができます: -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[8] *} ## 必要に応じてパラメータを並び替えるトリック @@ -58,9 +52,7 @@ Pythonは「デフォルト」を持たない値の前に「デフォルト」 Pythonはその`*`で何かをすることはありませんが、それ以降のすべてのパラメータがキーワード引数(キーと値のペア)として呼ばれるべきものであると知っているでしょう。それはkwargsとしても知られています。たとえデフォルト値がなくても。 -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[8] *} ## 数値の検証: 以上 @@ -68,9 +60,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなれけばなりません。 -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *} ## 数値の検証: より大きいと小なりイコール @@ -79,9 +69,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 * `gt`: より大きい(`g`reater `t`han) * `le`: 小なりイコール(`l`ess than or `e`qual) -```Python hl_lines="9" -{!../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *} ## 数値の検証: 浮動小数点、 大なり小なり @@ -93,9 +81,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 これはltも同じです。 -```Python hl_lines="11" -{!../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *} ## まとめ diff --git a/docs/ja/docs/tutorial/path-params.md b/docs/ja/docs/tutorial/path-params.md index d86a27cb4..1893ec12f 100644 --- a/docs/ja/docs/tutorial/path-params.md +++ b/docs/ja/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメータ」や「パス変数」を宣言できます: -```Python hl_lines="6 7" -{!../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6,7] *} パスパラメータ `item_id` の値は、引数 `item_id` として関数に渡されます。 @@ -18,9 +16,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー 標準のPythonの型アノテーションを使用して、関数内のパスパラメータの型を宣言できます: -```Python hl_lines="7" -{!../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} ここでは、 `item_id` は `int` として宣言されています。 @@ -121,9 +117,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー *path operations* は順に評価されるので、 `/users/me` が `/users/{user_id}` よりも先に宣言されているか確認する必要があります: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} それ以外の場合、 `/users/{users_id}` は `/users/me` としてもマッチします。値が「"me"」であるパラメータ `user_id` を受け取ると「考え」ます。 @@ -139,9 +133,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー そして、固定値のクラス属性を作ります。すると、その値が使用可能な値となります: -```Python hl_lines="1 6 7 8 9" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6,7,8,9] *} /// info | 情報 @@ -159,9 +151,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー 次に、作成したenumクラスである`ModelName`を使用した型アノテーションをもつ*パスパラメータ*を作成します: -```Python hl_lines="16" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### ドキュメントの確認 @@ -177,17 +167,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー これは、作成した列挙型 `ModelName` の*列挙型メンバ*と比較できます: -```Python hl_lines="17" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### *列挙値*の取得 `model_name.value` 、もしくは一般に、 `your_enum_member.value` を使用して実際の値 (この場合は `str`) を取得できます。 -```Python hl_lines="20" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} /// tip | 豆知識 @@ -201,9 +187,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー それらはクライアントに返される前に適切な値 (この場合は文字列) に変換されます。 -```Python hl_lines="18 21 23" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} クライアントは以下の様なJSONレスポンスを得ます: @@ -242,9 +226,7 @@ Starletteのオプションを直接使用することで、以下のURLの様 したがって、以下の様に使用できます: -```Python hl_lines="6" -{!../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} /// tip | 豆知識 diff --git a/docs/ja/docs/tutorial/query-params-str-validations.md b/docs/ja/docs/tutorial/query-params-str-validations.md index 6450c91c4..22b89e452 100644 --- a/docs/ja/docs/tutorial/query-params-str-validations.md +++ b/docs/ja/docs/tutorial/query-params-str-validations.md @@ -4,9 +4,7 @@ 以下のアプリケーションを例にしてみましょう: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial001.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *} クエリパラメータ `q` は `Optional[str]` 型で、`None` を許容する `str` 型を意味しており、デフォルトは `None` です。そのため、FastAPIはそれが必須ではないと理解します。 @@ -26,17 +24,13 @@ FastAPIは、 `q` はデフォルト値が `=None` であるため、必須で そのために、まずは`fastapi`から`Query`をインポートします: -```Python hl_lines="3" -{!../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *} ## デフォルト値として`Query`を使用 パラメータのデフォルト値として使用し、パラメータ`max_length`を50に設定します: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} デフォルト値`None`を`Query(default=None)`に置き換える必要があるので、`Query`の最初の引数はデフォルト値を定義するのと同じです。 @@ -86,17 +80,13 @@ q: Union[str, None] = Query(default=None, max_length=50) パラメータ`min_length`も追加することができます: -```Python hl_lines="10" -{!../../docs_src/query_params_str_validations/tutorial003.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[10] *} ## 正規表現の追加 パラメータが一致するべき正規表現を定義することができます: -```Python hl_lines="11" -{!../../docs_src/query_params_str_validations/tutorial004.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[11] *} この特定の正規表現は受け取ったパラメータの値をチェックします: @@ -114,9 +104,7 @@ q: Union[str, None] = Query(default=None, max_length=50) クエリパラメータ`q`の`min_length`を`3`とし、デフォルト値を`fixedquery`としてみましょう: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial005.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} /// note | 備考 @@ -146,9 +134,7 @@ q: Union[str, None] = Query(default=None, min_length=3) そのため、`Query`を使用して必須の値を宣言する必要がある場合は、第一引数に`...`を使用することができます: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial006.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} /// info | 情報 @@ -164,9 +150,7 @@ q: Union[str, None] = Query(default=None, min_length=3) 例えば、URL内に複数回出現するクエリパラメータ`q`を宣言するには以下のように書きます: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial011.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} そしてURLは以下です: @@ -201,9 +185,7 @@ http://localhost:8000/items/?q=foo&q=bar また、値が指定されていない場合はデフォルトの`list`を定義することもできます。 -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial012.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} 以下のURLを開くと: @@ -226,9 +208,7 @@ http://localhost:8000/items/ `List[str]`の代わりに直接`list`を使うこともできます: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} /// note | 備考 @@ -254,15 +234,11 @@ http://localhost:8000/items/ `title`を追加できます: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial007.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[9] *} `description`を追加できます: -```Python hl_lines="13" -{!../../docs_src/query_params_str_validations/tutorial008.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## エイリアスパラメータ @@ -282,9 +258,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems それならば、`alias`を宣言することができます。エイリアスはパラメータの値を見つけるのに使用されます: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial009.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} ## 非推奨パラメータ @@ -294,9 +268,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems その場合、`Query`にパラメータ`deprecated=True`を渡します: -```Python hl_lines="18" -{!../../docs_src/query_params_str_validations/tutorial010.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} ドキュメントは以下のようになります: diff --git a/docs/ja/docs/tutorial/query-params.md b/docs/ja/docs/tutorial/query-params.md index 71f78eca5..74e455579 100644 --- a/docs/ja/docs/tutorial/query-params.md +++ b/docs/ja/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ パスパラメータではない関数パラメータを宣言すると、それらは自動的に "クエリ" パラメータとして解釈されます。 -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} クエリはURL内で `?` の後に続くキーとバリューの組で、 `&` で区切られています。 @@ -63,9 +61,7 @@ http://127.0.0.1:8000/items/?skip=20 同様に、デフォルト値を `None` とすることで、オプショナルなクエリパラメータを宣言できます: -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial002.py!} -``` +{* ../../docs_src/query_params/tutorial002.py hl[9] *} この場合、関数パラメータ `q` はオプショナルとなり、デフォルトでは `None` になります。 @@ -79,9 +75,7 @@ http://127.0.0.1:8000/items/?skip=20 `bool` 型も宣言できます。これは以下の様に変換されます: -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial003.py!} -``` +{* ../../docs_src/query_params/tutorial003.py hl[9] *} この場合、以下にアクセスすると: @@ -123,9 +117,7 @@ http://127.0.0.1:8000/items/foo?short=yes 名前で判別されます: -```Python hl_lines="8 10" -{!../../docs_src/query_params/tutorial004.py!} -``` +{* ../../docs_src/query_params/tutorial004.py hl[8,10] *} ## 必須のクエリパラメータ @@ -135,9 +127,7 @@ http://127.0.0.1:8000/items/foo?short=yes しかしクエリパラメータを必須にしたい場合は、ただデフォルト値を宣言しなければよいです: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} ここで、クエリパラメータ `needy` は `str` 型の必須のクエリパラメータです @@ -181,9 +171,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy そして当然、あるパラメータを必須に、別のパラメータにデフォルト値を設定し、また別のパラメータをオプショナルにできます: -```Python hl_lines="10" -{!../../docs_src/query_params/tutorial006.py!} -``` +{* ../../docs_src/query_params/tutorial006.py hl[10] *} この場合、3つのクエリパラメータがあります。: diff --git a/docs/ja/docs/tutorial/request-forms-and-files.md b/docs/ja/docs/tutorial/request-forms-and-files.md index 1e4237b20..110e3106a 100644 --- a/docs/ja/docs/tutorial/request-forms-and-files.md +++ b/docs/ja/docs/tutorial/request-forms-and-files.md @@ -12,17 +12,13 @@ ## `File`と`Form`のインポート -```Python hl_lines="1" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[1] *} ## `File`と`Form`のパラメータの定義 ファイルやフォームのパラメータは`Body`や`Query`の場合と同じように作成します: -```Python hl_lines="8" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[8] *} ファイルとフォームフィールドがフォームデータとしてアップロードされ、ファイルとフォームフィールドを受け取ります。 diff --git a/docs/ja/docs/tutorial/request-forms.md b/docs/ja/docs/tutorial/request-forms.md index f130c067f..eca2cd6dc 100644 --- a/docs/ja/docs/tutorial/request-forms.md +++ b/docs/ja/docs/tutorial/request-forms.md @@ -14,17 +14,13 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用し `fastapi`から`Form`をインポートします: -```Python hl_lines="1" -{!../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[1] *} ## `Form`のパラメータの定義 `Body`や`Query`の場合と同じようにフォームパラメータを作成します: -```Python hl_lines="7" -{!../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[7] *} 例えば、OAuth2仕様が使用できる方法の1つ(「パスワードフロー」と呼ばれる)では、フォームフィールドとして`username`と`password`を送信する必要があります。 diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md index 97821f125..b8464a4c7 100644 --- a/docs/ja/docs/tutorial/response-model.md +++ b/docs/ja/docs/tutorial/response-model.md @@ -8,9 +8,7 @@ * `@app.delete()` * など。 -```Python hl_lines="17" -{!../../docs_src/response_model/tutorial001.py!} -``` +{* ../../docs_src/response_model/tutorial001.py hl[17] *} /// note | 備考 @@ -41,15 +39,11 @@ FastAPIは`response_model`を使って以下のことをします: ここでは`UserIn`モデルを宣言しています。それには平文のパスワードが含まれています: -```Python hl_lines="9 11" -{!../../docs_src/response_model/tutorial002.py!} -``` +{* ../../docs_src/response_model/tutorial002.py hl[9,11] *} そして、このモデルを使用して入力を宣言し、同じモデルを使って出力を宣言しています: -```Python hl_lines="17 18" -{!../../docs_src/response_model/tutorial002.py!} -``` +{* ../../docs_src/response_model/tutorial002.py hl[17,18] *} これで、ブラウザがパスワードを使ってユーザーを作成する際に、APIがレスポンスで同じパスワードを返すようになりました。 @@ -67,21 +61,15 @@ FastAPIは`response_model`を使って以下のことをします: 代わりに、平文のパスワードを持つ入力モデルと、パスワードを持たない出力モデルを作成することができます: -```Python hl_lines="9 11 16" -{!../../docs_src/response_model/tutorial003.py!} -``` +{* ../../docs_src/response_model/tutorial003.py hl[9,11,16] *} ここでは、*path operation関数*がパスワードを含む同じ入力ユーザーを返しているにもかかわらず: -```Python hl_lines="24" -{!../../docs_src/response_model/tutorial003.py!} -``` +{* ../../docs_src/response_model/tutorial003.py hl[24] *} ...`response_model`を`UserOut`と宣言したことで、パスワードが含まれていません: -```Python hl_lines="22" -{!../../docs_src/response_model/tutorial003.py!} -``` +{* ../../docs_src/response_model/tutorial003.py hl[22] *} そのため、**FastAPI** は出力モデルで宣言されていない全てのデータをフィルタリングしてくれます(Pydanticを使用)。 @@ -99,9 +87,7 @@ FastAPIは`response_model`を使って以下のことをします: レスポンスモデルにはデフォルト値を設定することができます: -```Python hl_lines="11 13 14" -{!../../docs_src/response_model/tutorial004.py!} -``` +{* ../../docs_src/response_model/tutorial004.py hl[11,13,14] *} * `description: str = None`は`None`がデフォルト値です。 * `tax: float = 10.5`は`10.5`がデフォルト値です。 @@ -115,9 +101,7 @@ FastAPIは`response_model`を使って以下のことをします: *path operation デコレータ*に`response_model_exclude_unset=True`パラメータを設定することができます: -```Python hl_lines="24" -{!../../docs_src/response_model/tutorial004.py!} -``` +{* ../../docs_src/response_model/tutorial004.py hl[24] *} そして、これらのデフォルト値はレスポンスに含まれず、実際に設定された値のみが含まれます。 @@ -205,9 +189,7 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d /// -```Python hl_lines="31 37" -{!../../docs_src/response_model/tutorial005.py!} -``` +{* ../../docs_src/response_model/tutorial005.py hl[31,37] *} /// tip | 豆知識 @@ -221,9 +203,7 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d もし`set`を使用することを忘れて、代わりに`list`や`tuple`を使用しても、FastAPIはそれを`set`に変換して正しく動作します: -```Python hl_lines="31 37" -{!../../docs_src/response_model/tutorial006.py!} -``` +{* ../../docs_src/response_model/tutorial006.py hl[31,37] *} ## まとめ diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md index 56bcdaf6c..6d197d543 100644 --- a/docs/ja/docs/tutorial/response-status-code.md +++ b/docs/ja/docs/tutorial/response-status-code.md @@ -8,9 +8,7 @@ * `@app.delete()` * など。 -```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 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス 先ほどの例をもう一度見てみましょう: -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201`は「作成完了」のためのステータスコードです。 @@ -86,9 +82,7 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス `fastapi.status`の便利な変数を利用することができます。 -```Python hl_lines="1 6" -{!../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} それらは便利です。それらは同じ番号を保持しており、その方法ではエディタの自動補完を使用してそれらを見つけることができます。 diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md index 44dfad737..1834e67b2 100644 --- a/docs/ja/docs/tutorial/schema-extra-example.md +++ b/docs/ja/docs/tutorial/schema-extra-example.md @@ -10,9 +10,7 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 Pydanticのドキュメント: スキーマのカスタマイズで説明されているように、`Config`と`schema_extra`を使ってPydanticモデルの例を宣言することができます: -```Python hl_lines="15 16 17 18 19 20 21 22 23" -{!../../docs_src/schema_extra_example/tutorial001.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial001.py hl[15,16,17,18,19,20,21,22,23] *} その追加情報はそのまま出力され、JSON Schemaに追加されます。 @@ -20,9 +18,7 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 後述する`Field`、`Path`、`Query`、`Body`などでは、任意の引数を関数に渡すことでJSON Schemaの追加情報を宣言することもできます: -```Python hl_lines="4 10 11 12 13" -{!../../docs_src/schema_extra_example/tutorial002.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial002.py hl[4,10,11,12,13] *} /// warning | 注意 @@ -36,9 +32,7 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 例えば、`Body`にボディリクエストの`example`を渡すことができます: -```Python hl_lines="21 22 23 24 25 26" -{!../../docs_src/schema_extra_example/tutorial003.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial003.py hl[21,22,23,24,25,26] *} ## ドキュメントのUIの例 diff --git a/docs/ja/docs/tutorial/security/first-steps.md b/docs/ja/docs/tutorial/security/first-steps.md index 6ace1b542..0ce0f929b 100644 --- a/docs/ja/docs/tutorial/security/first-steps.md +++ b/docs/ja/docs/tutorial/security/first-steps.md @@ -20,9 +20,7 @@ `main.py`に、下記の例をコピーします: -```Python -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py *} ## 実行 @@ -128,9 +126,7 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー `OAuth2PasswordBearer` クラスのインスタンスを作成する時に、パラメーター`tokenUrl`を渡します。このパラメーターには、クライアント (ユーザーのブラウザで動作するフロントエンド) がトークンを取得するために`ユーザー名`と`パスワード`を送信するURLを指定します。 -```Python hl_lines="6" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[6] *} /// tip | 豆知識 @@ -168,9 +164,7 @@ oauth2_scheme(some, parameters) これで`oauth2_scheme`を`Depends`で依存関係に渡すことができます。 -```Python hl_lines="10" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} この依存関係は、*path operation function*のパラメーター`token`に代入される`str`を提供します。 diff --git a/docs/ja/docs/tutorial/security/get-current-user.md b/docs/ja/docs/tutorial/security/get-current-user.md index 898bbd797..9fc46c07c 100644 --- a/docs/ja/docs/tutorial/security/get-current-user.md +++ b/docs/ja/docs/tutorial/security/get-current-user.md @@ -2,9 +2,7 @@ 一つ前の章では、(依存性注入システムに基づいた)セキュリティシステムは、 *path operation関数* に `str` として `token` を与えていました: -```Python hl_lines="10" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} しかし、それはまだそんなに有用ではありません。 @@ -16,9 +14,7 @@ ボディを宣言するのにPydanticを使用するのと同じやり方で、Pydanticを別のどんなところでも使うことができます: -```Python hl_lines="5 12-16" -{!../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[5,12:16] *} ## 依存関係 `get_current_user` を作成 @@ -30,25 +26,19 @@ 以前直接 *path operation* の中でしていたのと同じように、新しい依存関係である `get_current_user` は `str` として `token` を受け取るようになります: -```Python hl_lines="25" -{!../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[25] *} ## ユーザーの取得 `get_current_user` は作成した(偽物の)ユーティリティ関数を使って、 `str` としてトークンを受け取り、先ほどのPydanticの `User` モデルを返却します: -```Python hl_lines="19-22 26-27" -{!../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[19:22,26:27] *} ## 現在のユーザーの注入 ですので、 `get_current_user` に対して同様に *path operation* の中で `Depends` を利用できます。 -```Python hl_lines="31" -{!../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[31] *} Pydanticモデルの `User` として、 `current_user` の型を宣言することに注意してください。 @@ -103,9 +93,7 @@ Pydanticモデルの `User` として、 `current_user` の型を宣言するこ さらに、こうした何千もの *path operations* は、たった3行で表現できるのです: -```Python hl_lines="30-32" -{!../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[30:32] *} ## まとめ diff --git a/docs/ja/docs/tutorial/security/oauth2-jwt.md b/docs/ja/docs/tutorial/security/oauth2-jwt.md index 825a1b2b3..4859819cc 100644 --- a/docs/ja/docs/tutorial/security/oauth2-jwt.md +++ b/docs/ja/docs/tutorial/security/oauth2-jwt.md @@ -118,9 +118,7 @@ PassLibのcontextには、検証だけが許された非推奨の古いハッシ さらに、ユーザーを認証して返す関数も作成します。 -```Python hl_lines="7 48 55-56 59-60 69-75" -{!../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004.py hl[7,48,55:56,59:60,69:75] *} /// note | 備考 @@ -156,9 +154,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し 新しいアクセストークンを生成するユーティリティ関数を作成します。 -```Python hl_lines="6 12-14 28-30 78-86" -{!../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004.py hl[6,12:14,28:30,78:86] *} ## 依存関係の更新 @@ -168,9 +164,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し トークンが無効な場合は、すぐにHTTPエラーを返します。 -```Python hl_lines="89-106" -{!../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004.py hl[89:106] *} ## `/token` パスオペレーションの更新 @@ -178,9 +172,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し JWTアクセストークンを作成し、それを返します。 -```Python hl_lines="115-130" -{!../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004.py hl[115:130] *} ### JWTの"subject" `sub` についての技術的な詳細 diff --git a/docs/ja/docs/tutorial/static-files.md b/docs/ja/docs/tutorial/static-files.md index 37ea22dd7..f63f3f3b1 100644 --- a/docs/ja/docs/tutorial/static-files.md +++ b/docs/ja/docs/tutorial/static-files.md @@ -7,9 +7,7 @@ * `StaticFiles` をインポート。 * `StaticFiles()` インスタンスを生成し、特定のパスに「マウント」。 -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} /// note | 技術詳細 diff --git a/docs/ja/docs/tutorial/testing.md b/docs/ja/docs/tutorial/testing.md index b7e80cb8d..fe6c8c6b4 100644 --- a/docs/ja/docs/tutorial/testing.md +++ b/docs/ja/docs/tutorial/testing.md @@ -18,9 +18,7 @@ チェックしたい Python の標準的な式と共に、シンプルに `assert` 文を記述します。 -```Python hl_lines="2 12 15-18" -{!../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} /// tip | 豆知識 @@ -56,17 +54,13 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ **FastAPI** アプリに `main.py` ファイルがあるとします: -```Python -{!../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### テストファイル 次に、テストを含む `test_main.py` ファイルを作成し、`main` モジュール (`main.py`) から `app` をインポートします: -```Python -{!../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py *} ## テスト: 例の拡張 @@ -83,29 +77,13 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ これらの *path operation* には `X-Token` ヘッダーが必要です。 -//// tab | Python 3.10+ - -```Python -{!> ../../docs_src/app_testing/app_b_py310/main.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python -{!> ../../docs_src/app_testing/app_b/main.py!} -``` - -//// +{* ../../docs_src/app_testing/app_b_py310/main.py *} ### 拡張版テストファイル 次に、先程のものに拡張版のテストを加えた、`test_main_b.py` を作成します。 -```Python -{!> ../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} リクエストに情報を渡せるクライアントが必要で、その方法がわからない場合はいつでも、`httpx` での実現方法を検索 (Google) できます。 diff --git a/docs/ko/docs/advanced/advanced-dependencies.md b/docs/ko/docs/advanced/advanced-dependencies.md index aa5a332f8..7fa043fa3 100644 --- a/docs/ko/docs/advanced/advanced-dependencies.md +++ b/docs/ko/docs/advanced/advanced-dependencies.md @@ -18,35 +18,7 @@ Python에는 클래스의 인스턴스를 "호출 가능"하게 만드는 방법 이를 위해 `__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 | 참고 - -가능하다면 `Annotated` 버전을 사용하는 것이 좋습니다. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *} 이 경우, **FastAPI**는 추가 매개변수와 하위 의존성을 확인하기 위해 `__call__`을 사용하게 되며, 나중에 *경로 연산 함수*에서 매개변수에 값을 전달할 때 이를 호출하게 됩니다. @@ -55,35 +27,7 @@ Python에는 클래스의 인스턴스를 "호출 가능"하게 만드는 방법 이제 `__init__`을 사용하여 의존성을 "매개변수화"할 수 있는 인스턴스의 매개변수를 선언할 수 있습니다: -//// 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 | 참고 - -가능하다면 `Annotated` 버전을 사용하는 것이 좋습니다. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *} 이 경우, **FastAPI**는 `__init__`에 전혀 관여하지 않으며, 우리는 이 메서드를 코드에서 직접 사용하게 됩니다. @@ -91,35 +35,7 @@ Python에는 클래스의 인스턴스를 "호출 가능"하게 만드는 방법 다음과 같이 이 클래스의 인스턴스를 생성할 수 있습니다: -//// 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 | 참고 - -가능하다면 `Annotated` 버전을 사용하는 것이 좋습니다. - -/// - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *} 이렇게 하면 `checker.fixed_content` 속성에 `"bar"`라는 값을 담아 의존성을 "매개변수화"할 수 있습니다. @@ -136,35 +52,7 @@ checker(q="somequery") ...그리고 이때 반환되는 값을 *경로 연산 함수*의 `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 | 참고 - -가능하다면 `Annotated` 버전을 사용하는 것이 좋습니다. - -/// - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *} /// tip | 참고 diff --git a/docs/ko/docs/advanced/events.md b/docs/ko/docs/advanced/events.md index 273c9a479..ae349e7be 100644 --- a/docs/ko/docs/advanced/events.md +++ b/docs/ko/docs/advanced/events.md @@ -14,9 +14,7 @@ 응용 프로그램을 시작하기 전에 실행하려는 함수를 "startup" 이벤트로 선언합니다: -```Python hl_lines="8" -{!../../docs_src/events/tutorial001.py!} -``` +{* ../../docs_src/events/tutorial001.py hl[8] *} 이 경우 `startup` 이벤트 핸들러 함수는 단순히 몇 가지 값으로 구성된 `dict` 형식의 "데이터베이스"를 초기화합니다. @@ -28,9 +26,7 @@ 응용 프로그램이 종료될 때 실행하려는 함수를 추가하려면 `"shutdown"` 이벤트로 선언합니다: -```Python hl_lines="6" -{!../../docs_src/events/tutorial002.py!} -``` +{* ../../docs_src/events/tutorial002.py hl[6] *} 이 예제에서 `shutdown` 이벤트 핸들러 함수는 `"Application shutdown"`이라는 텍스트가 적힌 `log.txt` 파일을 추가할 것입니다. diff --git a/docs/ko/docs/advanced/response-change-status-code.md b/docs/ko/docs/advanced/response-change-status-code.md index f3cdd2ba5..1ba9aa3cc 100644 --- a/docs/ko/docs/advanced/response-change-status-code.md +++ b/docs/ko/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ 그리고 이 *임시* 응답 객체에서 `status_code`를 설정할 수 있습니다. -```Python hl_lines="1 9 12" -{!../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} 그리고 평소처럼 원하는 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다. diff --git a/docs/ko/docs/advanced/response-cookies.md b/docs/ko/docs/advanced/response-cookies.md index f762e94b5..327f20afe 100644 --- a/docs/ko/docs/advanced/response-cookies.md +++ b/docs/ko/docs/advanced/response-cookies.md @@ -6,9 +6,7 @@ 그런 다음 해당 *임시* 응답 객체에서 쿠키를 설정할 수 있습니다. -```Python hl_lines="1 8-9" -{!../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} 그런 다음 필요한 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다. @@ -25,9 +23,7 @@ 이를 위해 [Response를 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 설명한 대로 응답을 생성할 수 있습니다. 그런 다음 쿠키를 설정하고 반환하면 됩니다: -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} /// tip `Response` 매개변수를 사용하지 않고 응답을 직접 반환하는 경우, FastAPI는 이를 직접 반환한다는 점에 유의하세요. diff --git a/docs/ko/docs/advanced/response-directly.md b/docs/ko/docs/advanced/response-directly.md index aedebff9d..08d63c43c 100644 --- a/docs/ko/docs/advanced/response-directly.md +++ b/docs/ko/docs/advanced/response-directly.md @@ -34,9 +34,7 @@ Pydantic 모델로 데이터 변환을 수행하지 않으며, 내용을 다른 이러한 경우, 데이터를 응답에 전달하기 전에 `jsonable_encoder`를 사용하여 변환할 수 있습니다: -```Python hl_lines="6-7 21-22" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} /// note | 기술적 세부 사항 @@ -55,9 +53,7 @@ Pydantic 모델로 데이터 변환을 수행하지 않으며, 내용을 다른 XML 내용을 문자열에 넣고, 이를 `Response`에 넣어 반환할 수 있습니다: -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ## 참고 사항 `Response`를 직접 반환할 때, 그 데이터는 자동으로 유효성 검사되거나, 변환(직렬화)되거나, 문서화되지 않습니다. diff --git a/docs/ko/docs/advanced/response-headers.md b/docs/ko/docs/advanced/response-headers.md index 974a06969..e8abe0be2 100644 --- a/docs/ko/docs/advanced/response-headers.md +++ b/docs/ko/docs/advanced/response-headers.md @@ -6,9 +6,7 @@ 그런 다음, 여러분은 해당 *임시* 응답 객체에서 헤더를 설정할 수 있습니다. -```Python hl_lines="1 7-8" -{!../../docs_src/response_headers/tutorial002.py!} -``` +{* ../../docs_src/response_headers/tutorial002.py hl[1,7:8] *} 그 후, 일반적으로 사용하듯이 필요한 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다. @@ -24,9 +22,7 @@ [응답을 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 설명한 대로 응답을 생성하고, 헤더를 추가 매개변수로 전달하세요. -```Python hl_lines="10-12" -{!../../docs_src/response_headers/tutorial001.py!} -``` +{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *} /// note | 기술적 세부사항 diff --git a/docs/ko/docs/advanced/testing-events.md b/docs/ko/docs/advanced/testing-events.md index dc082412a..502762f23 100644 --- a/docs/ko/docs/advanced/testing-events.md +++ b/docs/ko/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ 테스트에서 이벤트 핸들러(`startup` 및 `shutdown`)를 실행해야 하는 경우, `with` 문과 함께 `TestClient`를 사용할 수 있습니다. -```Python hl_lines="9-12 20-24" -{!../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/ko/docs/advanced/testing-websockets.md b/docs/ko/docs/advanced/testing-websockets.md index f1580c3c3..9f3b4a451 100644 --- a/docs/ko/docs/advanced/testing-websockets.md +++ b/docs/ko/docs/advanced/testing-websockets.md @@ -4,9 +4,7 @@ 이를 위해 `with` 문에서 `TestClient`를 사용하여 WebSocket에 연결합니다: -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} /// note | 참고 diff --git a/docs/ko/docs/advanced/using-request-directly.md b/docs/ko/docs/advanced/using-request-directly.md index 027ea9fad..bfa4fa4db 100644 --- a/docs/ko/docs/advanced/using-request-directly.md +++ b/docs/ko/docs/advanced/using-request-directly.md @@ -29,9 +29,7 @@ 이를 위해서는 요청에 직접 접근해야 합니다. -```Python hl_lines="1 7-8" -{!../../docs_src/using_request_directly/tutorial001.py!} -``` +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} *경로 작동 함수* 매개변수를 `Request` 타입으로 선언하면 **FastAPI**가 해당 매개변수에 `Request` 객체를 전달하는 것을 알게 됩니다. diff --git a/docs/ko/docs/advanced/wsgi.md b/docs/ko/docs/advanced/wsgi.md index 87aabf203..3e9de3e6c 100644 --- a/docs/ko/docs/advanced/wsgi.md +++ b/docs/ko/docs/advanced/wsgi.md @@ -12,9 +12,7 @@ 그 후, 해당 경로에 마운트합니다. -```Python hl_lines="2-3 23" -{!../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,23] *} ## 확인하기 diff --git a/docs/ko/docs/python-types.md b/docs/ko/docs/python-types.md index 7cc98ba76..18d4b341e 100644 --- a/docs/ko/docs/python-types.md +++ b/docs/ko/docs/python-types.md @@ -22,9 +22,8 @@ 간단한 예제부터 시작해봅시다: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + 이 프로그램을 실행한 결과값: @@ -38,9 +37,8 @@ John Doe * `title()`로 각 첫 문자를 대문자로 변환시킵니다. * 두 단어를 중간에 공백을 두고 연결합니다. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### 코드 수정 @@ -82,9 +80,8 @@ John Doe 이게 "타입 힌트"입니다: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + 타입힌트는 다음과 같이 기본 값을 선언하는 것과는 다릅니다: @@ -112,9 +109,8 @@ John Doe 아래 함수를 보면, 이미 타입 힌트가 적용되어 있는 걸 볼 수 있습니다: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + 편집기가 변수의 타입을 알고 있기 때문에, 자동완성 뿐 아니라 에러도 확인할 수 있습니다: @@ -122,9 +118,8 @@ John Doe 이제 고쳐야하는 걸 알기 때문에, `age`를 `str(age)`과 같이 문자열로 바꾸게 됩니다: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## 타입 선언 @@ -143,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### 타입 매개변수를 활용한 Generic(제네릭) 타입 @@ -161,9 +155,8 @@ John Doe `typing`에서 `List`(대문자 `L`)를 import 합니다. -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + 콜론(`:`) 문법을 이용하여 변수를 선언합니다. @@ -171,9 +164,8 @@ John Doe 이때 배열은 내부 타입을 포함하는 타입이기 때문에 대괄호 안에 넣어줍니다. -```Python hl_lines="4" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + /// tip | 팁 @@ -199,9 +191,8 @@ John Doe `tuple`과 `set`도 동일하게 선언할 수 있습니다. -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + 이 뜻은 아래와 같습니다: @@ -216,9 +207,8 @@ John Doe 두 번째 매개변수는 `dict`의 값(value)입니다. -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + 이 뜻은 아래와 같습니다: @@ -255,15 +245,13 @@ John Doe 이름(name)을 가진 `Person` 클래스가 있다고 해봅시다. -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + 그렇게 하면 변수를 `Person`이라고 선언할 수 있게 됩니다. -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + 그리고 역시나 모든 에디터 도움을 받게 되겠죠. @@ -283,9 +271,8 @@ John Doe Pydantic 공식 문서 예시: -```Python -{!../../docs_src/python_types/tutorial011.py!} -``` +{* ../../docs_src/python_types/tutorial011.py *} + /// info | 정보 diff --git a/docs/ko/docs/tutorial/background-tasks.md b/docs/ko/docs/tutorial/background-tasks.md index 27f265608..a2c4abbd9 100644 --- a/docs/ko/docs/tutorial/background-tasks.md +++ b/docs/ko/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을 먼저 아래와 같이 `BackgroundTasks`를 임포트하고, `BackgroundTasks`를 _경로 작동 함수_ 에서 매개변수로 가져오고 정의합니다. -```Python hl_lines="1 13" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** 는 `BackgroundTasks` 개체를 생성하고, 매개 변수로 전달합니다. @@ -33,17 +31,13 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을 그리고 이 작업은 `async`와 `await`를 사용하지 않으므로 일반 `def` 함수로 선언합니다. -```Python hl_lines="6-9" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## 백그라운드 작업 추가 _경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _백그라운드 작업_ 개체에 전달합니다. -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` 함수는 다음과 같은 인자를 받습니다 : @@ -57,21 +51,7 @@ _경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _ **FastAPI**는 각 경우에 수행할 작업과 동일한 개체를 내부적으로 재사용하기에, 모든 백그라운드 작업이 함께 병합되고 나중에 백그라운드에서 실행됩니다. -//// tab | Python 3.6 and above - -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="11 13 20 23" -{!> ../../docs_src/background_tasks/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *} 이 예제에서는 응답이 반환된 후에 `log.txt` 파일에 메시지가 기록됩니다. diff --git a/docs/ko/docs/tutorial/body-fields.md b/docs/ko/docs/tutorial/body-fields.md index f6532f369..4708e7099 100644 --- a/docs/ko/docs/tutorial/body-fields.md +++ b/docs/ko/docs/tutorial/body-fields.md @@ -6,57 +6,7 @@ 먼저 이를 임포트해야 합니다: -//// tab | Python 3.10+ - -```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+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="2" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} /// warning | 경고 @@ -68,57 +18,7 @@ 그 다음 모델 어트리뷰트와 함께 `Field`를 사용할 수 있습니다: -//// 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+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="9-12" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} `Field`는 `Query`, `Path`와 `Body`와 같은 방식으로 동작하며, 모두 같은 매개변수들 등을 가집니다. diff --git a/docs/ko/docs/tutorial/body-multiple-params.md b/docs/ko/docs/tutorial/body-multiple-params.md index 569ff016e..edf892dfa 100644 --- a/docs/ko/docs/tutorial/body-multiple-params.md +++ b/docs/ko/docs/tutorial/body-multiple-params.md @@ -10,9 +10,7 @@ 또한, 기본 값을 `None`으로 설정해 본문 매개변수를 선택사항으로 선언할 수 있습니다. -```Python hl_lines="19-21" -{!../../docs_src/body_multiple_params/tutorial001.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial001.py hl[19:21] *} /// note | 참고 @@ -35,9 +33,7 @@ 하지만, 다중 본문 매개변수 역시 선언할 수 있습니다. 예. `item`과 `user`: -```Python hl_lines="22" -{!../../docs_src/body_multiple_params/tutorial002.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial002.py hl[22] *} 이 경우에, **FastAPI**는 이 함수 안에 한 개 이상의 본문 매개변수(Pydantic 모델인 두 매개변수)가 있다고 알 것입니다. @@ -79,9 +75,7 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 하지만, **FastAPI**의 `Body`를 사용해 다른 본문 키로 처리하도록 제어할 수 있습니다: -```Python hl_lines="23" -{!../../docs_src/body_multiple_params/tutorial003.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial003.py hl[23] *} 이 경우에는 **FastAPI**는 본문을 이와 같이 예측할 것입니다: @@ -110,9 +104,7 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 기본적으로 단일 값은 쿼리 매개변수로 해석되므로, 명시적으로 `Query`를 추가할 필요가 없고, 아래처럼 할 수 있습니다: -```Python hl_lines="27" -{!../../docs_src/body_multiple_params/tutorial004.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial004.py hl[27] *} 이렇게: @@ -134,9 +126,7 @@ Pydantic 모델 `Item`의 `item`을 본문 매개변수로 오직 한개만 갖 하지만, 만약 모델 내용에 `item `키를 가진 JSON으로 예측하길 원한다면, 추가적인 본문 매개변수를 선언한 것처럼 `Body`의 특별한 매개변수인 `embed`를 사용할 수 있습니다: -```Python hl_lines="17" -{!../../docs_src/body_multiple_params/tutorial005.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial005.py hl[17] *} 아래 처럼: diff --git a/docs/ko/docs/tutorial/body-nested-models.md b/docs/ko/docs/tutorial/body-nested-models.md index e9b1d2e18..ebd7b3ba6 100644 --- a/docs/ko/docs/tutorial/body-nested-models.md +++ b/docs/ko/docs/tutorial/body-nested-models.md @@ -5,9 +5,7 @@ 어트리뷰트를 서브타입으로 정의할 수 있습니다. 예를 들어 파이썬 `list`는: -```Python hl_lines="14" -{!../../docs_src/body_nested_models/tutorial001.py!} -``` +{* ../../docs_src/body_nested_models/tutorial001.py hl[14] *} 이는 `tags`를 항목 리스트로 만듭니다. 각 항목의 타입을 선언하지 않더라도요. @@ -19,9 +17,7 @@ 먼저, 파이썬 표준 `typing` 모듈에서 `List`를 임포트합니다: -```Python hl_lines="1" -{!../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### 타입 매개변수로 `List` 선언 @@ -42,9 +38,7 @@ my_list: List[str] 마찬가지로 예제에서 `tags`를 구체적으로 "문자열의 리스트"로 만들 수 있습니다: -```Python hl_lines="14" -{!../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[14] *} ## 집합 타입 @@ -54,9 +48,7 @@ my_list: List[str] 그렇다면 `Set`을 임포트 하고 `tags`를 `str`의 `set`으로 선언할 수 있습니다: -```Python hl_lines="1 14" -{!../../docs_src/body_nested_models/tutorial003.py!} -``` +{* ../../docs_src/body_nested_models/tutorial003.py hl[1,14] *} 덕분에 중복 데이터가 있는 요청을 수신하더라도 고유한 항목들의 집합으로 변환됩니다. @@ -78,17 +70,13 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 예를 들어, `Image` 모델을 선언할 수 있습니다: -```Python hl_lines="9-11" -{!../../docs_src/body_nested_models/tutorial004.py!} -``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[9:11] *} ### 서브모듈을 타입으로 사용 그리고 어트리뷰트의 타입으로 사용할 수 있습니다: -```Python hl_lines="20" -{!../../docs_src/body_nested_models/tutorial004.py!} -``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[20] *} 이는 **FastAPI**가 다음과 유사한 본문을 기대한다는 것을 의미합니다: @@ -121,9 +109,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 예를 들어 `Image` 모델 안에 `url` 필드를 `str` 대신 Pydantic의 `HttpUrl`로 선언할 수 있습니다: -```Python hl_lines="4 10" -{!../../docs_src/body_nested_models/tutorial005.py!} -``` +{* ../../docs_src/body_nested_models/tutorial005.py hl[4,10] *} 이 문자열이 유효한 URL인지 검사하고 JSON 스키마/OpenAPI로 문서화 됩니다. @@ -131,9 +117,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. `list`, `set` 등의 서브타입으로 Pydantic 모델을 사용할 수도 있습니다: -```Python hl_lines="20" -{!../../docs_src/body_nested_models/tutorial006.py!} -``` +{* ../../docs_src/body_nested_models/tutorial006.py hl[20] *} 아래와 같은 JSON 본문으로 예상(변환, 검증, 문서화 등을)합니다: @@ -171,9 +155,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 단독으로 깊게 중첩된 모델을 정의할 수 있습니다: -```Python hl_lines="9 14 20 23 27" -{!../../docs_src/body_nested_models/tutorial007.py!} -``` +{* ../../docs_src/body_nested_models/tutorial007.py hl[9,14,20,23,27] *} /// info | 정보 @@ -191,9 +173,7 @@ images: List[Image] 이를 아래처럼: -```Python hl_lines="15" -{!../../docs_src/body_nested_models/tutorial008.py!} -``` +{* ../../docs_src/body_nested_models/tutorial008.py hl[15] *} ## 어디서나 편집기 지원 @@ -223,9 +203,7 @@ Pydantic 모델 대신에 `dict`를 직접 사용하여 작업할 경우, 이러 이 경우, `float` 값을 가진 `int` 키가 있는 모든 `dict`를 받아들입니다: -```Python hl_lines="15" -{!../../docs_src/body_nested_models/tutorial009.py!} -``` +{* ../../docs_src/body_nested_models/tutorial009.py hl[15] *} /// tip | 팁 diff --git a/docs/ko/docs/tutorial/body.md b/docs/ko/docs/tutorial/body.md index 9e614ef1c..b3914fa4b 100644 --- a/docs/ko/docs/tutorial/body.md +++ b/docs/ko/docs/tutorial/body.md @@ -22,21 +22,7 @@ 먼저 `pydantic`에서 `BaseModel`를 임포트해야 합니다: -//// 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] *} ## 여러분의 데이터 모델 만들기 @@ -44,21 +30,7 @@ 모든 어트리뷰트에 대해 표준 파이썬 타입을 사용합니다: -//// tab | Python 3.10+ - -```Python hl_lines="5-9" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7-11" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *} 쿼리 매개변수를 선언할 때와 같이, 모델 어트리뷰트가 기본 값을 가지고 있어도 이는 필수가 아닙니다. 그외에는 필수입니다. 그저 `None`을 사용하여 선택적으로 만들 수 있습니다. @@ -86,21 +58,7 @@ 여러분의 *경로 작동*에 추가하기 위해, 경로 매개변수 그리고 쿼리 매개변수에서 선언했던 것과 같은 방식으로 선언하면 됩니다. -//// 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] *} ...그리고 만들어낸 모델인 `Item`으로 타입을 선언합니다. @@ -167,21 +125,7 @@ 함수 안에서 모델 객체의 모든 어트리뷰트에 직접 접근 가능합니다: -//// 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!} -``` - -//// +{* ../../docs_src/body/tutorial002_py310.py hl[19] *} ## 요청 본문 + 경로 매개변수 @@ -189,21 +133,7 @@ **FastAPI**는 경로 매개변수와 일치하는 함수 매개변수가 **경로에서 가져와야 한다**는 것을 인지하며, Pydantic 모델로 선언된 그 함수 매개변수는 **요청 본문에서 가져와야 한다**는 것을 인지할 것입니다. -//// tab | Python 3.10+ - -```Python hl_lines="15-16" -{!> ../../docs_src/body/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17-18" -{!> ../../docs_src/body/tutorial003.py!} -``` - -//// +{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *} ## 요청 본문 + 경로 + 쿼리 매개변수 @@ -211,21 +141,7 @@ **FastAPI**는 각각을 인지하고 데이터를 옳바른 위치에 가져올 것입니다. -//// 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] *} 함수 매개변수는 다음을 따라서 인지하게 됩니다: diff --git a/docs/ko/docs/tutorial/cookie-params.md b/docs/ko/docs/tutorial/cookie-params.md index 427539210..fba756d49 100644 --- a/docs/ko/docs/tutorial/cookie-params.md +++ b/docs/ko/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ 먼저 `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+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## `Cookie` 매개변수 선언 @@ -64,57 +14,7 @@ 첫 번째 값은 기본값이며, 추가 검증이나 어노테이션 매개변수 모두 전달할 수 있습니다: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} /// note | 기술 세부사항 diff --git a/docs/ko/docs/tutorial/cors.md b/docs/ko/docs/tutorial/cors.md index 0222e6258..1ef5a7480 100644 --- a/docs/ko/docs/tutorial/cors.md +++ b/docs/ko/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * 특정한 HTTP 메소드(`POST`, `PUT`) 또는 와일드카드 `"*"` 를 사용한 모든 HTTP 메소드. * 특정한 HTTP 헤더 또는 와일드카드 `"*"` 를 사용한 모든 HTTP 헤더. -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} `CORSMiddleware` 에서 사용하는 기본 매개변수는 제한적이므로, 브라우저가 교차-도메인 상황에서 특정한 출처, 메소드, 헤더 등을 사용할 수 있도록 하려면 이들을 명시적으로 허용해야 합니다. diff --git a/docs/ko/docs/tutorial/debugging.md b/docs/ko/docs/tutorial/debugging.md index fcb68b565..e42f1ba88 100644 --- a/docs/ko/docs/tutorial/debugging.md +++ b/docs/ko/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ FastAPI 애플리케이션에서 `uvicorn`을 직접 임포트하여 실행합니다 -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### `__name__ == "__main__"` 에 대하여 diff --git a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md index 41e48aefc..3e5cdcc8c 100644 --- a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,21 +6,7 @@ 이전 예제에서, 우리는 의존성(의존 가능한) 함수에서 `딕셔너리`객체를 반환하고 있었습니다: -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} 우리는 *경로 작동 함수*의 매개변수 `commons`에서 `딕셔너리` 객체를 얻습니다. @@ -81,57 +67,15 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 그래서, 우리는 위 예제에서의 `common_paramenters` 의존성을 클래스 `CommonQueryParams`로 바꿀 수 있습니다. -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="9-13" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002.py hl[11:15] *} 클래스의 인스턴스를 생성하는 데 사용되는 `__init__` 메서드에 주목하기 바랍니다: -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002.py hl[12] *} ...이전 `common_parameters`와 동일한 매개변수를 가집니다: -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="6" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} 이 매개변수들은 **FastAPI**가 의존성을 "해결"하기 위해 사용할 것입니다 @@ -147,21 +91,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 이제 아래의 클래스를 이용해서 의존성을 정의할 수 있습니다. -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002.py hl[19] *} **FastAPI**는 `CommonQueryParams` 클래스를 호출합니다. 이것은 해당 클래스의 "인스턴스"를 생성하고 그 인스턴스는 함수의 매개변수 `commons`로 전달됩니다. @@ -200,21 +130,7 @@ commons = Depends(CommonQueryParams) ..전체적인 코드는 아래와 같습니다: -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial003.py hl[19] *} 그러나 자료형을 선언하면 에디터가 매개변수 `commons`로 전달될 것이 무엇인지 알게 되고, 이를 통해 코드 완성, 자료형 확인 등에 도움이 될 수 있으므로 권장됩니다. @@ -248,21 +164,7 @@ commons: CommonQueryParams = Depends() 아래에 같은 예제가 있습니다: -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial004.py hl[19] *} ...이렇게 코드를 단축하여도 **FastAPI**는 무엇을 해야하는지 알고 있습니다. diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index fab636b7f..4a3854cef 100644 --- a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,35 +14,7 @@ `Depends()`로 된 `list`이어야합니다: -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *} 이러한 의존성들은 기존 의존성들과 같은 방식으로 실행/해결됩니다. 그러나 값은 (무엇이든 반환한다면) *경로 작동 함수*에 제공되지 않습니다. @@ -72,69 +44,13 @@ (헤더같은) 요청 요구사항이나 하위-의존성을 선언할 수 있습니다: -//// tab | Python 3.9+ - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7 12" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="6 11" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *} ### 오류 발생시키기 다음 의존성은 기존 의존성과 동일하게 예외를 `raise`를 일으킬 수 있습니다: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *} ### 값 반환하기 @@ -142,35 +58,7 @@ 그래서 이미 다른 곳에서 사용된 (값을 반환하는) 일반적인 의존성을 재사용할 수 있고, 비록 값은 사용되지 않지만 의존성은 실행될 것입니다: -//// tab | Python 3.9+ - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *} ## *경로 작동* 모음에 대한 의존성 diff --git a/docs/ko/docs/tutorial/dependencies/global-dependencies.md b/docs/ko/docs/tutorial/dependencies/global-dependencies.md index 0ad8b55fd..0d0e7684d 100644 --- a/docs/ko/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/global-dependencies.md @@ -6,35 +6,7 @@ 그런 경우에, 애플리케이션의 모든 *경로 작동*에 적용될 것입니다: -//// tab | Python 3.9+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.8 Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/dependencies/tutorial012.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[16] *} 그리고 [*경로 작동 데코레이터*에 `dependencies` 추가하기](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}에 대한 아이디어는 여전히 적용되지만 여기에서는 앱에 있는 모든 *경로 작동*에 적용됩니다. diff --git a/docs/ko/docs/tutorial/dependencies/index.md b/docs/ko/docs/tutorial/dependencies/index.md index 1aba6e787..b35a41e37 100644 --- a/docs/ko/docs/tutorial/dependencies/index.md +++ b/docs/ko/docs/tutorial/dependencies/index.md @@ -31,57 +31,7 @@ *경로 작동 함수*가 가질 수 있는 모든 매개변수를 갖는 단순한 함수입니다: -//// 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+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="8-11" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *} 이게 다입니다. @@ -113,113 +63,13 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 ### `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+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} ### "의존자"에 의존성 명시하기 *경로 작동 함수*의 매개변수로 `Body`, `Query` 등을 사용하는 방식과 같이 새로운 매개변수로 `Depends`를 사용합니다: -//// 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+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} 비록 `Body`, `Query` 등을 사용하는 것과 같은 방식으로 여러분의 함수의 매개변수에 있는 `Depends`를 사용하지만, `Depends`는 약간 다르게 작동합니다. @@ -276,29 +126,7 @@ commons: Annotated[dict, Depends(common_parameters)] 하지만 `Annotated`를 사용하고 있기에, `Annotated` 값을 변수에 저장하고 여러 장소에서 사용할 수 있습니다: -//// 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 | 팁 diff --git a/docs/ko/docs/tutorial/encoder.md b/docs/ko/docs/tutorial/encoder.md index 52277f258..4323957f4 100644 --- a/docs/ko/docs/tutorial/encoder.md +++ b/docs/ko/docs/tutorial/encoder.md @@ -20,9 +20,7 @@ JSON 호환 가능 데이터만 수신하는 `fake_db` 데이터베이스가 존 Pydantic 모델과 같은 객체를 받고 JSON 호환 가능한 버전으로 반환합니다: -```Python hl_lines="5 22" -{!../../docs_src/encoder/tutorial001.py!} -``` +{* ../../docs_src/encoder/tutorial001.py hl[5,22] *} 이 예시는 Pydantic 모델을 `dict`로, `datetime` 형식을 `str`로 변환합니다. diff --git a/docs/ko/docs/tutorial/extra-data-types.md b/docs/ko/docs/tutorial/extra-data-types.md index 8baaa64fc..4a41ba0dc 100644 --- a/docs/ko/docs/tutorial/extra-data-types.md +++ b/docs/ko/docs/tutorial/extra-data-types.md @@ -55,108 +55,8 @@ 위의 몇몇 자료형을 매개변수로 사용하는 *경로 작동* 예시입니다. -//// tab | Python 3.10+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 3 13-17" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 2 11-15" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 2 12-16" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} 함수 안의 매개변수가 그들만의 데이터 자료형을 가지고 있으며, 예를 들어, 다음과 같이 날짜를 조작할 수 있음을 참고하십시오: -//// tab | Python 3.10+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-20" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17-18" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/ko/docs/tutorial/first-steps.md b/docs/ko/docs/tutorial/first-steps.md index 4a689b74a..174f00d46 100644 --- a/docs/ko/docs/tutorial/first-steps.md +++ b/docs/ko/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ 가장 단순한 FastAPI 파일은 다음과 같이 보일 것입니다: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} 위 코드를 `main.py`에 복사합니다. @@ -133,9 +131,7 @@ API와 통신하는 클라이언트(프론트엔드, 모바일, IoT 애플리케 ### 1 단계: `FastAPI` 임포트 -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI`는 당신의 API를 위한 모든 기능을 제공하는 파이썬 클래스입니다. @@ -149,9 +145,7 @@ API와 통신하는 클라이언트(프론트엔드, 모바일, IoT 애플리케 ### 2 단계: `FastAPI` "인스턴스" 생성 -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} 여기에서 `app` 변수는 `FastAPI` 클래스의 "인스턴스"가 됩니다. @@ -171,9 +165,7 @@ $ uvicorn main:app --reload 아래처럼 앱을 만든다면: -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} 이를 `main.py` 파일에 넣고, `uvicorn`을 아래처럼 호출해야 합니다: @@ -250,9 +242,7 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 #### *경로 작동 데코레이터* 정의 -```Python hl_lines="6" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} `@app.get("/")`은 **FastAPI**에게 바로 아래에 있는 함수가 다음으로 이동하는 요청을 처리한다는 것을 알려줍니다. @@ -306,9 +296,7 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 * **작동**: 은 `get`입니다. * **함수**: 는 "데코레이터" 아래에 있는 함수입니다 (`@app.get("/")` 아래). -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} 이것은 파이썬 함수입니다. @@ -320,9 +308,7 @@ URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **Fa `async def`을 이용하는 대신 일반 함수로 정의할 수 있습니다: -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} /// note | 참고 @@ -332,9 +318,7 @@ URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **Fa ### 5 단계: 콘텐츠 반환 -```Python hl_lines="8" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} `dict`, `list`, 단일값을 가진 `str`, `int` 등을 반환할 수 있습니다. diff --git a/docs/ko/docs/tutorial/header-params.md b/docs/ko/docs/tutorial/header-params.md index 972f52a33..7379eb2a0 100644 --- a/docs/ko/docs/tutorial/header-params.md +++ b/docs/ko/docs/tutorial/header-params.md @@ -6,9 +6,7 @@ 먼저 `Header`를 임포트합니다: -```Python hl_lines="3" -{!../../docs_src/header_params/tutorial001.py!} -``` +{* ../../docs_src/header_params/tutorial001.py hl[3] *} ## `Header` 매개변수 선언 @@ -16,9 +14,7 @@ 첫 번째 값은 기본값이며, 추가 검증이나 어노테이션 매개변수 모두 전달할 수 있습니다: -```Python hl_lines="9" -{!../../docs_src/header_params/tutorial001.py!} -``` +{* ../../docs_src/header_params/tutorial001.py hl[9] *} /// note | 기술 세부사항 @@ -50,9 +46,7 @@ 만약 언더스코어를 하이픈으로 자동 변환을 비활성화해야 할 어떤 이유가 있다면, `Header`의 `convert_underscores` 매개변수를 `False`로 설정하십시오: -```Python hl_lines="10" -{!../../docs_src/header_params/tutorial002.py!} -``` +{* ../../docs_src/header_params/tutorial002.py hl[10] *} /// warning | 경고 @@ -70,9 +64,7 @@ 예를 들어, 두 번 이상 나타날 수 있는 `X-Token`헤더를 선언하려면, 다음과 같이 작성합니다: -```Python hl_lines="9" -{!../../docs_src/header_params/tutorial003.py!} -``` +{* ../../docs_src/header_params/tutorial003.py hl[9] *} 다음과 같은 두 개의 HTTP 헤더를 전송하여 해당 *경로* 와 통신할 경우: diff --git a/docs/ko/docs/tutorial/metadata.md b/docs/ko/docs/tutorial/metadata.md index 87531152c..a50dfa2e7 100644 --- a/docs/ko/docs/tutorial/metadata.md +++ b/docs/ko/docs/tutorial/metadata.md @@ -1,4 +1,3 @@ - # 메타데이터 및 문서화 URL **FastAPI** 응용 프로그램에서 다양한 메타데이터 구성을 사용자 맞춤 설정할 수 있습니다. @@ -19,9 +18,7 @@ OpenAPI 명세 및 자동화된 API 문서 UI에 사용되는 다음 필드를 다음과 같이 설정할 수 있습니다: -```Python hl_lines="3-16 19-32" -{!../../docs_src/metadata/tutorial001.py!} -``` +{* ../../docs_src/metadata/tutorial001.py hl[3:16,19:32] *} /// tip @@ -39,9 +36,7 @@ OpenAPI 3.1.0 및 FastAPI 0.99.0부터 `license_info`에 `identifier`를 URL 대 예: -```Python hl_lines="31" -{!../../docs_src/metadata/tutorial001_1.py!} -``` +{* ../../docs_src/metadata/tutorial001_1.py hl[31] *} ## 태그에 대한 메타데이터 @@ -61,9 +56,7 @@ OpenAPI 3.1.0 및 FastAPI 0.99.0부터 `license_info`에 `identifier`를 URL 대 `users` 및 `items`에 대한 태그 예시와 함께 메타데이터를 생성하고 이를 `openapi_tags` 매개변수로 전달해 보겠습니다: -```Python hl_lines="3-16 18" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} 설명 안에 마크다운을 사용할 수 있습니다. 예를 들어 "login"은 굵게(**login**) 표시되고, "fancy"는 기울임꼴(_fancy_)로 표시됩니다. @@ -77,9 +70,7 @@ OpenAPI 3.1.0 및 FastAPI 0.99.0부터 `license_info`에 `identifier`를 URL 대 `tags` 매개변수를 *경로 작동* 및 `APIRouter`와 함께 사용하여 태그에 할당할 수 있습니다: -```Python hl_lines="21 26" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} /// info @@ -107,9 +98,7 @@ OpenAPI 구조는 기본적으로 `/openapi.json`에서 제공됩니다. 예를 들어, 이를 `/api/v1/openapi.json`에 제공하도록 설정하려면: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial002.py!} -``` +{* ../../docs_src/metadata/tutorial002.py hl[3] *} OpenAPI 구조를 완전히 비활성화하려면 `openapi_url=None`으로 설정할 수 있으며, 이를 사용하여 문서화 사용자 인터페이스도 비활성화됩니다. @@ -126,6 +115,4 @@ OpenAPI 구조를 완전히 비활성화하려면 `openapi_url=None`으로 설 예를 들어, Swagger UI를 `/documentation`에서 제공하고 ReDoc을 비활성화하려면: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial003.py!} -``` +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/ko/docs/tutorial/middleware.md b/docs/ko/docs/tutorial/middleware.md index 0547066f1..3cd752a0e 100644 --- a/docs/ko/docs/tutorial/middleware.md +++ b/docs/ko/docs/tutorial/middleware.md @@ -31,9 +31,7 @@ * 그런 다음, *경로 작업*에 의해 생성된 `response` 를 반환합니다. * `response`를 반환하기 전에 추가로 `response`를 수정할 수 있습니다. -```Python hl_lines="8-9 11 14" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} /// tip | 팁 @@ -59,9 +57,7 @@ 예를 들어, 요청을 수행하고 응답을 생성하는데 까지 걸린 시간 값을 가지고 있는 `X-Process-Time` 같은 사용자 정의 헤더를 추가할 수 있습니다. -```Python hl_lines="10 12-13" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} ## 다른 미들웨어 diff --git a/docs/ko/docs/tutorial/path-operation-configuration.md b/docs/ko/docs/tutorial/path-operation-configuration.md index 75a9c71ce..81914182a 100644 --- a/docs/ko/docs/tutorial/path-operation-configuration.md +++ b/docs/ko/docs/tutorial/path-operation-configuration.md @@ -16,9 +16,7 @@ 하지만 각 코드의 의미를 모른다면, `status`에 있는 단축 상수들을 사용할수 있습니다: -```Python hl_lines="3 17" -{!../../docs_src/path_operation_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *} 각 상태 코드들은 응답에 사용되며, OpenAPI 스키마에 추가됩니다. @@ -34,9 +32,7 @@ (보통 단일 `str`인) `str`로 구성된 `list`와 함께 매개변수 `tags`를 전달하여, `경로 작동`에 태그를 추가할 수 있습니다: -```Python hl_lines="17 22 27" -{!../../docs_src/path_operation_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *} 전달된 태그들은 OpenAPI의 스키마에 추가되며, 자동 문서 인터페이스에서 사용됩니다: @@ -46,9 +42,7 @@ `summary`와 `description`을 추가할 수 있습니다: -```Python hl_lines="20-21" -{!../../docs_src/path_operation_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *} ## 독스트링으로 만든 기술 @@ -56,9 +50,7 @@ 마크다운 문법으로 독스트링을 작성할 수 있습니다, 작성된 마크다운 형식의 독스트링은 (마크다운의 들여쓰기를 고려하여) 올바르게 화면에 출력됩니다. -```Python hl_lines="19-27" -{!../../docs_src/path_operation_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *} 이는 대화형 문서에서 사용됩니다: @@ -68,9 +60,7 @@ `response_description` 매개변수로 응답에 관한 설명을 명시할 수 있습니다: -```Python hl_lines="21" -{!../../docs_src/path_operation_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial005.py hl[21] *} /// info | 정보 @@ -92,9 +82,7 @@ OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 단일 *경로 작동*을 없애지 않고 지원중단을 해야한다면, `deprecated` 매개변수를 전달하면 됩니다. -```Python hl_lines="16" -{!../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} 대화형 문서에 지원중단이라고 표시됩니다. diff --git a/docs/ko/docs/tutorial/path-params-numeric-validations.md b/docs/ko/docs/tutorial/path-params-numeric-validations.md index 736f2dc1d..f21c9290e 100644 --- a/docs/ko/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ko/docs/tutorial/path-params-numeric-validations.md @@ -6,9 +6,7 @@ 먼저 `fastapi`에서 `Path`를 임포트합니다: -```Python hl_lines="3" -{!../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[3] *} ## 메타데이터 선언 @@ -16,9 +14,7 @@ 예를 들어, `title` 메타데이터 값을 경로 매개변수 `item_id`에 선언하려면 다음과 같이 입력할 수 있습니다: -```Python hl_lines="10" -{!../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[10] *} /// note | 참고 @@ -46,9 +42,7 @@ 따라서 함수를 다음과 같이 선언 할 수 있습니다: -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} ## 필요한 경우 매개변수 정렬하기, 트릭 @@ -58,9 +52,7 @@ 파이썬은 `*`으로 아무런 행동도 하지 않지만, 따르는 매개변수들은 kwargs로도 알려진 키워드 인자(키-값 쌍)여야 함을 인지합니다. 기본값을 가지고 있지 않더라도 그렇습니다. -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ## 숫자 검증: 크거나 같음 @@ -68,9 +60,7 @@ 여기서 `ge=1`인 경우, `item_id`는 `1`보다 "크거나(`g`reater) 같은(`e`qual)" 정수형 숫자여야 합니다. -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *} ## 숫자 검증: 크거나 같음 및 작거나 같음 @@ -79,9 +69,7 @@ * `gt`: 크거나(`g`reater `t`han) * `le`: 작거나 같은(`l`ess than or `e`qual) -```Python hl_lines="9" -{!../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *} ## 숫자 검증: 부동소수, 크거나 및 작거나 @@ -93,9 +81,7 @@ lt 역시 마찬가지입니다. -```Python hl_lines="11" -{!../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *} ## 요약 diff --git a/docs/ko/docs/tutorial/path-params.md b/docs/ko/docs/tutorial/path-params.md index 21808e2ca..b72787e0b 100644 --- a/docs/ko/docs/tutorial/path-params.md +++ b/docs/ko/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ 파이썬의 포맷 문자열 리터럴에서 사용되는 문법을 이용하여 경로 "매개변수" 또는 "변수"를 선언할 수 있습니다: -```Python hl_lines="6-7" -{!../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} 경로 매개변수 `item_id`의 값은 함수의 `item_id` 인자로 전달됩니다. @@ -18,9 +16,7 @@ 파이썬 표준 타입 어노테이션을 사용하여 함수에 있는 경로 매개변수의 타입을 선언할 수 있습니다: -```Python hl_lines="7" -{!../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} 위의 예시에서, `item_id`는 `int`로 선언되었습니다. @@ -121,9 +117,7 @@ *경로 작동*은 순차적으로 실행되기 때문에 `/users/{user_id}` 이전에 `/users/me`를 먼저 선언해야 합니다: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} 그렇지 않으면 `/users/{user_id}`는 `/users/me` 요청 또한 매개변수 `user_id`의 값이 `"me"`인 것으로 "생각하게" 됩니다. @@ -139,9 +133,7 @@ 가능한 값들에 해당하는 고정된 값의 클래스 어트리뷰트들을 만듭니다: -```Python hl_lines="1 6-9" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} /// info | 정보 @@ -159,9 +151,7 @@ 생성한 열거형 클래스(`ModelName`)를 사용하는 타입 어노테이션으로 *경로 매개변수*를 만듭니다: -```Python hl_lines="16" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### 문서 확인 @@ -177,17 +167,13 @@ 열거형 `ModelName`의 *열거형 멤버*를 비교할 수 있습니다: -```Python hl_lines="17" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### *열거형 값* 가져오기 `model_name.value` 또는 일반적으로 `your_enum_member.value`를 이용하여 실제 값(위 예시의 경우 `str`)을 가져올 수 있습니다: -```Python hl_lines="20" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} /// tip | 팁 @@ -201,9 +187,7 @@ 클라이언트에 반환하기 전에 해당 값(이 경우 문자열)으로 변환됩니다: -```Python hl_lines="18 21 23" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} 클라이언트는 아래의 JSON 응답을 얻습니다: @@ -242,9 +226,7 @@ Starlette의 옵션을 직접 이용하여 다음과 같은 URL을 사용함으 따라서 다음과 같이 사용할 수 있습니다: -```Python hl_lines="6" -{!../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} /// tip | 팁 diff --git a/docs/ko/docs/tutorial/query-params-str-validations.md b/docs/ko/docs/tutorial/query-params-str-validations.md index 71f884e83..f2ca453ac 100644 --- a/docs/ko/docs/tutorial/query-params-str-validations.md +++ b/docs/ko/docs/tutorial/query-params-str-validations.md @@ -4,9 +4,7 @@ 이 응용 프로그램을 예로 들어보겠습니다: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial001.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *} 쿼리 매개변수 `q`는 `Optional[str]` 자료형입니다. 즉, `str` 자료형이지만 `None` 역시 될 수 있음을 뜻하고, 실제로 기본값은 `None`이기 때문에 FastAPI는 이 매개변수가 필수가 아니라는 것을 압니다. @@ -26,17 +24,13 @@ FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압 이를 위해 먼저 `fastapi`에서 `Query`를 임포트합니다: -```Python hl_lines="3" -{!../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *} ## 기본값으로 `Query` 사용 이제 `Query`를 매개변수의 기본값으로 사용하여 `max_length` 매개변수를 50으로 설정합니다: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} 기본값 `None`을 `Query(None)`으로 바꿔야 하므로, `Query`의 첫 번째 매개변수는 기본값을 정의하는 것과 같은 목적으로 사용됩니다. @@ -86,17 +80,13 @@ q: str = Query(None, max_length=50) 매개변수 `min_length` 또한 추가할 수 있습니다: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial003.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[9] *} ## 정규식 추가 매개변수와 일치해야 하는 정규표현식을 정의할 수 있습니다: -```Python hl_lines="10" -{!../../docs_src/query_params_str_validations/tutorial004.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[10] *} 이 특정 정규표현식은 전달 받은 매개변수 값을 검사합니다: @@ -114,9 +104,7 @@ q: str = Query(None, max_length=50) `min_length`가 `3`이고, 기본값이 `"fixedquery"`인 쿼리 매개변수 `q`를 선언해봅시다: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial005.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} /// note | 참고 @@ -146,9 +134,7 @@ q: Optional[str] = Query(None, min_length=3) 그래서 `Query`를 필수값으로 만들어야 할 때면, 첫 번째 인자로 `...`를 사용할 수 있습니다: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial006.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} /// info | 정보 @@ -164,9 +150,7 @@ q: Optional[str] = Query(None, min_length=3) 예를 들어, URL에서 여러번 나오는 `q` 쿼리 매개변수를 선언하려면 다음과 같이 작성할 수 있습니다: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial011.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} 아래와 같은 URL을 사용합니다: @@ -201,9 +185,7 @@ http://localhost:8000/items/?q=foo&q=bar 그리고 제공된 값이 없으면 기본 `list` 값을 정의할 수도 있습니다: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial012.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} 아래로 이동한다면: @@ -226,9 +208,7 @@ http://localhost:8000/items/ `List[str]` 대신 `list`를 직접 사용할 수도 있습니다: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} /// note | 참고 @@ -254,15 +234,11 @@ http://localhost:8000/items/ `title`을 추가할 수 있습니다: -```Python hl_lines="10" -{!../../docs_src/query_params_str_validations/tutorial007.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *} 그리고 `description`도 추가할 수 있습니다: -```Python hl_lines="13" -{!../../docs_src/query_params_str_validations/tutorial008.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## 별칭 매개변수 @@ -282,9 +258,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 이럴 경우 `alias`를 선언할 수 있으며, 해당 별칭은 매개변수 값을 찾는 데 사용됩니다: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial009.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} ## 매개변수 사용하지 않게 하기 @@ -294,9 +268,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 그렇다면 `deprecated=True` 매개변수를 `Query`로 전달합니다: -```Python hl_lines="18" -{!../../docs_src/query_params_str_validations/tutorial010.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} 문서가 아래와 같이 보일겁니다: diff --git a/docs/ko/docs/tutorial/query-params.md b/docs/ko/docs/tutorial/query-params.md index 7fa3e8c53..d5b9837c4 100644 --- a/docs/ko/docs/tutorial/query-params.md +++ b/docs/ko/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ 경로 매개변수의 일부가 아닌 다른 함수 매개변수를 선언하면 "쿼리" 매개변수로 자동 해석합니다. -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} 쿼리는 URL에서 `?` 후에 나오고 `&`으로 구분되는 키-값 쌍의 집합입니다. @@ -63,9 +61,7 @@ http://127.0.0.1:8000/items/?skip=20 같은 방법으로 기본값을 `None`으로 설정하여 선택적 매개변수를 선언할 수 있습니다: -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial002.py!} -``` +{* ../../docs_src/query_params/tutorial002.py hl[9] *} 이 경우 함수 매개변수 `q`는 선택적이며 기본값으로 `None` 값이 됩니다. @@ -87,9 +83,7 @@ FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다. `bool` 형으로 선언할 수도 있고, 아래처럼 변환됩니다: -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial003.py!} -``` +{* ../../docs_src/query_params/tutorial003.py hl[9] *} 이 경우, 아래로 이동하면: @@ -132,9 +126,7 @@ http://127.0.0.1:8000/items/foo?short=yes 매개변수들은 이름으로 감지됩니다: -```Python hl_lines="8 10" -{!../../docs_src/query_params/tutorial004.py!} -``` +{* ../../docs_src/query_params/tutorial004.py hl[8,10] *} ## 필수 쿼리 매개변수 @@ -144,9 +136,7 @@ http://127.0.0.1:8000/items/foo?short=yes 그러나 쿼리 매개변수를 필수로 만들려면 단순히 기본값을 선언하지 않으면 됩니다: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} 여기 쿼리 매개변수 `needy`는 `str`형인 필수 쿼리 매개변수입니다. @@ -190,9 +180,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy 그리고 물론, 일부 매개변수는 필수로, 다른 일부는 기본값을, 또 다른 일부는 선택적으로 선언할 수 있습니다: -```Python hl_lines="10" -{!../../docs_src/query_params/tutorial006.py!} -``` +{* ../../docs_src/query_params/tutorial006.py hl[10] *} 위 예시에서는 3가지 쿼리 매개변수가 있습니다: diff --git a/docs/ko/docs/tutorial/request-files.md b/docs/ko/docs/tutorial/request-files.md index ca0f43978..9162b353c 100644 --- a/docs/ko/docs/tutorial/request-files.md +++ b/docs/ko/docs/tutorial/request-files.md @@ -16,17 +16,13 @@ `fastapi` 에서 `File` 과 `UploadFile` 을 임포트 합니다: -```Python hl_lines="1" -{!../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[1] *} ## `File` 매개변수 정의 `Body` 및 `Form` 과 동일한 방식으로 파일의 매개변수를 생성합니다: -```Python hl_lines="7" -{!../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[7] *} /// info | 정보 @@ -54,9 +50,7 @@ File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본 `File` 매개변수를 `UploadFile` 타입으로 정의합니다: -```Python hl_lines="12" -{!../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[12] *} `UploadFile` 을 사용하는 것은 `bytes` 과 비교해 다음과 같은 장점이 있습니다: @@ -142,9 +136,7 @@ HTML의 폼들(`
`)이 서버에 데이터를 전송하는 방식은 이 기능을 사용하기 위해 , `bytes` 의 `List` 또는 `UploadFile` 를 선언하기 바랍니다: -```Python hl_lines="10 15" -{!../../docs_src/request_files/tutorial002.py!} -``` +{* ../../docs_src/request_files/tutorial002.py hl[10,15] *} 선언한대로, `bytes` 의 `list` 또는 `UploadFile` 들을 전송받을 것입니다. diff --git a/docs/ko/docs/tutorial/request-forms-and-files.md b/docs/ko/docs/tutorial/request-forms-and-files.md index 75bca9f15..dc1bda21a 100644 --- a/docs/ko/docs/tutorial/request-forms-and-files.md +++ b/docs/ko/docs/tutorial/request-forms-and-files.md @@ -12,17 +12,13 @@ ## `File` 및 `Form` 업로드 -```Python hl_lines="1" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[1] *} ## `File` 및 `Form` 매개변수 정의 `Body` 및 `Query`와 동일한 방식으로 파일과 폼의 매개변수를 생성합니다: -```Python hl_lines="8" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[8] *} 파일과 폼 필드는 폼 데이터 형식으로 업로드되어 파일과 폼 필드로 전달됩니다. diff --git a/docs/ko/docs/tutorial/response-model.md b/docs/ko/docs/tutorial/response-model.md index 6ba9654d6..a71d649f9 100644 --- a/docs/ko/docs/tutorial/response-model.md +++ b/docs/ko/docs/tutorial/response-model.md @@ -8,9 +8,7 @@ * `@app.delete()` * 기타. -```Python hl_lines="17" -{!../../docs_src/response_model/tutorial001.py!} -``` +{* ../../docs_src/response_model/tutorial001.py hl[17] *} /// note | 참고 @@ -41,15 +39,11 @@ FastAPI는 이 `response_model`를 사용하여: 여기서 우리는 평문 비밀번호를 포함하는 `UserIn` 모델을 선언합니다: -```Python hl_lines="9 11" -{!../../docs_src/response_model/tutorial002.py!} -``` +{* ../../docs_src/response_model/tutorial002.py hl[9,11] *} 그리고 이 모델을 사용하여 입력을 선언하고 같은 모델로 출력을 선언합니다: -```Python hl_lines="17-18" -{!../../docs_src/response_model/tutorial002.py!} -``` +{* ../../docs_src/response_model/tutorial002.py hl[17:18] *} 이제 브라우저가 비밀번호로 사용자를 만들 때마다 API는 응답으로 동일한 비밀번호를 반환합니다. @@ -67,21 +61,15 @@ FastAPI는 이 `response_model`를 사용하여: 대신 평문 비밀번호로 입력 모델을 만들고 해당 비밀번호 없이 출력 모델을 만들 수 있습니다: -```Python hl_lines="9 11 16" -{!../../docs_src/response_model/tutorial003.py!} -``` +{* ../../docs_src/response_model/tutorial003.py hl[9,11,16] *} 여기서 *경로 작동 함수*가 비밀번호를 포함하는 동일한 입력 사용자를 반환할지라도: -```Python hl_lines="24" -{!../../docs_src/response_model/tutorial003.py!} -``` +{* ../../docs_src/response_model/tutorial003.py hl[24] *} ...`response_model`을 `UserOut` 모델로 선언했기 때문에 비밀번호를 포함하지 않습니다: -```Python hl_lines="22" -{!../../docs_src/response_model/tutorial003.py!} -``` +{* ../../docs_src/response_model/tutorial003.py hl[22] *} 따라서 **FastAPI**는 출력 모델에서 선언하지 않은 모든 데이터를 (Pydantic을 사용하여) 필터링합니다. @@ -99,9 +87,7 @@ FastAPI는 이 `response_model`를 사용하여: 응답 모델은 아래와 같이 기본값을 가질 수 있습니다: -```Python hl_lines="11 13-14" -{!../../docs_src/response_model/tutorial004.py!} -``` +{* ../../docs_src/response_model/tutorial004.py hl[11,13:14] *} * `description: Optional[str] = None`은 기본값으로 `None`을 갖습니다. * `tax: float = 10.5`는 기본값으로 `10.5`를 갖습니다. @@ -115,9 +101,7 @@ FastAPI는 이 `response_model`를 사용하여: *경로 작동 데코레이터* 매개변수를 `response_model_exclude_unset=True`로 설정 할 수 있습니다: -```Python hl_lines="24" -{!../../docs_src/response_model/tutorial004.py!} -``` +{* ../../docs_src/response_model/tutorial004.py hl[24] *} 이러한 기본값은 응답에 포함되지 않고 실제로 설정된 값만 포함됩니다. @@ -207,9 +191,7 @@ Pydantic 모델이 하나만 있고 출력에서 ​​일부 데이터를 제 /// -```Python hl_lines="31 37" -{!../../docs_src/response_model/tutorial005.py!} -``` +{* ../../docs_src/response_model/tutorial005.py hl[31,37] *} /// tip | 팁 @@ -223,9 +205,7 @@ Pydantic 모델이 하나만 있고 출력에서 ​​일부 데이터를 제 `list` 또는 `tuple` 대신 `set`을 사용하는 법을 잊었더라도, FastAPI는 `set`으로 변환하고 정상적으로 작동합니다: -```Python hl_lines="31 37" -{!../../docs_src/response_model/tutorial006.py!} -``` +{* ../../docs_src/response_model/tutorial006.py hl[31,37] *} ## 요약 diff --git a/docs/ko/docs/tutorial/response-status-code.md b/docs/ko/docs/tutorial/response-status-code.md index 8e3a16645..bcaf7843b 100644 --- a/docs/ko/docs/tutorial/response-status-code.md +++ b/docs/ko/docs/tutorial/response-status-code.md @@ -8,9 +8,7 @@ * `@app.delete()` * 기타 -```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 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 상기 예시 참고: -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201` 은 "생성됨"를 의미하는 상태 코드입니다. @@ -86,9 +82,7 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 `fastapi.status` 의 편의 변수를 사용할 수 있습니다. -```Python hl_lines="1 6" -{!../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} 이것은 단순히 작업을 편리하게 하기 위한 것으로, HTTP 상태 코드와 동일한 번호를 갖고있지만, 이를 사용하면 편집기의 자동완성 기능을 사용할 수 있습니다: diff --git a/docs/ko/docs/tutorial/security/get-current-user.md b/docs/ko/docs/tutorial/security/get-current-user.md index cf550735a..98ef3885e 100644 --- a/docs/ko/docs/tutorial/security/get-current-user.md +++ b/docs/ko/docs/tutorial/security/get-current-user.md @@ -2,9 +2,7 @@ 이전 장에서 (의존성 주입 시스템을 기반으로 한)보안 시스템은 *경로 작동 함수*에서 `str`로 `token`을 제공했습니다: -```Python hl_lines="10" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} 그러나 아직도 유용하지 않습니다. @@ -16,21 +14,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다른 곳에서 사용할 수 있습니다. -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="3 10-14" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[5,12:16] *} ## `get_current_user` 의존성 생성하기 @@ -42,61 +26,19 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 이전에 *경로 작동*에서 직접 수행했던 것과 동일하게 새 종속성 `get_current_user`는 하위 종속성 `oauth2_scheme`에서 `str`로 `token`을 수신합니다. -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="23" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[25] *} ## 유저 가져오기 `get_current_user`는 토큰을 `str`로 취하고 Pydantic `User` 모델을 반환하는 우리가 만든 (가짜) 유틸리티 함수를 사용합니다. -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="17-20 24-25" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[19:22,26:27] *} ## 현재 유저 주입하기 이제 *경로 작동*에서 `get_current_user`와 동일한 `Depends`를 사용할 수 있습니다. -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="29" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[31] *} Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알아야 합니다. @@ -150,21 +92,7 @@ Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알 그리고 이 수천 개의 *경로 작동*은 모두 3줄 정도로 줄일 수 있습니다. -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="28-30" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[30:32] *} ## 요약 diff --git a/docs/ko/docs/tutorial/security/simple-oauth2.md b/docs/ko/docs/tutorial/security/simple-oauth2.md index fd18c1d47..ddc7430af 100644 --- a/docs/ko/docs/tutorial/security/simple-oauth2.md +++ b/docs/ko/docs/tutorial/security/simple-oauth2.md @@ -52,21 +52,7 @@ OAuth2의 경우 문자열일 뿐입니다. 먼저 `OAuth2PasswordRequestForm`을 가져와 `/token`에 대한 *경로 작동*에서 `Depends`의 의존성으로 사용합니다. -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="4 76" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="2 74" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[4,76] *} `OAuth2PasswordRequestForm`은 다음을 사용하여 폼 본문을 선언하는 클래스 의존성입니다: @@ -114,21 +100,7 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 오류의 경우 `HTTPException` 예외를 사용합니다: -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="3 77-79" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="1 75-77" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[3,77:79] *} ### 패스워드 확인하기 @@ -156,19 +128,11 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` //// tab | P파이썬 3.7 이상 -```Python hl_lines="80-83" -{!> ../../docs_src/security/tutorial003.py!} -``` +{* ../../docs_src/security/tutorial003.py hl[80:83] *} //// -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="78-81" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_py310.py hl[78:81] *} #### `**user_dict`에 대해 @@ -210,21 +174,7 @@ UserInDB( /// -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="85" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="83" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[85] *} /// 팁 @@ -250,21 +200,7 @@ UserInDB( 따라서 엔드포인트에서는 사용자가 존재하고 올바르게 인증되었으며 활성 상태인 경우에만 사용자를 얻습니다: -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="58-66 69-72 90" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="55-64 67-70 88" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[58:66,69:72,90] *} /// 정보 diff --git a/docs/ko/docs/tutorial/static-files.md b/docs/ko/docs/tutorial/static-files.md index af785f206..9db5e1c67 100644 --- a/docs/ko/docs/tutorial/static-files.md +++ b/docs/ko/docs/tutorial/static-files.md @@ -7,9 +7,7 @@ * `StaticFiles` 임포트합니다. * 특정 경로에 `StaticFiles()` 인스턴스를 "마운트" 합니다. -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} /// note | 기술적 세부사항 diff --git a/docs/nl/docs/python-types.md b/docs/nl/docs/python-types.md index 00052037c..fb8b1e5fd 100644 --- a/docs/nl/docs/python-types.md +++ b/docs/nl/docs/python-types.md @@ -22,9 +22,8 @@ Als je een Python expert bent en alles al weet over type hints, sla dan dit hoof Laten we beginnen met een eenvoudig voorbeeld: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Het aanroepen van dit programma leidt tot het volgende resultaat: @@ -39,9 +38,8 @@ De functie voert het volgende uit: `` * Voeg samen met een spatie in het midden. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Bewerk het @@ -83,9 +81,8 @@ Dat is alles. Dat zijn de "type hints": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Dit is niet hetzelfde als het declareren van standaardwaarden zoals bij: @@ -113,9 +110,8 @@ Nu kun je de opties bekijken en er doorheen scrollen totdat je de optie vindt di Bekijk deze functie, deze heeft al type hints: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Omdat de editor de types van de variabelen kent, krijgt u niet alleen aanvulling, maar ook controles op fouten: @@ -123,9 +119,8 @@ Omdat de editor de types van de variabelen kent, krijgt u niet alleen aanvulling Nu weet je hoe je het moet oplossen, converteer `age` naar een string met `str(age)`: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Types declareren @@ -144,9 +139,8 @@ Je kunt bijvoorbeeld het volgende gebruiken: * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Generieke types met typeparameters @@ -370,9 +364,8 @@ Het gaat alleen om de woorden en naamgeving. Maar die naamgeving kan invloed heb Laten we als voorbeeld deze functie nemen: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c.py!} -``` +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} + De parameter `name` is gedefinieerd als `Optional[str]`, maar is **niet optioneel**, je kunt de functie niet aanroepen zonder de parameter: @@ -388,9 +381,8 @@ say_hi(name=None) # Dit werkt, None is geldig 🎉 Het goede nieuws is dat als je eenmaal Python 3.10 gebruikt, je je daar geen zorgen meer over hoeft te maken, omdat je dan gewoon `|` kunt gebruiken om unions van types te definiëren: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c_py310.py!} -``` +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} + Dan hoef je je geen zorgen te maken over namen als `Optional` en `Union`. 😎 @@ -452,15 +444,13 @@ Je kunt een klasse ook declareren als het type van een variabele. Stel dat je een klasse `Person` hebt, met een naam: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Vervolgens kun je een variabele van het type `Persoon` declareren: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + Dan krijg je ook nog eens volledige editorondersteuning: diff --git a/docs/pt/docs/advanced/additional-responses.md b/docs/pt/docs/advanced/additional-responses.md index 58e75ad93..1060d18af 100644 --- a/docs/pt/docs/advanced/additional-responses.md +++ b/docs/pt/docs/advanced/additional-responses.md @@ -26,9 +26,7 @@ O **FastAPI** pegará este modelo, gerará o esquema JSON dele e incluirá no lo Por exemplo, para declarar um outro retorno com o status code `404` e um modelo do Pydantic chamado `Message`, você pode escrever: -```Python hl_lines="18 22" -{!../../docs_src/additional_responses/tutorial001.py!} -``` +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} /// note | Nota @@ -177,9 +175,7 @@ Você pode utilizar o mesmo parâmetro `responses` para adicionar diferentes med Por exemplo, você pode adicionar um media type adicional de `image/png`, declarando que a sua *operação de caminho* pode retornar um objeto JSON (com o media type `application/json`) ou uma imagem PNG: -```Python hl_lines="19-24 28" -{!../../docs_src/additional_responses/tutorial002.py!} -``` +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} /// note | Nota @@ -207,9 +203,7 @@ Por exemplo, você pode declarar um retorno com o código de status `404` que ut E um retorno com o código de status `200` que utiliza o seu `response_model`, porém inclui um `example` customizado: -```Python hl_lines="20-31" -{!../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} Isso será combinado e incluído em seu OpenAPI, e disponibilizado na documentação da sua API: @@ -243,9 +237,7 @@ Você pode utilizar essa técnica para reutilizar alguns retornos predefinidos n Por exemplo: -```Python hl_lines="13-17 26" -{!../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## Mais informações sobre retornos OpenAPI diff --git a/docs/pt/docs/advanced/additional-status-codes.md b/docs/pt/docs/advanced/additional-status-codes.md index 5fe970d2a..06d619151 100644 --- a/docs/pt/docs/advanced/additional-status-codes.md +++ b/docs/pt/docs/advanced/additional-status-codes.md @@ -14,57 +14,7 @@ Mas você também deseja aceitar novos itens. E quando os itens não existiam, e Para conseguir isso, importe `JSONResponse` e retorne o seu conteúdo diretamente, definindo o `status_code` que você deseja: -//// 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 | Dica - -Faça uso da versão `Annotated` quando possível. - -/// - -```Python hl_lines="2 23" -{!> ../../docs_src/additional_status_codes/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Faça uso da versão `Annotated` quando possível. - -/// - -```Python hl_lines="4 25" -{!> ../../docs_src/additional_status_codes/tutorial001.py!} -``` - -//// +{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *} /// warning | Aviso diff --git a/docs/pt/docs/advanced/advanced-dependencies.md b/docs/pt/docs/advanced/advanced-dependencies.md index 52fe121f9..f57abba61 100644 --- a/docs/pt/docs/advanced/advanced-dependencies.md +++ b/docs/pt/docs/advanced/advanced-dependencies.md @@ -18,35 +18,7 @@ Não propriamente a classe (que já é um chamável), mas a instância desta cla Para fazer isso, nós declaramos o método `__call__`: -//// 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 | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *} Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâmetros adicionais e sub dependências, e isso é o que será chamado para passar o valor ao parâmetro na sua *função de operação de rota* posteriormente. @@ -54,35 +26,7 @@ Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâm E agora, nós podemos utilizar o `__init__` para declarar os parâmetros da instância que podemos utilizar para "parametrizar" a dependência: -//// 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 | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *} Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós vamos utilizar diretamente em nosso código. @@ -90,35 +34,7 @@ Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós Nós poderíamos criar uma instância desta classe com: -//// 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 | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *} E deste modo nós podemos "parametrizar" a nossa dependência, que agora possui `"bar"` dentro dele, como o atributo `checker.fixed_content`. @@ -134,35 +50,7 @@ checker(q="somequery") ...e passar o que quer que isso retorne como valor da dependência em nossa *função de operação de rota* como o parâmetro `fixed_content_included`: -//// 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 | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *} /// tip | Dica diff --git a/docs/pt/docs/advanced/async-tests.md b/docs/pt/docs/advanced/async-tests.md index 8fae97298..a2b79426c 100644 --- a/docs/pt/docs/advanced/async-tests.md +++ b/docs/pt/docs/advanced/async-tests.md @@ -32,15 +32,11 @@ Para um exemplos simples, vamos considerar uma estrutura de arquivos semelhante O arquivo `main.py` teria: -```Python -{!../../docs_src/async_tests/main.py!} -``` +{* ../../docs_src/async_tests/main.py *} O arquivo `test_main.py` teria os testes para para o arquivo `main.py`, ele poderia ficar assim: -```Python -{!../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py *} ## Executá-lo @@ -60,9 +56,7 @@ $ pytest O marcador `@pytest.mark.anyio` informa ao pytest que esta função de teste deve ser invocada de maneira assíncrona: -```Python hl_lines="7" -{!../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py hl[7] *} /// tip | Dica @@ -72,9 +66,7 @@ Note que a função de teste é `async def` agora, no lugar de apenas `def` como Então podemos criar um `AsyncClient` com a aplicação, e enviar requisições assíncronas para ela utilizando `await`. -```Python hl_lines="9-12" -{!../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} Isso é equivalente a: diff --git a/docs/pt/docs/advanced/custom-response.md b/docs/pt/docs/advanced/custom-response.md index 5f673d7ce..a0bcc2b97 100644 --- a/docs/pt/docs/advanced/custom-response.md +++ b/docs/pt/docs/advanced/custom-response.md @@ -30,9 +30,7 @@ Isso ocorre por que, por padrão, o FastAPI irá verificar cada item dentro do d Mas se você tem certeza que o conteúdo que você está retornando é **serializável com JSON**, você pode passá-lo diretamente para a classe de resposta e evitar o trabalho extra que o FastAPI teria ao passar o conteúdo pelo `jsonable_encoder` antes de passar para a classe de resposta. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} /// info | Informação @@ -57,9 +55,7 @@ Para retornar uma resposta com HTML diretamente do **FastAPI**, utilize `HTMLRes * Importe `HTMLResponse` * Passe `HTMLResponse` como o parâmetro de `response_class` do seu *decorador de operação de rota*. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial002.py!} -``` +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} /// info | Informação @@ -77,9 +73,7 @@ Como visto em [Retornando uma Resposta Diretamente](response-directly.md){.inter O mesmo exemplo de antes, retornando uma `HTMLResponse`, poderia parecer com: -```Python hl_lines="2 7 19" -{!../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} /// warning | Aviso @@ -103,9 +97,7 @@ A `response_class` será usada apenas para documentar o OpenAPI da *operação d Por exemplo, poderia ser algo como: -```Python hl_lines="7 21 23" -{!../../docs_src/custom_response/tutorial004.py!} -``` +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} Neste exemplo, a função `generate_html_response()` já cria e retorna uma `Response` em vez de retornar o HTML em uma `str`. @@ -144,9 +136,7 @@ Ela aceita os seguintes parâmetros: O FastAPI (Starlette, na verdade) irá incluir o cabeçalho Content-Length automaticamente. Ele também irá incluir o cabeçalho Content-Type, baseado no `media_type` e acrescentando uma codificação para tipos textuais. -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ### `HTMLResponse` @@ -156,9 +146,7 @@ Usa algum texto ou sequência de bytes e retorna uma resposta HTML. Como você l Usa algum texto ou sequência de bytes para retornar uma resposta de texto não formatado. -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial005.py!} -``` +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} ### `JSONResponse` @@ -192,9 +180,7 @@ Essa resposta requer a instalação do pacote `ujson`, com o comando `pip instal /// -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001.py!} -``` +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} /// tip | Dica @@ -208,17 +194,13 @@ Retorna um redirecionamento HTTP. Utiliza o código de status 307 (Redirecioname Você pode retornar uma `RedirectResponse` diretamente: -```Python hl_lines="2 9" -{!../../docs_src/custom_response/tutorial006.py!} -``` +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} --- Ou você pode utilizá-la no parâmetro `response_class`: -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial006b.py!} -``` +{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *} Se você fizer isso, então você pode retornar a URL diretamente da sua *função de operação de rota* @@ -228,17 +210,13 @@ Neste caso, o `status_code` utilizada será o padrão de `RedirectResponse`, que Você também pode utilizar o parâmetro `status_code` combinado com o parâmetro `response_class`: -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial006c.py!} -``` +{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *} ### `StreamingResponse` Recebe uma gerador assíncrono ou um gerador/iterador comum e retorna o corpo da requisição continuamente (stream). -```Python hl_lines="2 14" -{!../../docs_src/custom_response/tutorial007.py!} -``` +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} #### Utilizando `StreamingResponse` com objetos semelhantes a arquivos @@ -279,15 +257,11 @@ Recebe um conjunto de argumentos do construtor diferente dos outros tipos de res Respostas de Arquivos incluem o tamanho do arquivo, data da última modificação e ETags apropriados, nos cabeçalhos `Content-Length`, `Last-Modified` e `ETag`, respectivamente. -```Python hl_lines="2 10" -{!../../docs_src/custom_response/tutorial009.py!} -``` +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} Você também pode usar o parâmetro `response_class`: -```Python hl_lines="2 8 10" -{!../../docs_src/custom_response/tutorial009b.py!} -``` +{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *} Nesse caso, você pode retornar o caminho do arquivo diretamente da sua *função de operação de rota*. @@ -301,9 +275,7 @@ Vamos supor também que você queira retornar um JSON indentado e formatado, ent Você poderia criar uma classe `CustomORJSONResponse`. A principal coisa a ser feita é sobrecarregar o método render da classe Response, `Response.render(content)`, que retorna o conteúdo em bytes, para retornar o conteúdo que você deseja: -```Python hl_lines="9-14 17" -{!../../docs_src/custom_response/tutorial009c.py!} -``` +{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *} Agora em vez de retornar: @@ -329,9 +301,7 @@ O padrão que define isso é o `default_response_class`. No exemplo abaixo, o **FastAPI** irá utilizar `ORJSONResponse` por padrão, em todas as *operações de rota*, em vez de `JSONResponse`. -```Python hl_lines="2 4" -{!../../docs_src/custom_response/tutorial010.py!} -``` +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} /// tip | Dica diff --git a/docs/pt/docs/advanced/dataclasses.md b/docs/pt/docs/advanced/dataclasses.md index af603ada7..600c8c268 100644 --- a/docs/pt/docs/advanced/dataclasses.md +++ b/docs/pt/docs/advanced/dataclasses.md @@ -4,9 +4,7 @@ FastAPI é construído em cima do **Pydantic**, e eu tenho mostrado como usar mo Mas o FastAPI também suporta o uso de `dataclasses` da mesma forma: -```Python hl_lines="1 7-12 19-20" -{!../../docs_src/dataclasses/tutorial001.py!} -``` +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} Isso ainda é suportado graças ao **Pydantic**, pois ele tem suporte interno para `dataclasses`. @@ -34,9 +32,7 @@ Mas se você tem um monte de dataclasses por aí, este é um truque legal para u Você também pode usar `dataclasses` no parâmetro `response_model`: -```Python hl_lines="1 7-13 19" -{!../../docs_src/dataclasses/tutorial002.py!} -``` +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} A dataclass será automaticamente convertida para uma dataclass Pydantic. diff --git a/docs/pt/docs/advanced/events.md b/docs/pt/docs/advanced/events.md index 783dbfc83..504b6db57 100644 --- a/docs/pt/docs/advanced/events.md +++ b/docs/pt/docs/advanced/events.md @@ -31,9 +31,7 @@ Vamos iniciar com um exemplo e ver isso detalhadamente. Nós criamos uma função assíncrona chamada `lifespan()` com `yield` como este: -```Python hl_lines="16 19" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[16,19] *} Aqui nós estamos simulando a *inicialização* custosa do carregamento do modelo colocando a (falsa) função de modelo no dicionário com modelos de _machine learning_ antes do `yield`. Este código será executado **antes** da aplicação **começar a receber requisições**, durante a *inicialização*. @@ -51,9 +49,7 @@ Talvez você precise inicializar uma nova versão, ou apenas cansou de executá- A primeira coisa a notar, é que estamos definindo uma função assíncrona com `yield`. Isso é muito semelhante à Dependências com `yield`. -```Python hl_lines="14-19" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[14:19] *} A primeira parte da função, antes do `yield`, será executada **antes** da aplicação inicializar. @@ -65,9 +61,7 @@ Se você verificar, a função está decorada com um `@asynccontextmanager`. Que converte a função em algo chamado de "**Gerenciador de Contexto Assíncrono**". -```Python hl_lines="1 13" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[1,13] *} Um **gerenciador de contexto** em Python é algo que você pode usar em uma declaração `with`, por exemplo, `open()` pode ser usado como um gerenciador de contexto: @@ -89,9 +83,7 @@ No nosso exemplo de código acima, nós não usamos ele diretamente, mas nós pa O parâmetro `lifespan` da aplicação `FastAPI` usa um **Gerenciador de Contexto Assíncrono**, então nós podemos passar nosso novo gerenciador de contexto assíncrono do `lifespan` para ele. -```Python hl_lines="22" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[22] *} ## Eventos alternativos (deprecados) @@ -113,9 +105,7 @@ Essas funções podem ser declaradas com `async def` ou `def` normal. Para adicionar uma função que deve rodar antes da aplicação iniciar, declare-a com o evento `"startup"`: -```Python hl_lines="8" -{!../../docs_src/events/tutorial001.py!} -``` +{* ../../docs_src/events/tutorial001.py hl[8] *} Nesse caso, a função de manipulação de evento `startup` irá inicializar os itens do "banco de dados" (só um `dict`) com alguns valores. @@ -127,9 +117,7 @@ E sua aplicação não irá começar a receber requisições até que todos os m Para adicionar uma função que deve ser executada quando a aplicação estiver encerrando, declare ela com o evento `"shutdown"`: -```Python hl_lines="6" -{!../../docs_src/events/tutorial002.py!} -``` +{* ../../docs_src/events/tutorial002.py hl[6] *} Aqui, a função de manipulação de evento `shutdown` irá escrever uma linha de texto `"Application shutdown"` no arquivo `log.txt`. diff --git a/docs/pt/docs/advanced/openapi-callbacks.md b/docs/pt/docs/advanced/openapi-callbacks.md index c66ababa0..b0659d3d6 100644 --- a/docs/pt/docs/advanced/openapi-callbacks.md +++ b/docs/pt/docs/advanced/openapi-callbacks.md @@ -31,9 +31,7 @@ Ele terá uma *operação de rota* que receberá um corpo `Invoice`, e um parâm Essa parte é bastante normal, a maior parte do código provavelmente já é familiar para você: -```Python hl_lines="9-13 36-53" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *} /// tip | Dica @@ -92,9 +90,7 @@ Adotar temporariamente esse ponto de vista (do *desenvolvedor externo*) pode aju Primeiramente crie um novo `APIRouter` que conterá um ou mais callbacks. -```Python hl_lines="3 25" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *} ### Crie a *operação de rota* do callback @@ -105,9 +101,7 @@ Ele deve parecer exatamente como uma *operação de rota* normal do FastAPI: * Ele provavelmente deveria ter uma declaração do corpo que deveria receber, por exemplo. `body: InvoiceEvent`. * E também deveria ter uma declaração de um código de status de resposta, por exemplo. `response_model=InvoiceEventReceived`. -```Python hl_lines="16-18 21-22 28-32" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *} Há 2 diferenças principais de uma *operação de rota* normal: @@ -175,9 +169,7 @@ Nesse ponto você tem a(s) *operação de rota de callback* necessária(s) (a(s) Agora use o parâmetro `callbacks` no decorador da *operação de rota de sua API* para passar o atributo `.routes` (que é na verdade apenas uma `list` de rotas/*operações de rota*) do roteador de callback que você criou acima: -```Python hl_lines="35" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *} /// tip | Dica diff --git a/docs/pt/docs/advanced/openapi-webhooks.md b/docs/pt/docs/advanced/openapi-webhooks.md index 344fe6371..f35922234 100644 --- a/docs/pt/docs/advanced/openapi-webhooks.md +++ b/docs/pt/docs/advanced/openapi-webhooks.md @@ -32,9 +32,7 @@ Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do Fast Quando você cria uma aplicação com o **FastAPI**, existe um atributo chamado `webhooks`, que você utilizar para defini-los da mesma maneira que você definiria as suas **operações de rotas**, utilizando por exemplo `@app.webhooks.post()`. -```Python hl_lines="9-13 36-53" -{!../../docs_src/openapi_webhooks/tutorial001.py!} -``` +{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *} Os webhooks que você define aparecerão no esquema do **OpenAPI** e na **página de documentação** gerada automaticamente. diff --git a/docs/pt/docs/advanced/path-operation-advanced-configuration.md b/docs/pt/docs/advanced/path-operation-advanced-configuration.md index 04f5cc9a3..411d0f9a7 100644 --- a/docs/pt/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/pt/docs/advanced/path-operation-advanced-configuration.md @@ -155,17 +155,13 @@ Por exemplo, nesta aplicação nós não usamos a funcionalidade integrada ao Fa //// tab | Pydantic v2 -```Python hl_lines="17-22 24" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *} //// //// tab | Pydantic v1 -```Python hl_lines="17-22 24" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[17:22,24] *} //// @@ -183,17 +179,13 @@ E então no nosso código, nós analisamos o conteúdo YAML diretamente, e estam //// tab | Pydantic v2 -```Python hl_lines="26-33" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} //// //// tab | Pydantic v1 -```Python hl_lines="26-33" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[26:33] *} //// diff --git a/docs/pt/docs/advanced/response-change-status-code.md b/docs/pt/docs/advanced/response-change-status-code.md index 2ac5eca18..358c12d54 100644 --- a/docs/pt/docs/advanced/response-change-status-code.md +++ b/docs/pt/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ Você pode declarar um parâmetro do tipo `Response` em sua *função de operaç E então você pode definir o `status_code` neste objeto de retorno temporal. -```Python hl_lines="1 9 12" -{!../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} E então você pode retornar qualquer objeto que você precise, como você faria normalmente (um `dict`, um modelo de banco de dados, etc.). diff --git a/docs/pt/docs/advanced/response-cookies.md b/docs/pt/docs/advanced/response-cookies.md index cd8f39db3..eed69f222 100644 --- a/docs/pt/docs/advanced/response-cookies.md +++ b/docs/pt/docs/advanced/response-cookies.md @@ -6,9 +6,7 @@ Você pode declarar um parâmetro do tipo `Response` na sua *função de operaç E então você pode definir cookies nesse objeto de resposta *temporário*. -```Python hl_lines="1 8-9" -{!../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} Em seguida, você pode retornar qualquer objeto que precise, como normalmente faria (um `dict`, um modelo de banco de dados, etc). @@ -26,9 +24,7 @@ Para fazer isso, você pode criar uma resposta como descrito em [Retornando uma Então, defina os cookies nela e a retorne: -```Python hl_lines="10-12" -{!../../docs_src/response_cookies/tutorial001.py!} -``` +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} /// tip | Dica diff --git a/docs/pt/docs/advanced/response-directly.md b/docs/pt/docs/advanced/response-directly.md index fd2a0eef1..ea717be00 100644 --- a/docs/pt/docs/advanced/response-directly.md +++ b/docs/pt/docs/advanced/response-directly.md @@ -34,9 +34,7 @@ Por exemplo, você não pode colocar um modelo do Pydantic em uma `JSONResponse` Para esses casos, você pode usar o `jsonable_encoder` para converter seus dados antes de repassá-los para a resposta: -```Python hl_lines="6-7 21-22" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} /// note | Detalhes Técnicos @@ -56,9 +54,7 @@ Vamos dizer quer retornar uma resposta ../../docs_src/security/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="2 7 11" -{!> ../../docs_src/security/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="2 6 10" -{!> ../../docs_src/security/tutorial006.py!} -``` - -//// +{* ../../docs_src/security/tutorial006_an_py39.py hl[4,8,12] *} Quando você tentar abrir a URL pela primeira vez (ou clicar no botão "Executar" nos documentos) o navegador vai pedir pelo seu usuário e senha: @@ -68,35 +40,7 @@ Para lidar com isso, primeiramente nós convertemos o `username` e o `password` Então nós podemos utilizar o `secrets.compare_digest()` para garantir que o `credentials.username` é `"stanleyjobson"`, e que o `credentials.password` é `"swordfish"`. -//// tab | Python 3.9+ - -```Python hl_lines="1 12-24" -{!> ../../docs_src/security/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 12-24" -{!> ../../docs_src/security/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="1 11-21" -{!> ../../docs_src/security/tutorial007.py!} -``` - -//// +{* ../../docs_src/security/tutorial007_an_py39.py hl[1,12:24] *} Isso seria parecido com: @@ -161,32 +105,4 @@ Deste modo, ao utilizar `secrets.compare_digest()` no código de sua aplicação Após detectar que as credenciais estão incorretas, retorne um `HTTPException` com o status 401 (o mesmo retornado quando nenhuma credencial foi informada) e adicione o cabeçalho `WWW-Authenticate` para fazer com que o navegador mostre o prompt de login novamente: -//// tab | Python 3.9+ - -```Python hl_lines="26-30" -{!> ../../docs_src/security/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="26-30" -{!> ../../docs_src/security/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="23-27" -{!> ../../docs_src/security/tutorial007.py!} -``` - -//// +{* ../../docs_src/security/tutorial007_an_py39.py hl[26:30] *} diff --git a/docs/pt/docs/advanced/security/oauth2-scopes.md b/docs/pt/docs/advanced/security/oauth2-scopes.md index 49fb75944..1d53f42d8 100644 --- a/docs/pt/docs/advanced/security/oauth2-scopes.md +++ b/docs/pt/docs/advanced/security/oauth2-scopes.md @@ -62,71 +62,7 @@ Para o OAuth2, eles são apenas strings. Primeiro, vamos olhar rapidamente as partes que mudam dos exemplos do **Tutorial - Guia de Usuário** para [OAuth2 com Senha (e hash), Bearer com tokens JWT](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Agora utilizando escopos OAuth2: -//// tab | Python 3.10+ - -```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:125,129:135,140,156] *} Agora vamos revisar essas mudanças passo a passo. @@ -136,71 +72,7 @@ A primeira mudança é que agora nós estamos declarando o esquema de segurança O parâmetro `scopes` recebe um `dict` contendo cada escopo como chave e a descrição como valor: -//// tab | Python 3.10+ - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="64-67" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="62-65" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *} Pelo motivo de estarmos declarando estes escopos, eles aparecerão nos documentos da API quando você se autenticar/autorizar. @@ -226,71 +98,7 @@ Porém em sua aplicação, por segurança, você deve garantir que você apenas /// -//// tab | Python 3.10+ - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="157" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="155" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[156] *} ## Declare escopos em *operações de rota* e dependências @@ -316,71 +124,7 @@ Nós estamos fazendo isso aqui para demonstrar como o **FastAPI** lida com escop /// -//// tab | Python 3.10+ - -```Python hl_lines="5 140 171" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="5 140 171" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 141 172" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="4 139 168" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="5 140 169" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="5 140 169" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[5,140,171] *} /// info | Informações Técnicas @@ -406,71 +150,7 @@ Nós também declaramos um parâmetro especial do tipo `SecurityScopes`, importa A classe `SecurityScopes` é semelhante à classe `Request` (`Request` foi utilizada para obter o objeto da requisição diretamente). -//// tab | Python 3.10+ - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 107" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="8 105" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *} ## Utilize os `scopes` @@ -484,71 +164,7 @@ Nós criamos uma `HTTPException` que nós podemos reutilizar (`raise`) mais tard Nesta exceção, nós incluímos os escopos necessários (se houver algum) como uma string separada por espaços (utilizando `scope_str`). Nós colocamos esta string contendo os escopos no cabeçalho `WWW-Authenticate` (isso é parte da especificação). -//// tab | Python 3.10+ - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="107 109-117" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="105 107-115" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *} ## Verifique o `username` e o formato dos dados @@ -564,71 +180,7 @@ No lugar de, por exemplo, um `dict`, ou alguma outra coisa, que poderia quebrar Nós também verificamos que nós temos um usuário com o "*username*", e caso contrário, nós levantamos a mesma exceção que criamos anteriormente. -//// tab | Python 3.10+ - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="48 118-129" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="46 116-127" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:128] *} ## Verifique os `scopes` @@ -636,71 +188,7 @@ Nós verificamos agora que todos os escopos necessários, por essa dependência Para isso, nós utilizamos `security_scopes.scopes`, que contém uma `list` com todos esses escopos como uma `str`. -//// tab | Python 3.10+ - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="130-136" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="128-134" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[129:135] *} ## Árvore de dependência e escopos diff --git a/docs/pt/docs/advanced/settings.md b/docs/pt/docs/advanced/settings.md index d32b70ed4..00a39b0af 100644 --- a/docs/pt/docs/advanced/settings.md +++ b/docs/pt/docs/advanced/settings.md @@ -180,9 +180,7 @@ Você pode utilizar todas as ferramentas e funcionalidades de validação que s //// tab | Pydantic v2 -```Python hl_lines="2 5-8 11" -{!> ../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} //// @@ -194,9 +192,7 @@ Na versão 1 do Pydantic você importaria `BaseSettings` diretamente do módulo /// -```Python hl_lines="2 5-8 11" -{!> ../../docs_src/settings/tutorial001_pv1.py!} -``` +{* ../../docs_src/settings/tutorial001_pv1.py hl[2,5:8,11] *} //// @@ -214,9 +210,7 @@ Depois ele irá converter e validar os dados. Assim, quando você utilizar aquel Depois, Você pode utilizar o novo objeto `settings` na sua aplicação: -```Python hl_lines="18-20" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} ### Executando o servidor @@ -250,15 +244,11 @@ Você também pode incluir essas configurações em um arquivo de um módulo sep Por exemplo, você pode adicionar um arquivo `config.py` com: -```Python -{!../../docs_src/settings/app01/config.py!} -``` +{* ../../docs_src/settings/app01/config.py *} E utilizar essa configuração em `main.py`: -```Python hl_lines="3 11-13" -{!../../docs_src/settings/app01/main.py!} -``` +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} /// dica @@ -276,9 +266,7 @@ Isso é especialmente útil durante os testes, já que é bastante simples sobre Baseando-se no exemplo anterior, seu arquivo `config.py` seria parecido com isso: -```Python hl_lines="10" -{!../../docs_src/settings/app02/config.py!} -``` +{* ../../docs_src/settings/app02/config.py hl[10] *} Perceba que dessa vez não criamos uma instância padrão `settings = Settings()`. @@ -286,35 +274,7 @@ Perceba que dessa vez não criamos uma instância padrão `settings = Settings() Agora criamos a dependência que retorna um novo objeto `config.Settings()`. -//// tab | Python 3.9+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="5 11-12" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *} /// dica @@ -326,43 +286,13 @@ Por enquanto, você pode considerar `get_settings()` como uma função normal. E então podemos declarar essas configurações como uma dependência na função de operação da rota e utilizar onde for necessário. -//// tab | Python 3.9+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="16 18-20" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *} ### Configurações e testes Então seria muito fácil fornecer uma configuração diferente durante a execução dos testes sobrescrevendo a dependência de `get_settings`: -```Python hl_lines="9-10 13 21" -{!../../docs_src/settings/app02/test_main.py!} -``` +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} Na sobrescrita da dependência, definimos um novo valor para `admin_email` quando instanciamos um novo objeto `Settings`, e então retornamos esse novo objeto. @@ -405,9 +335,7 @@ E então adicionar o seguinte código em `config.py`: //// tab | Pydantic v2 -```Python hl_lines="9" -{!> ../../docs_src/settings/app03_an/config.py!} -``` +{* ../../docs_src/settings/app03_an/config.py hl[9] *} /// dica @@ -419,9 +347,7 @@ O atributo `model_config` é usado apenas para configuração do Pydantic. Você //// tab | Pydantic v1 -```Python hl_lines="9-10" -{!> ../../docs_src/settings/app03_an/config_pv1.py!} -``` +{* ../../docs_src/settings/app03_an/config_pv1.py hl[9:10] *} /// dica @@ -462,35 +388,7 @@ Iriamos criar um novo objeto a cada requisição, e estaríamos lendo o arquivo Mas como estamos utilizando o decorador `@lru_cache` acima, o objeto `Settings` é criado apenas uma vez, na primeira vez que a função é chamada. ✔️ -//// tab | Python 3.9+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="1 10" -{!> ../../docs_src/settings/app03/main.py!} -``` - -//// +{* ../../docs_src/settings/app03_an_py39/main.py hl[1,11] *} Dessa forma, todas as chamadas da função `get_settings()` nas dependências das próximas requisições, em vez de executar o código interno de `get_settings()` e instanciar um novo objeto `Settings`, irão retornar o mesmo objeto que foi retornado na primeira chamada, de novo e de novo. diff --git a/docs/pt/docs/advanced/sub-applications.md b/docs/pt/docs/advanced/sub-applications.md index 7f0381cc2..efc6bef64 100644 --- a/docs/pt/docs/advanced/sub-applications.md +++ b/docs/pt/docs/advanced/sub-applications.md @@ -10,9 +10,7 @@ Se você precisar ter duas aplicações FastAPI independentes, cada uma com seu Primeiro, crie a aplicação principal, de nível superior, **FastAPI**, e suas *operações de rota*: -```Python hl_lines="3 6-8" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[3,6:8] *} ### Sub-aplicação @@ -20,9 +18,7 @@ Em seguida, crie sua sub-aplicação e suas *operações de rota*. Essa sub-aplicação é apenas outra aplicação FastAPI padrão, mas esta é a que será "montada": -```Python hl_lines="11 14-16" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,14:16] *} ### Monte a sub-aplicação @@ -30,9 +26,7 @@ Na sua aplicação de nível superior, `app`, monte a sub-aplicação, `subapi`. Neste caso, ela será montada no caminho `/subapi`: -```Python hl_lines="11 19" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,19] *} ### Verifique a documentação automática da API diff --git a/docs/pt/docs/advanced/templates.md b/docs/pt/docs/advanced/templates.md index 2314fed91..4d22bfbbf 100644 --- a/docs/pt/docs/advanced/templates.md +++ b/docs/pt/docs/advanced/templates.md @@ -25,9 +25,7 @@ $ pip install jinja2 * Declare um parâmetro `Request` no *path operation* que retornará um template. * Use o `template` que você criou para renderizar e retornar uma `TemplateResponse`, passe o nome do template, o request object, e um "context" dict com pares chave-valor a serem usados dentro do template do Jinja2. -```Python hl_lines="4 11 15-18" -{!../../docs_src/templates/tutorial001.py!} -``` +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *} /// note diff --git a/docs/pt/docs/advanced/testing-dependencies.md b/docs/pt/docs/advanced/testing-dependencies.md index 94594e7e9..3ede4741d 100644 --- a/docs/pt/docs/advanced/testing-dependencies.md +++ b/docs/pt/docs/advanced/testing-dependencies.md @@ -28,57 +28,7 @@ Para sobrepor a dependência para os testes, você coloca como chave a dependên E então o **FastAPI** chamará a sobreposição no lugar da dependência original. -//// tab | Python 3.10+ - -```Python hl_lines="26-27 30" -{!> ../../docs_src/dependency_testing/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="28-29 32" -{!> ../../docs_src/dependency_testing/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="29-30 33" -{!> ../../docs_src/dependency_testing/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="24-25 28" -{!> ../../docs_src/dependency_testing/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="28-29 32" -{!> ../../docs_src/dependency_testing/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependency_testing/tutorial001_an_py310.py hl[26:27,30] *} /// tip | Dica diff --git a/docs/pt/docs/advanced/testing-events.md b/docs/pt/docs/advanced/testing-events.md index b6796e835..6113c9913 100644 --- a/docs/pt/docs/advanced/testing-events.md +++ b/docs/pt/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ Quando você precisa que os seus manipuladores de eventos (`startup` e `shutdown`) sejam executados em seus testes, você pode utilizar o `TestClient` usando a instrução `with`: -```Python hl_lines="9-12 20-24" -{!../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/pt/docs/advanced/testing-websockets.md b/docs/pt/docs/advanced/testing-websockets.md index 99e1a6db4..942771bc9 100644 --- a/docs/pt/docs/advanced/testing-websockets.md +++ b/docs/pt/docs/advanced/testing-websockets.md @@ -4,9 +4,7 @@ Você pode usar o mesmo `TestClient` para testar WebSockets. Para isso, você utiliza o `TestClient` dentro de uma instrução `with`, conectando com o WebSocket: -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} /// note | Nota diff --git a/docs/pt/docs/advanced/using-request-directly.md b/docs/pt/docs/advanced/using-request-directly.md index df7e01833..f31e2ed15 100644 --- a/docs/pt/docs/advanced/using-request-directly.md +++ b/docs/pt/docs/advanced/using-request-directly.md @@ -29,9 +29,7 @@ Vamos imaginar que você deseja obter o endereço de IP/host do cliente dentro d Para isso você precisa acessar a requisição diretamente. -```Python hl_lines="1 7-8" -{!../../docs_src/using_request_directly/tutorial001.py!} -``` +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} Ao declarar o parâmetro com o tipo sendo um `Request` em sua *função de operação de rota*, o **FastAPI** saberá como passar o `Request` neste parâmetro. diff --git a/docs/pt/docs/advanced/websockets.md b/docs/pt/docs/advanced/websockets.md index 694f2bb5d..82e443886 100644 --- a/docs/pt/docs/advanced/websockets.md +++ b/docs/pt/docs/advanced/websockets.md @@ -38,9 +38,7 @@ Na produção, você teria uma das opções acima. Mas é a maneira mais simples de focar no lado do servidor de WebSockets e ter um exemplo funcional: -```Python hl_lines="2 6-38 41-43" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} ## Criando um `websocket` diff --git a/docs/pt/docs/how-to/conditional-openapi.md b/docs/pt/docs/how-to/conditional-openapi.md index 675b812e6..6b44e9c81 100644 --- a/docs/pt/docs/how-to/conditional-openapi.md +++ b/docs/pt/docs/how-to/conditional-openapi.md @@ -29,9 +29,7 @@ Você pode usar facilmente as mesmas configurações do Pydantic para configurar Por exemplo: -```Python hl_lines="6 11" -{!../../docs_src/conditional_openapi/tutorial001.py!} -``` +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} Aqui declaramos a configuração `openapi_url` com o mesmo padrão de `"/openapi.json"`. diff --git a/docs/pt/docs/how-to/configure-swagger-ui.md b/docs/pt/docs/how-to/configure-swagger-ui.md index 58bb1557c..915b2b5c5 100644 --- a/docs/pt/docs/how-to/configure-swagger-ui.md +++ b/docs/pt/docs/how-to/configure-swagger-ui.md @@ -18,9 +18,7 @@ Sem alterar as configurações, o destaque de sintaxe é habilitado por padrão: Mas você pode desabilitá-lo definindo `syntaxHighlight` como `False`: -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial001.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *} ...e então o Swagger UI não mostrará mais o destaque de sintaxe: @@ -30,9 +28,7 @@ Mas você pode desabilitá-lo definindo `syntaxHighlight` como `False`: Da mesma forma que você pode definir o tema de destaque de sintaxe com a chave `"syntaxHighlight.theme"` (observe que há um ponto no meio): -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial002.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *} Essa configuração alteraria o tema de cores de destaque de sintaxe: @@ -44,17 +40,13 @@ O FastAPI inclui alguns parâmetros de configuração padrão apropriados para a Inclui estas configurações padrão: -```Python -{!../../fastapi/openapi/docs.py[ln:7-23]!} -``` +{* ../../fastapi/openapi/docs.py ln[7:23] *} Você pode substituir qualquer um deles definindo um valor diferente no argumento `swagger_ui_parameters`. Por exemplo, para desabilitar `deepLinking` você pode passar essas configurações para `swagger_ui_parameters`: -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial003.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *} ## Outros parâmetros da UI do Swagger diff --git a/docs/pt/docs/how-to/custom-docs-ui-assets.md b/docs/pt/docs/how-to/custom-docs-ui-assets.md index 00dd144c9..3adc7529e 100644 --- a/docs/pt/docs/how-to/custom-docs-ui-assets.md +++ b/docs/pt/docs/how-to/custom-docs-ui-assets.md @@ -18,9 +18,7 @@ O primeiro passo é desativar a documentação automática, pois por padrão, el Para desativá-los, defina suas URLs como `None` ao criar seu aplicativo `FastAPI`: -```Python hl_lines="8" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} ### Incluir a documentação personalizada @@ -36,9 +34,7 @@ Você pode reutilizar as funções internas do FastAPI para criar as páginas HT E de forma semelhante para o 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 | Dica @@ -54,9 +50,7 @@ Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse aux Agora, para poder testar se tudo funciona, crie uma *operação de rota*: -```Python hl_lines="36-38" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} ### Teste @@ -124,9 +118,7 @@ Depois disso, sua estrutura de arquivos deve se parecer com: * Importe `StaticFiles`. * "Monte" a instância `StaticFiles()` em um caminho específico. -```Python hl_lines="7 11" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} ### Teste os arquivos estáticos @@ -158,9 +150,7 @@ Da mesma forma que ao usar um CDN personalizado, o primeiro passo é desativar a Para desativá-los, defina suas URLs como `None` ao criar seu aplicativo `FastAPI`: -```Python hl_lines="9" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} ### Incluir a documentação personalizada para arquivos estáticos @@ -176,9 +166,7 @@ Novamente, você pode reutilizar as funções internas do FastAPI para criar as E de forma semelhante para o 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 | Dica @@ -194,9 +182,7 @@ Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse aux Agora, para poder testar se tudo funciona, crie uma *operação de rota*: -```Python hl_lines="39-41" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} ### Teste a UI de Arquivos Estáticos diff --git a/docs/pt/docs/how-to/custom-request-and-route.md b/docs/pt/docs/how-to/custom-request-and-route.md index 64325eed9..8f432f6fe 100644 --- a/docs/pt/docs/how-to/custom-request-and-route.md +++ b/docs/pt/docs/how-to/custom-request-and-route.md @@ -42,9 +42,7 @@ Se não houver `gzip` no cabeçalho, ele não tentará descomprimir o corpo. Dessa forma, a mesma classe de rota pode lidar com requisições comprimidas ou não comprimidas. -```Python hl_lines="8-15" -{!../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[8:15] *} ### Criar uma classe `GzipRoute` personalizada @@ -56,9 +54,7 @@ Esse método retorna uma função. E essa função é o que irá receber uma req Aqui nós usamos para criar um `GzipRequest` a partir da requisição original. -```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 | Detalhes Técnicos @@ -96,26 +92,18 @@ Também podemos usar essa mesma abordagem para acessar o corpo da requisição e Tudo que precisamos fazer é manipular a requisição dentro de um bloco `try`/`except`: -```Python hl_lines="13 15" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[13,15] *} Se uma exceção ocorrer, a instância `Request` ainda estará em escopo, então podemos ler e fazer uso do corpo da requisição ao lidar com o erro: -```Python hl_lines="16-18" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[16:18] *} ## Classe `APIRoute` personalizada em um router você também pode definir o parametro `route_class` de uma `APIRouter`; -```Python hl_lines="26" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[26] *} Nesse exemplo, as *operações de rota* sob o `router` irão usar a classe `TimedRoute` personalizada, e terão um cabeçalho extra `X-Response-Time` na resposta com o tempo que levou para gerar a resposta: -```Python hl_lines="13-20" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[13:20] *} diff --git a/docs/pt/docs/how-to/extending-openapi.md b/docs/pt/docs/how-to/extending-openapi.md index 40917325b..b4785edc1 100644 --- a/docs/pt/docs/how-to/extending-openapi.md +++ b/docs/pt/docs/how-to/extending-openapi.md @@ -1,4 +1,3 @@ - # Extendendo o OpenAPI Existem alguns casos em que pode ser necessário modificar o esquema OpenAPI gerado. @@ -44,25 +43,19 @@ Por exemplo, vamos adicionar documentação do Strawberry. diff --git a/docs/pt/docs/how-to/separate-openapi-schemas.md b/docs/pt/docs/how-to/separate-openapi-schemas.md index 50d321d4c..291b0e163 100644 --- a/docs/pt/docs/how-to/separate-openapi-schemas.md +++ b/docs/pt/docs/how-to/separate-openapi-schemas.md @@ -10,123 +10,13 @@ Vamos ver como isso funciona e como alterar se for necessário. Digamos que você tenha um modelo Pydantic com valores padrão, como este: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} - -# Code below omitted 👇 -``` - -
-👀 Visualização completa do arquivo - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -
- -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} - -# Code below omitted 👇 -``` - -
-👀 Visualização completa do arquivo - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -
- -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} - -# Code below omitted 👇 -``` - -
-👀 Visualização completa do arquivo - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -
- -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *} ### Modelo para Entrada Se você usar esse modelo como entrada, como aqui: -//// tab | Python 3.10+ - -```Python hl_lines="14" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} - -# Code below omitted 👇 -``` - -
-👀 Visualização completa do arquivo - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -
- -//// - -//// tab | Python 3.9+ - -```Python hl_lines="16" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} - -# Code below omitted 👇 -``` - -
-👀 Visualização completa do arquivo - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -
- -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} - -# Code below omitted 👇 -``` - -
-👀 Visualização completa do arquivo - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -
- -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *} ... então o campo `description` não será obrigatório. Porque ele tem um valor padrão de `None`. @@ -142,29 +32,7 @@ Você pode confirmar que na documentação, o campo `description` não tem um ** Mas se você usar o mesmo modelo como saída, como aqui: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="21" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py hl[19] *} ... então, como `description` tem um valor padrão, se você **não retornar nada** para esse campo, ele ainda terá o **valor padrão**. @@ -223,29 +91,7 @@ O suporte para `separate_input_output_schemas` foi adicionado no FastAPI `0.102. /// -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/separate_openapi_schemas/tutorial002.py!} -``` - -//// +{* ../../docs_src/separate_openapi_schemas/tutorial002_py310.py hl[10] *} ### Mesmo Esquema para Modelos de Entrada e Saída na Documentação diff --git a/docs/pt/docs/tutorial/body-fields.md b/docs/pt/docs/tutorial/body-fields.md index ac0b85ab5..e7dfb07f2 100644 --- a/docs/pt/docs/tutorial/body-fields.md +++ b/docs/pt/docs/tutorial/body-fields.md @@ -6,9 +6,7 @@ Da mesma forma que você pode declarar validações adicionais e metadados nos p Primeiro, você tem que importá-lo: -```Python hl_lines="4" -{!../../docs_src/body_fields/tutorial001.py!} -``` +{* ../../docs_src/body_fields/tutorial001.py hl[4] *} /// warning | Aviso @@ -20,9 +18,7 @@ Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como Você pode então utilizar `Field` com atributos do modelo: -```Python hl_lines="11-14" -{!../../docs_src/body_fields/tutorial001.py!} -``` +{* ../../docs_src/body_fields/tutorial001.py hl[11:14] *} `Field` funciona da mesma forma que `Query`, `Path` e `Body`, ele possui todos os mesmos parâmetros, etc. diff --git a/docs/pt/docs/tutorial/body-multiple-params.md b/docs/pt/docs/tutorial/body-multiple-params.md index ad4931b11..eda9b4dff 100644 --- a/docs/pt/docs/tutorial/body-multiple-params.md +++ b/docs/pt/docs/tutorial/body-multiple-params.md @@ -8,21 +8,7 @@ Primeiro, é claro, você pode misturar `Path`, `Query` e declarações de parâ E você também pode declarar parâmetros de corpo como opcionais, definindo o valor padrão com `None`: -//// tab | Python 3.10+ - -```Python hl_lines="17-19" -{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial001_py310.py hl[17:19] *} /// note | Nota @@ -45,21 +31,7 @@ No exemplo anterior, as *operações de rota* esperariam um JSON no corpo conten Mas você pode também declarar múltiplos parâmetros de corpo, por exemplo, `item` e `user`: -//// tab | Python 3.10+ - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} Neste caso, o **FastAPI** perceberá que existe mais de um parâmetro de corpo na função (dois parâmetros que são modelos Pydantic). @@ -100,21 +72,7 @@ Se você declará-lo como é, porque é um valor singular, o **FastAPI** assumir Mas você pode instruir o **FastAPI** para tratá-lo como outra chave do corpo usando `Body`: -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial003.py!} -``` - -//// - -//// tab | Python 3.10+ - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial003.py hl[22] *} Neste caso, o **FastAPI** esperará um corpo como: @@ -154,21 +112,7 @@ q: str | None = None Por exemplo: -//// tab | Python 3.10+ - -```Python hl_lines="26" -{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial004_py310.py hl[26] *} /// info | Informação @@ -190,21 +134,7 @@ item: Item = Body(embed=True) como em: -//// tab | Python 3.10+ - -```Python hl_lines="15" -{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial005_py310.py hl[15] *} Neste caso o **FastAPI** esperará um corpo como: diff --git a/docs/pt/docs/tutorial/body-nested-models.md b/docs/pt/docs/tutorial/body-nested-models.md index bbe72a744..2954ae3db 100644 --- a/docs/pt/docs/tutorial/body-nested-models.md +++ b/docs/pt/docs/tutorial/body-nested-models.md @@ -6,9 +6,7 @@ Com o **FastAPI**, você pode definir, validar, documentar e usar modelos profun Você pode definir um atributo como um subtipo. Por exemplo, uma `list` do Python: -```Python hl_lines="14" -{!../../docs_src/body_nested_models/tutorial001.py!} -``` +{* ../../docs_src/body_nested_models/tutorial001.py hl[14] *} Isso fará com que tags seja uma lista de itens mesmo sem declarar o tipo dos elementos desta lista. @@ -20,9 +18,7 @@ Mas o Python tem uma maneira específica de declarar listas com tipos internos o Primeiramente, importe `List` do módulo `typing` que já vem por padrão no Python: -```Python hl_lines="1" -{!../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### Declare a `List` com um parâmetro de tipo @@ -44,9 +40,7 @@ Use a mesma sintaxe padrão para atributos de modelo com tipos internos. Portanto, em nosso exemplo, podemos fazer com que `tags` sejam especificamente uma "lista de strings": -```Python hl_lines="14" -{!../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[14] *} ## Tipo "set" @@ -58,9 +52,7 @@ E que o Python tem um tipo de dados especial para conjuntos de itens únicos, o Então podemos importar `Set` e declarar `tags` como um `set` de `str`s: -```Python hl_lines="1 14" -{!../../docs_src/body_nested_models/tutorial003.py!} -``` +{* ../../docs_src/body_nested_models/tutorial003.py hl[1,14] *} Com isso, mesmo que você receba uma requisição contendo dados duplicados, ela será convertida em um conjunto de itens exclusivos. @@ -82,17 +74,13 @@ Tudo isso, aninhado arbitrariamente. Por exemplo, nós podemos definir um modelo `Image`: -```Python hl_lines="9-11" -{!../../docs_src/body_nested_models/tutorial004.py!} -``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[9:11] *} ### Use o sub-modelo como um tipo E então podemos usa-lo como o tipo de um atributo: -```Python hl_lines="20" -{!../../docs_src/body_nested_models/tutorial004.py!} -``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[20] *} Isso significa que o **FastAPI** vai esperar um corpo similar à: @@ -125,9 +113,7 @@ Para ver todas as opções possíveis, cheque a documentação para os ../../../docs_src/body_updates/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *} `PUT` é usado para receber dados que devem substituir os dados existentes. @@ -84,29 +62,7 @@ Isso gera um `dict` com apenas os dados definidos ao criar o modelo `item`, excl Então, você pode usar isso para gerar um `dict` com apenas os dados definidos (enviados na solicitação), omitindo valores padrão: -//// tab | Python 3.10+ - -```Python hl_lines="32" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *} ### Usando o parâmetro `update` do Pydantic @@ -122,29 +78,7 @@ Os exemplos aqui usam `.copy()` para compatibilidade com o Pydantic v1, mas voc Como `stored_item_model.model_copy(update=update_data)`: -//// tab | Python 3.10+ - -```Python hl_lines="33" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *} ### Recapitulando as atualizações parciais @@ -161,29 +95,7 @@ Resumindo, para aplicar atualizações parciais você pode: * Salvar os dados no seu banco de dados. * Retornar o modelo atualizado. -//// tab | Python 3.10+ - -```Python hl_lines="28-35" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *} /// tip | Dica diff --git a/docs/pt/docs/tutorial/body.md b/docs/pt/docs/tutorial/body.md index f3a1fda75..2508d7981 100644 --- a/docs/pt/docs/tutorial/body.md +++ b/docs/pt/docs/tutorial/body.md @@ -22,9 +22,7 @@ Como é desencorajado, a documentação interativa com Swagger UI não irá most Primeiro, você precisa importar `BaseModel` do `pydantic`: -```Python hl_lines="4" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[4] *} ## Crie seu modelo de dados @@ -32,9 +30,7 @@ Então você declara seu modelo de dados como uma classe que herda `BaseModel`. Utilize os tipos Python padrão para todos os atributos: -```Python hl_lines="7-11" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[7:11] *} Assim como quando declaramos parâmetros de consulta, quando um atributo do modelo possui um valor padrão, ele se torna opcional. Caso contrário, se torna obrigatório. Use `None` para torná-lo opcional. @@ -62,9 +58,7 @@ Por exemplo, o modelo acima declara um JSON "`object`" (ou `dict` no Python) com Para adicionar o corpo na *função de operação de rota*, declare-o da mesma maneira que você declarou parâmetros de rota e consulta: -```Python hl_lines="18" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[18] *} ...E declare o tipo como o modelo que você criou, `Item`. @@ -131,9 +125,7 @@ Melhora o suporte do editor para seus modelos Pydantic com:: Dentro da função, você pode acessar todos os atributos do objeto do modelo diretamente: -```Python hl_lines="21" -{!../../docs_src/body/tutorial002.py!} -``` +{* ../../docs_src/body/tutorial002.py hl[21] *} ## Corpo da requisição + parâmetros de rota @@ -141,9 +133,7 @@ Você pode declarar parâmetros de rota e corpo da requisição ao mesmo tempo. O **FastAPI** irá reconhecer que os parâmetros da função que combinam com parâmetros de rota devem ser **retirados da rota**, e parâmetros da função que são declarados como modelos Pydantic sejam **retirados do corpo da requisição**. -```Python hl_lines="17-18" -{!../../docs_src/body/tutorial003.py!} -``` +{* ../../docs_src/body/tutorial003.py hl[17:18] *} ## Corpo da requisição + parâmetros de rota + parâmetros de consulta @@ -151,9 +141,7 @@ Você também pode declarar parâmetros de **corpo**, **rota** e **consulta**, a O **FastAPI** irá reconhecer cada um deles e retirar a informação do local correto. -```Python hl_lines="18" -{!../../docs_src/body/tutorial004.py!} -``` +{* ../../docs_src/body/tutorial004.py hl[18] *} Os parâmetros da função serão reconhecidos conforme abaixo: diff --git a/docs/pt/docs/tutorial/cookie-param-models.md b/docs/pt/docs/tutorial/cookie-param-models.md index 671e0d74f..3d46ba44c 100644 --- a/docs/pt/docs/tutorial/cookie-param-models.md +++ b/docs/pt/docs/tutorial/cookie-param-models.md @@ -20,57 +20,7 @@ Essa mesma técnica se aplica para `Query`, `Cookie`, e `Header`. 😎 Declare o parâmetro de **cookie** que você precisa em um **modelo Pydantic**, e depois declare o parâmetro como um `Cookie`: -//// tab | Python 3.10+ - -```Python hl_lines="9-12 16" -{!> ../../docs_src/cookie_param_models/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-12 16" -{!> ../../docs_src/cookie_param_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10-13 17" -{!> ../../docs_src/cookie_param_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="7-10 14" -{!> ../../docs_src/cookie_param_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9-12 16" -{!> ../../docs_src/cookie_param_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} O **FastAPI** irá **extrair** os dados para **cada campo** dos **cookies** recebidos na requisição e lhe fornecer o modelo Pydantic que você definiu. @@ -102,35 +52,7 @@ Agora a sua API possui o poder de contrar o seu próprio ../../docs_src/cookie_param_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/cookie_param_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/cookie_param_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *} Se o cliente tentar enviar alguns **cookies extras**, eles receberão um retorno de **erro**. diff --git a/docs/pt/docs/tutorial/cookie-params.md b/docs/pt/docs/tutorial/cookie-params.md index 50bec8cf7..da85d796e 100644 --- a/docs/pt/docs/tutorial/cookie-params.md +++ b/docs/pt/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ Você pode definir parâmetros de Cookie da mesma maneira que define paramêtros Primeiro importe `Cookie`: -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## Declare parâmetros de `Cookie` @@ -65,57 +15,7 @@ Então declare os paramêtros de cookie usando a mesma estrutura que em `Path` e Você pode definir o valor padrão, assim como todas as validações extras ou parâmetros de anotação: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_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 | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} /// note | Detalhes Técnicos diff --git a/docs/pt/docs/tutorial/cors.md b/docs/pt/docs/tutorial/cors.md index 326101bd2..0ab07a3c2 100644 --- a/docs/pt/docs/tutorial/cors.md +++ b/docs/pt/docs/tutorial/cors.md @@ -46,9 +46,7 @@ Você também pode especificar se o seu backend permite: * Métodos HTTP específicos (`POST`, `PUT`) ou todos eles com o curinga `"*"`. * Cabeçalhos HTTP específicos ou todos eles com o curinga `"*"`. -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} Os parâmetros padrão usados ​​pela implementação `CORSMiddleware` são restritivos por padrão, então você precisará habilitar explicitamente as origens, métodos ou cabeçalhos específicos para que os navegadores tenham permissão para usá-los em um contexto de domínios diferentes. diff --git a/docs/pt/docs/tutorial/debugging.md b/docs/pt/docs/tutorial/debugging.md index fca162988..67b764457 100644 --- a/docs/pt/docs/tutorial/debugging.md +++ b/docs/pt/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ Você pode conectar o depurador no seu editor, por exemplo, com o Visual Studio Em seu aplicativo FastAPI, importe e execute `uvicorn` diretamente: -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### Sobre `__name__ == "__main__"` diff --git a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md index fcf71d08c..ef67aa979 100644 --- a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,57 +6,7 @@ Antes de nos aprofundarmos no sistema de **Injeção de Dependência**, vamos me No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injetável"): -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *} Mas assim obtemos um `dict` como valor do parâmetro `commons` na *função de operação de rota*. @@ -119,165 +69,15 @@ Isso também se aplica a objetos chamáveis que não recebem nenhum parâmetro. Então, podemos mudar o "injetável" na dependência `common_parameters` acima para a classe `CommonQueryParams`: -//// tab | Python 3.10+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12-16" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="9-13" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *} Observe o método `__init__` usado para criar uma instância da classe: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *} ...ele possui os mesmos parâmetros que nosso `common_parameters` anterior: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="6" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *} Esses parâmetros são utilizados pelo **FastAPI** para "definir" a dependência. @@ -293,57 +93,7 @@ Os dados serão convertidos, validados, documentados no esquema da OpenAPI e etc Agora você pode declarar sua dependência utilizando essa classe. -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *} O **FastAPI** chama a classe `CommonQueryParams`. Isso cria uma "instância" dessa classe e é a instância que será passada para o parâmetro `commons` na sua função. @@ -437,57 +187,7 @@ commons = Depends(CommonQueryParams) ...como em: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *} Mas declarar o tipo é encorajado por que é a forma que o seu editor de texto sabe o que será passado como valor do parâmetro `commons`. @@ -575,57 +275,7 @@ Você declara a dependência como o tipo do parâmetro, e utiliza `Depends()` se O mesmo exemplo ficaria então dessa forma: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *} ...e o **FastAPI** saberá o que fazer. diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 89c34855e..d7d31bb45 100644 --- a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,35 +14,7 @@ O *decorador da operação de rota* recebe um argumento opcional `dependencies`. Ele deve ser uma lista de `Depends()`: -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *} Essas dependências serão executadas/resolvidas da mesma forma que dependências comuns. Mas o valor delas (se existir algum) não será passado para a sua *função de operação de rota*. @@ -72,69 +44,13 @@ Você pode utilizar as mesmas *funções* de dependências que você usaria norm Dependências podem declarar requisitos de requisições (como cabeçalhos) ou outras subdependências: -//// tab | Python 3.9+ - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7 12" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível - -/// - -```Python hl_lines="6 11" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *} ### Levantando exceções Essas dependências podem levantar exceções, da mesma forma que dependências comuns: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *} ### Valores de retorno @@ -142,37 +58,7 @@ E elas também podem ou não retornar valores, eles não serão utilizados. Então, você pode reutilizar uma dependência comum (que retorna um valor) que já seja utilizada em outro lugar, e mesmo que o valor não seja utilizado, a dependência será executada: -//// tab | Python 3.9+ - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | Dica - - - -/// - - Utilize a versão com `Annotated` se possível - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *} ## Dependências para um grupo de *operações de rota* diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md index 90c1e02e0..eaf711197 100644 --- a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md @@ -29,21 +29,15 @@ Por exemplo, você poderia utilizar isso para criar uma sessão do banco de dado Apenas o código anterior a declaração com `yield` e o código contendo essa declaração são executados antes de criar uma resposta. -```Python hl_lines="2-4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *} O valor gerado (yielded) é o que é injetado nas *operações de rota* e outras dependências. -```Python hl_lines="4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} O código após o `yield` é executado após a resposta ser entregue: -```Python hl_lines="5-6" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *} /// tip | Dica @@ -207,35 +201,7 @@ Uma alternativa que você pode utilizar para capturar exceções (e possivelment Se você capturar uma exceção com `except` em uma dependência que utilize `yield` e ela não for levantada novamente (ou uma nova exceção for levantada), o FastAPI não será capaz de identifcar que houve uma exceção, da mesma forma que aconteceria com Python puro: -//// tab | Python 3.9+ - -```Python hl_lines="15-16" -{!> ../../docs_src/dependencies/tutorial008c_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14-15" -{!> ../../docs_src/dependencies/tutorial008c_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-annotated - -/// tip | dica - -utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="13-14" -{!> ../../docs_src/dependencies/tutorial008c.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *} Neste caso, o cliente irá ver uma resposta *HTTP 500 Internal Server Error* como deveria acontecer, já que não estamos levantando nenhuma `HTTPException` ou coisa parecida, mas o servidor **não terá nenhum log** ou qualquer outra indicação de qual foi o erro. 😱 @@ -245,21 +211,7 @@ Se você capturar uma exceção em uma dependência com `yield`, a menos que voc Você pode relançar a mesma exceção utilizando `raise`: -//// tab | Python 3.9+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial008d_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial008d_an.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *} //// tab | python 3.8+ non-annotated @@ -269,9 +221,7 @@ Utilize a versão com `Annotated` se possível. /// -```Python hl_lines="15" -{!> ../../docs_src/dependencies/tutorial008d.py!} -``` +{* ../../docs_src/dependencies/tutorial008d.py hl[15] *} //// @@ -402,9 +352,7 @@ Em python, você pode criar Gerenciadores de Contexto ao ../../docs_src/dependencies/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/dependencies/tutorial012.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[16] *} E todos os conceitos apresentados na sessão sobre [adicionar dependências em *decoradores de operação de rota*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} ainda se aplicam, mas nesse caso, para todas as *operações de rota* da aplicação. diff --git a/docs/pt/docs/tutorial/dependencies/index.md b/docs/pt/docs/tutorial/dependencies/index.md index 0f411ff1e..1500b715a 100644 --- a/docs/pt/docs/tutorial/dependencies/index.md +++ b/docs/pt/docs/tutorial/dependencies/index.md @@ -31,57 +31,7 @@ Primeiro vamos focar na dependência. Ela é apenas uma função que pode receber os mesmos parâmetros de uma *função de operação de rota*: -//// 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 | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="8-11" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *} E pronto. @@ -113,113 +63,13 @@ Certifique-se de [Atualizar a versão do FastAPI](../../deployment/versions.md#a ### Importando `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 | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} ### Declarando a dependência, no "dependente" Da mesma forma que você utiliza `Body`, `Query`, etc. Como parâmetros de sua *função de operação de rota*, utilize `Depends` com um novo parâmetro: -//// 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 | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} Ainda que `Depends` seja utilizado nos parâmetros da função da mesma forma que `Body`, `Query`, etc, `Depends` funciona de uma forma um pouco diferente. @@ -276,29 +126,7 @@ commons: Annotated[dict, Depends(common_parameters)] Mas como estamos utilizando `Annotated`, podemos guardar esse valor `Annotated` em uma variável e utilizá-la em múltiplos locais: -//// 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 | Dica diff --git a/docs/pt/docs/tutorial/dependencies/sub-dependencies.md b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md index 4c0f42dbb..3975ce182 100644 --- a/docs/pt/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md @@ -10,57 +10,7 @@ O **FastAPI** se encarrega de resolver essas dependências. Você pode criar uma primeira dependência (injetável) dessa forma: -//// tab | Python 3.10+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-10" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *} Esse código declara um parâmetro de consulta opcional, `q`, com o tipo `str`, e então retorna esse parâmetro. @@ -70,57 +20,7 @@ Isso é bastante simples (e não muito útil), mas irá nos ajudar a focar em co Então, você pode criar uma outra função para uma dependência (um "injetável") que ao mesmo tempo declara sua própria dependência (o que faz dela um "dependente" também): -//// tab | Python 3.10+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *} Vamos focar nos parâmetros declarados: @@ -133,57 +33,7 @@ Vamos focar nos parâmetros declarados: Então podemos utilizar a dependência com: -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *} /// info | Informação diff --git a/docs/pt/docs/tutorial/encoder.md b/docs/pt/docs/tutorial/encoder.md index d89c71fc8..87c6322e1 100644 --- a/docs/pt/docs/tutorial/encoder.md +++ b/docs/pt/docs/tutorial/encoder.md @@ -20,21 +20,7 @@ Você pode usar a função `jsonable_encoder` para resolver isso. A função recebe um objeto, como um modelo Pydantic e retorna uma versão compatível com JSON: -//// 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] *} Neste exemplo, ele converteria o modelo Pydantic em um `dict`, e o `datetime` em um `str`. diff --git a/docs/pt/docs/tutorial/extra-data-types.md b/docs/pt/docs/tutorial/extra-data-types.md index 78f7ac694..09c838be0 100644 --- a/docs/pt/docs/tutorial/extra-data-types.md +++ b/docs/pt/docs/tutorial/extra-data-types.md @@ -55,12 +55,8 @@ Aqui estão alguns dos tipos de dados adicionais que você pode usar: Aqui está um exemplo de *operação de rota* com parâmetros utilizando-se de alguns dos tipos acima. -```Python hl_lines="1 3 12-16" -{!../../docs_src/extra_data_types/tutorial001.py!} -``` +{* ../../docs_src/extra_data_types/tutorial001.py hl[1,3,12:16] *} Note que os parâmetros dentro da função tem seu tipo de dados natural, e você pode, por exemplo, realizar manipulações normais de data, como: -```Python hl_lines="18-19" -{!../../docs_src/extra_data_types/tutorial001.py!} -``` +{* ../../docs_src/extra_data_types/tutorial001.py hl[18:19] *} diff --git a/docs/pt/docs/tutorial/extra-models.md b/docs/pt/docs/tutorial/extra-models.md index 03227f2bb..cccef16e3 100644 --- a/docs/pt/docs/tutorial/extra-models.md +++ b/docs/pt/docs/tutorial/extra-models.md @@ -20,21 +20,7 @@ Se não souber, você aprenderá o que é uma "senha hash" nos [capítulos de se Aqui está uma ideia geral de como os modelos poderiam parecer com seus campos de senha e os lugares onde são usados: -//// tab | Python 3.8 and above - -```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../docs_src/extra_models/tutorial001.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../docs_src/extra_models/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial001.py hl[9,11,16,22,24,29:30,33:35,40:41] *} ### Sobre `**user_in.dict()` @@ -168,21 +154,7 @@ Toda conversão de dados, validação, documentação, etc. ainda funcionará no Dessa forma, podemos declarar apenas as diferenças entre os modelos (com `password` em texto claro, com `hashed_password` e sem senha): -//// tab | Python 3.8 and above - -```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../docs_src/extra_models/tutorial002.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../docs_src/extra_models/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial002.py hl[9,15:16,19:20,23:24] *} ## `Union` ou `anyOf` @@ -198,21 +170,7 @@ Ao definir um ../../docs_src/extra_models/tutorial003.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial003.py hl[1,14:15,18:20,33] *} ### `Union` no Python 3.10 @@ -234,21 +192,7 @@ Da mesma forma, você pode declarar respostas de listas de objetos. Para isso, use o padrão Python `typing.List` (ou simplesmente `list` no Python 3.9 e superior): -//// tab | Python 3.8 and above - -```Python hl_lines="1 20" -{!> ../../docs_src/extra_models/tutorial004.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="18" -{!> ../../docs_src/extra_models/tutorial004_py39.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial004.py hl[1,20] *} ## Resposta com `dict` arbitrário @@ -258,21 +202,7 @@ Isso é útil se você não souber os nomes de campo / atributo válidos (que se Neste caso, você pode usar `typing.Dict` (ou simplesmente dict no Python 3.9 e superior): -//// tab | Python 3.8 and above - -```Python hl_lines="1 8" -{!> ../../docs_src/extra_models/tutorial005.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="6" -{!> ../../docs_src/extra_models/tutorial005_py39.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial005.py hl[1,8] *} ## Em resumo diff --git a/docs/pt/docs/tutorial/first-steps.md b/docs/pt/docs/tutorial/first-steps.md index f301c18b6..523b8f05c 100644 --- a/docs/pt/docs/tutorial/first-steps.md +++ b/docs/pt/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ O arquivo FastAPI mais simples pode se parecer com: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Copie o conteúdo para um arquivo `main.py`. @@ -133,9 +131,7 @@ Você também pode usá-lo para gerar código automaticamente para clientes que ### Passo 1: importe `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` é uma classe Python que fornece todas as funcionalidades para sua API. @@ -149,9 +145,7 @@ Você pode usar todas as funcionalidades do ../../docs_src/header_param_models/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-14 18" -{!> ../../docs_src/header_param_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10-15 19" -{!> ../../docs_src/header_param_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="7-12 16" -{!> ../../docs_src/header_param_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="9-14 18" -{!> ../../docs_src/header_param_models/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="7-12 16" -{!> ../../docs_src/header_param_models/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *} O **FastAPI** irá **extrair** os dados de **cada campo** a partir dos **cabeçalhos** da requisição e te retornará o modelo do Pydantic que você definiu. @@ -96,71 +32,7 @@ Em alguns casos de uso especiais (provavelmente não muito comuns), você pode q Você pode usar a configuração dos modelos do Pydantic para proibir (`forbid`) quaisquer campos `extra`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/header_param_models/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/header_param_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/header_param_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/header_param_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/header_param_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/header_param_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/header_param_models/tutorial002_an_py310.py hl[10] *} Se um cliente tentar enviar alguns **cabeçalhos extra**, eles irão receber uma resposta de **erro**. diff --git a/docs/pt/docs/tutorial/header-params.md b/docs/pt/docs/tutorial/header-params.md index ac61d0305..d071bcc35 100644 --- a/docs/pt/docs/tutorial/header-params.md +++ b/docs/pt/docs/tutorial/header-params.md @@ -6,21 +6,7 @@ Você pode definir parâmetros de Cabeçalho da mesma maneira que define paramê Primeiro importe `Header`: -//// tab | Python 3.10+ - -```Python hl_lines="1" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial001_py310.py hl[1] *} ## Declare parâmetros de `Header` @@ -28,21 +14,7 @@ Então declare os paramêtros de cabeçalho usando a mesma estrutura que em `Pat O primeiro valor é o valor padrão, você pode passar todas as validações adicionais ou parâmetros de anotação: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial001_py310.py hl[7] *} /// note | Detalhes Técnicos @@ -74,21 +46,7 @@ Portanto, você pode usar `user_agent` como faria normalmente no código Python, Se por algum motivo você precisar desabilitar a conversão automática de sublinhados para hífens, defina o parâmetro `convert_underscores` de `Header` para `False`: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/header_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial002_py310.py hl[8] *} /// warning | Aviso @@ -106,29 +64,7 @@ Você receberá todos os valores do cabeçalho duplicado como uma `list` Python. Por exemplo, para declarar um cabeçalho de `X-Token` que pode aparecer mais de uma vez, você pode escrever: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial003_py310.py hl[7] *} Se você se comunicar com essa *operação de caminho* enviando dois cabeçalhos HTTP como: diff --git a/docs/pt/docs/tutorial/metadata.md b/docs/pt/docs/tutorial/metadata.md index 5db2882b9..57effb3ff 100644 --- a/docs/pt/docs/tutorial/metadata.md +++ b/docs/pt/docs/tutorial/metadata.md @@ -18,9 +18,7 @@ Você pode definir os seguintes campos que são usados na especificação OpenAP Você pode defini-los da seguinte maneira: -```Python hl_lines="3-16 19-32" -{!../../docs_src/metadata/tutorial001.py!} -``` +{* ../../docs_src/metadata/tutorial001.py hl[3:16,19:32] *} /// tip | Dica @@ -38,9 +36,7 @@ Desde o OpenAPI 3.1.0 e FastAPI 0.99.0, você também pode definir o license_inf Por exemplo: -```Python hl_lines="31" -{!../../docs_src/metadata/tutorial001_1.py!} -``` +{* ../../docs_src/metadata/tutorial001_1.py hl[31] *} ## Metadados para tags @@ -62,9 +58,7 @@ Vamos tentar isso em um exemplo com tags para `users` e `items`. Crie metadados para suas tags e passe-os para o parâmetro `openapi_tags`: -```Python hl_lines="3-16 18" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} Observe que você pode usar Markdown dentro das descrições. Por exemplo, "login" será exibido em negrito (**login**) e "fancy" será exibido em itálico (_fancy_). @@ -78,9 +72,7 @@ Você não precisa adicionar metadados para todas as tags que você usa. Use o parâmetro `tags` com suas *operações de rota* (e `APIRouter`s) para atribuí-los a diferentes tags: -```Python hl_lines="21 26" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} /// info | Informação @@ -108,9 +100,7 @@ Mas você pode configurá-lo com o parâmetro `openapi_url`. Por exemplo, para defini-lo para ser servido em `/api/v1/openapi.json`: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial002.py!} -``` +{* ../../docs_src/metadata/tutorial002.py hl[3] *} Se você quiser desativar completamente o esquema OpenAPI, pode definir `openapi_url=None`, o que também desativará as interfaces de documentação que o utilizam. @@ -127,6 +117,4 @@ Você pode configurar as duas interfaces de documentação incluídas: Por exemplo, para definir o Swagger UI para ser servido em `/documentation` e desativar o ReDoc: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial003.py!} -``` +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/pt/docs/tutorial/middleware.md b/docs/pt/docs/tutorial/middleware.md index d1b798356..32b81c646 100644 --- a/docs/pt/docs/tutorial/middleware.md +++ b/docs/pt/docs/tutorial/middleware.md @@ -31,9 +31,7 @@ A função middleware recebe: * Então ela retorna a `response` gerada pela *operação de rota* correspondente. * Você pode então modificar ainda mais o `response` antes de retorná-lo. -```Python hl_lines="8-9 11 14" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} /// tip | Dica @@ -59,9 +57,7 @@ E também depois que a `response` é gerada, antes de retorná-la. Por exemplo, você pode adicionar um cabeçalho personalizado `X-Process-Time` contendo o tempo em segundos que levou para processar a solicitação e gerar uma resposta: -```Python hl_lines="10 12-13" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} ## Outros middlewares diff --git a/docs/pt/docs/tutorial/path-operation-configuration.md b/docs/pt/docs/tutorial/path-operation-configuration.md index 5f3cc82fb..f183c9d23 100644 --- a/docs/pt/docs/tutorial/path-operation-configuration.md +++ b/docs/pt/docs/tutorial/path-operation-configuration.md @@ -16,29 +16,7 @@ Você pode passar diretamente o código `int`, como `404`. Mas se você não se lembrar o que cada código numérico significa, pode usar as constantes de atalho em `status`: -//// tab | Python 3.8 and above - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="1 15" -{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *} Esse código de status será usado na resposta e será adicionado ao esquema OpenAPI. @@ -54,29 +32,7 @@ Você também poderia usar `from starlette import status`. Você pode adicionar tags para sua *operação de rota*, passe o parâmetro `tags` com uma `list` de `str` (comumente apenas um `str`): -//// tab | Python 3.8 and above - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="15 20 25" -{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *} Eles serão adicionados ao esquema OpenAPI e usados pelas interfaces de documentação automática: @@ -90,37 +46,13 @@ Nestes casos, pode fazer sentido armazenar as tags em um `Enum`. **FastAPI** suporta isso da mesma maneira que com strings simples: -```Python hl_lines="1 8-10 13 18" -{!../../docs_src/path_operation_configuration/tutorial002b.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *} ## Resumo e descrição Você pode adicionar um `summary` e uma `description`: -//// tab | Python 3.8 and above - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="18-19" -{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *} ## Descrição do docstring @@ -128,29 +60,7 @@ Como as descrições tendem a ser longas e cobrir várias linhas, você pode dec Você pode escrever Markdown na docstring, ele será interpretado e exibido corretamente (levando em conta a indentação da docstring). -//// tab | Python 3.8 and above - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="17-25" -{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *} Ela será usada nas documentações interativas: @@ -161,29 +71,7 @@ Ela será usada nas documentações interativas: Você pode especificar a descrição da resposta com o parâmetro `response_description`: -//// tab | Python 3.8 and above - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="19" -{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial005.py hl[21] *} /// info | Informação @@ -205,9 +93,7 @@ Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma Se você precisar marcar uma *operação de rota* como descontinuada, mas sem removê-la, passe o parâmetro `deprecated`: -```Python hl_lines="16" -{!../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} Ela será claramente marcada como descontinuada nas documentações interativas: diff --git a/docs/pt/docs/tutorial/path-params-numeric-validations.md b/docs/pt/docs/tutorial/path-params-numeric-validations.md index 3361f86c5..3aea1188d 100644 --- a/docs/pt/docs/tutorial/path-params-numeric-validations.md +++ b/docs/pt/docs/tutorial/path-params-numeric-validations.md @@ -6,21 +6,7 @@ Do mesmo modo que você pode declarar mais validações e metadados para parâme Primeiro, importe `Path` de `fastapi`: -//// tab | Python 3.10+ - -```Python hl_lines="1" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001_py310.py hl[1] *} ## Declare metadados @@ -28,21 +14,7 @@ Você pode declarar todos os parâmetros da mesma maneira que na `Query`. Por exemplo para declarar um valor de metadado `title` para o parâmetro de rota `item_id` você pode digitar: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001_py310.py hl[8] *} /// note | Nota @@ -70,9 +42,7 @@ Isso não faz diferença para o **FastAPI**. Ele vai detectar os parâmetros pel Então, você pode declarar sua função assim: -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} ## Ordene os parâmetros de a acordo com sua necessidade, truques @@ -82,9 +52,7 @@ Passe `*`, como o primeiro parâmetro da função. O Python não vai fazer nada com esse `*`, mas ele vai saber que a partir dali os parâmetros seguintes deverão ser chamados argumentos nomeados (pares chave-valor), também conhecidos como kwargs. Mesmo que eles não possuam um valor padrão. -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ## Validações numéricas: maior que ou igual @@ -92,9 +60,7 @@ Com `Query` e `Path` (e outras que você verá mais tarde) você pode declarar r Aqui, com `ge=1`, `item_id` precisará ser um número inteiro maior que ("`g`reater than") ou igual ("`e`qual") a 1. -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *} ## Validações numéricas: maior que e menor que ou igual @@ -103,9 +69,7 @@ O mesmo se aplica para: * `gt`: maior que (`g`reater `t`han) * `le`: menor que ou igual (`l`ess than or `e`qual) -```Python hl_lines="9" -{!../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *} ## Validações numéricas: valores do tipo float, maior que e menor que @@ -117,9 +81,7 @@ Assim, `0.5` seria um valor válido. Mas `0.0` ou `0` não seria. E o mesmo para lt. -```Python hl_lines="11" -{!../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *} ## Recapitulando diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md index 64f8a0253..ecf77d676 100644 --- a/docs/pt/docs/tutorial/path-params.md +++ b/docs/pt/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ Você pode declarar os "parâmetros" ou "variáveis" com a mesma sintaxe utilizada pelo formato de strings do Python: -```Python hl_lines="6-7" -{!../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} O valor do parâmetro que foi passado à `item_id` será passado para a sua função como o argumento `item_id`. @@ -18,9 +16,7 @@ Então, se você rodar este exemplo e for até ../../docs_src/query_param_models/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-12 16" -{!> ../../docs_src/query_param_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10-14 18" -{!> ../../docs_src/query_param_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9-13 17" -{!> ../../docs_src/query_param_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="8-12 16" -{!> ../../docs_src/query_param_models/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9-13 17" -{!> ../../docs_src/query_param_models/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} O **FastAPI** **extrairá** os dados para **cada campo** dos **parâmetros de consulta** presentes na requisição, e fornecerá o modelo Pydantic que você definiu. @@ -97,71 +33,7 @@ Em alguns casos especiais (provavelmente não muito comuns), você queira **rest Você pode usar a configuração do modelo Pydantic para `forbid` (proibir) qualquer campo `extra`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_param_models/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_param_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_param_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_param_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_param_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_param_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} Caso um cliente tente enviar alguns dados **extras** nos **parâmetros de consulta**, eles receberão um retorno de **erro**. diff --git a/docs/pt/docs/tutorial/query-params-str-validations.md b/docs/pt/docs/tutorial/query-params-str-validations.md index 2fa0eeba0..8c4f2e655 100644 --- a/docs/pt/docs/tutorial/query-params-str-validations.md +++ b/docs/pt/docs/tutorial/query-params-str-validations.md @@ -4,9 +4,7 @@ O **FastAPI** permite que você declare informações adicionais e validações Vamos utilizar essa aplicação como exemplo: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial001.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *} O parâmetro de consulta `q` é do tipo `Union[str, None]`, o que significa que é do tipo `str` mas que também pode ser `None`, e de fato, o valor padrão é `None`, então o FastAPI saberá que não é obrigatório. @@ -26,17 +24,13 @@ Nós iremos forçar que mesmo o parâmetro `q` seja opcional, sempre que informa Para isso, primeiro importe `Query` de `fastapi`: -```Python hl_lines="3" -{!../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *} ## Use `Query` como o valor padrão Agora utilize-o como valor padrão do seu parâmetro, definindo o parâmetro `max_length` para 50: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} Note que substituímos o valor padrão de `None` para `Query(default=None)`, o primeiro parâmetro de `Query` serve para o mesmo propósito: definir o valor padrão do parâmetro. @@ -86,17 +80,13 @@ Isso irá validar os dados, mostrar um erro claro quando os dados forem inválid Você também pode incluir um parâmetro `min_length`: -```Python hl_lines="10" -{!../../docs_src/query_params_str_validations/tutorial003.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[10] *} ## Adicionando expressões regulares Você pode definir uma expressão regular que combine com um padrão esperado pelo parâmetro: -```Python hl_lines="11" -{!../../docs_src/query_params_str_validations/tutorial004.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[11] *} Essa expressão regular específica verifica se o valor recebido no parâmetro: @@ -114,9 +104,7 @@ Da mesma maneira que você utiliza `None` como o primeiro argumento para ser uti Vamos dizer que você queira que o parâmetro de consulta `q` tenha um `min_length` de `3`, e um valor padrão de `"fixedquery"`, então declararíamos assim: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial005.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} /// note | Observação @@ -146,9 +134,7 @@ q: Union[str, None] = Query(default=None, min_length=3) Então, quando você precisa declarar um parâmetro obrigatório utilizando o `Query`, você pode utilizar `...` como o primeiro argumento: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial006.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} /// info | Informação @@ -164,9 +150,7 @@ Quando você declara explicitamente um parâmetro com `Query` você pode declar Por exemplo, para declarar que o parâmetro `q` pode aparecer diversas vezes na URL, você escreveria: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial011.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} Então, com uma URL assim: @@ -201,9 +185,7 @@ A documentação interativa da API irá atualizar de acordo, permitindo múltipl E você também pode definir uma lista (`list`) de valores padrão caso nenhum seja informado: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial012.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} Se você for até: @@ -226,9 +208,7 @@ O valor padrão de `q` será: `["foo", "bar"]` e sua resposta será: Você também pode utilizar o tipo `list` diretamente em vez de `List[str]`: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} /// note | Observação @@ -254,15 +234,11 @@ Algumas delas não exibem todas as informações extras que declaramos, ainda qu Você pode adicionar um `title`: -```Python hl_lines="10" -{!../../docs_src/query_params_str_validations/tutorial007.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *} E uma `description`: -```Python hl_lines="13" -{!../../docs_src/query_params_str_validations/tutorial008.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## Apelidos (alias) de parâmetros @@ -282,9 +258,7 @@ Mas ainda você precisa que o nome seja exatamente `item-query`... Então você pode declarar um `alias`, e esse apelido (alias) que será utilizado para encontrar o valor do parâmetro: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial009.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} ## Parâmetros descontinuados @@ -294,9 +268,7 @@ Você tem que deixá-lo ativo por um tempo, já que existem clientes o utilizand Então você passa o parâmetro `deprecated=True` para `Query`: -```Python hl_lines="18" -{!../../docs_src/query_params_str_validations/tutorial010.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} Na documentação aparecerá assim: diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md index 89b951de6..8199de5af 100644 --- a/docs/pt/docs/tutorial/query-params.md +++ b/docs/pt/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ Quando você declara outros parâmetros na função que não fazem parte dos parâmetros da rota, esses parâmetros são automaticamente interpretados como parâmetros de "consulta". -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} A consulta é o conjunto de pares chave-valor que vai depois de `?` na URL, separado pelo caractere `&`. @@ -63,21 +61,7 @@ Os valores dos parâmetros na sua função serão: Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo o valor padrão para `None`: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} Nesse caso, o parâmetro da função `q` será opcional, e `None` será o padrão. @@ -91,21 +75,7 @@ Você também pode notar que o **FastAPI** é esperto o suficiente para perceber Você também pode declarar tipos `bool`, e eles serão convertidos: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} Nesse caso, se você for para: @@ -147,21 +117,7 @@ E você não precisa declarar eles em nenhuma ordem específica. Eles serão detectados pelo nome: -//// tab | Python 3.10+ - -```Python hl_lines="6 8" -{!> ../../docs_src/query_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 10" -{!> ../../docs_src/query_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Parâmetros de consulta obrigatórios @@ -171,9 +127,7 @@ Caso você não queira adicionar um valor específico mas queira apenas torná-l Porém, quando você quiser fazer com que o parâmetro de consulta seja obrigatório, você pode simplesmente não declarar nenhum valor como padrão. -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Aqui o parâmetro de consulta `needy` é um valor obrigatório, do tipo `str`. @@ -217,21 +171,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy E claro, você pode definir alguns parâmetros como obrigatórios, alguns possuindo um valor padrão, e outros sendo totalmente opcionais: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params/tutorial006.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} Nesse caso, existem 3 parâmetros de consulta: diff --git a/docs/pt/docs/tutorial/request-form-models.md b/docs/pt/docs/tutorial/request-form-models.md index 7128a0ae2..ea0e63d38 100644 --- a/docs/pt/docs/tutorial/request-form-models.md +++ b/docs/pt/docs/tutorial/request-form-models.md @@ -24,35 +24,7 @@ Isto é suportado desde a versão `0.113.0` do FastAPI. 🤓 Você precisa apenas declarar um **modelo Pydantic** com os campos que deseja receber como **campos de formulários**, e então declarar o parâmetro como um `Form`: -//// tab | Python 3.9+ - -```Python hl_lines="9-11 15" -{!> ../../docs_src/request_form_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8-10 14" -{!> ../../docs_src/request_form_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="7-9 13" -{!> ../../docs_src/request_form_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *} O **FastAPI** irá **extrair** as informações para **cada campo** dos **dados do formulário** na requisição e dar para você o modelo Pydantic que você definiu. @@ -76,35 +48,7 @@ Isso é suportado deste a versão `0.114.0` do FastAPI. 🤓 Você pode utilizar a configuração de modelo do Pydantic para `proibir` qualquer campo `extra`: -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/request_form_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/request_form_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/request_form_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *} Caso um cliente tente enviar informações adicionais, ele receberá um retorno de **erro**. diff --git a/docs/pt/docs/tutorial/request-forms-and-files.md b/docs/pt/docs/tutorial/request-forms-and-files.md index 77c099eb3..b08d87013 100644 --- a/docs/pt/docs/tutorial/request-forms-and-files.md +++ b/docs/pt/docs/tutorial/request-forms-and-files.md @@ -12,17 +12,13 @@ Por exemplo: `pip install python-multipart`. ## Importe `File` e `Form` -```Python hl_lines="1" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[1] *} ## Defina parâmetros de `File` e `Form` Crie parâmetros de arquivo e formulário da mesma forma que você faria para `Body` ou `Query`: -```Python hl_lines="8" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[8] *} Os arquivos e campos de formulário serão carregados como dados de formulário e você receberá os arquivos e campos de formulário. diff --git a/docs/pt/docs/tutorial/request-forms.md b/docs/pt/docs/tutorial/request-forms.md index 367fca072..756ceb581 100644 --- a/docs/pt/docs/tutorial/request-forms.md +++ b/docs/pt/docs/tutorial/request-forms.md @@ -14,17 +14,13 @@ Ex: `pip install python-multipart`. Importe `Form` de `fastapi`: -```Python hl_lines="1" -{!../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[1] *} ## Declare parâmetros de `Form` Crie parâmetros de formulário da mesma forma que você faria para `Body` ou `Query`: -```Python hl_lines="7" -{!../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[7] *} Por exemplo, em uma das maneiras que a especificação OAuth2 pode ser usada (chamada "fluxo de senha"), é necessário enviar um `username` e uma `password` como campos do formulário. diff --git a/docs/pt/docs/tutorial/request_files.md b/docs/pt/docs/tutorial/request_files.md index 39bfe284a..15c1ad825 100644 --- a/docs/pt/docs/tutorial/request_files.md +++ b/docs/pt/docs/tutorial/request_files.md @@ -16,69 +16,13 @@ Isso se deve por que arquivos enviados são enviados como "dados de formulário" Importe `File` e `UploadFile` do `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} ## Defina os parâmetros de `File` Cria os parâmetros do arquivo da mesma forma que você faria para `Body` ou `Form`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} /// info | Informação @@ -106,35 +50,7 @@ Mas existem vários casos em que você pode se beneficiar ao usar `UploadFile`. Defina um parâmetro de arquivo com o tipo `UploadFile` -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="13" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} Utilizando `UploadFile` tem várias vantagens sobre `bytes`: @@ -217,91 +133,13 @@ Isso não é uma limitação do **FastAPI**, é uma parte do protocolo HTTP. Você pode definir um arquivo como opcional utilizando as anotações de tipo padrão e definindo o valor padrão como `None`: -//// tab | Python 3.10+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 18" -{!> ../../docs_src/request_files/tutorial001_02_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated`, se possível - -/// - -```Python hl_lines="7 15" -{!> ../../docs_src/request_files/tutorial001_02_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated`, se possível - -/// - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} ## `UploadFile` com Metadados Adicionais Você também pode utilizar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais: -//// tab | Python 3.9+ - -```Python hl_lines="9 15" -{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 14" -{!> ../../docs_src/request_files/tutorial001_03_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível - -/// - -```Python hl_lines="7 13" -{!> ../../docs_src/request_files/tutorial001_03.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} ## Envio de Múltiplos Arquivos @@ -311,49 +149,7 @@ Ele ficam associados ao mesmo "campo do formulário" enviado com "form data". Para usar isso, declare uma lista de `bytes` ou `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11 16" -{!> ../../docs_src/request_files/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/request_files/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível - -/// - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} Você irá receber, como delcarado uma lista (`list`) de `bytes` ou `UploadFile`s, @@ -369,49 +165,7 @@ O **FastAPI** fornece as mesmas `starlette.responses` como `fastapi.responses` a E da mesma forma que antes, você pode utilizar `File()` para definir parâmetros adicionais, até mesmo para `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="11 18-20" -{!> ../../docs_src/request_files/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12 19-21" -{!> ../../docs_src/request_files/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="9 16" -{!> ../../docs_src/request_files/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="11 18" -{!> ../../docs_src/request_files/tutorial003.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} ## Recapitulando diff --git a/docs/pt/docs/tutorial/response-status-code.md b/docs/pt/docs/tutorial/response-status-code.md index 2c8924925..48957f67a 100644 --- a/docs/pt/docs/tutorial/response-status-code.md +++ b/docs/pt/docs/tutorial/response-status-code.md @@ -8,9 +8,7 @@ Da mesma forma que você pode especificar um modelo de resposta, você também p * `@app.delete()` * etc. -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} /// note | Nota @@ -77,9 +75,7 @@ Para saber mais sobre cada código de status e qual código serve para quê, ver Vamos ver o exemplo anterior novamente: -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201` é o código de status para "Criado". @@ -87,9 +83,7 @@ Mas você não precisa memorizar o que cada um desses códigos significa. Você pode usar as variáveis de conveniência de `fastapi.status`. -```Python hl_lines="1 6" -{!../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} Eles são apenas uma conveniência, eles possuem o mesmo número, mas dessa forma você pode usar o autocomplete do editor para encontrá-los: diff --git a/docs/pt/docs/tutorial/schema-extra-example.md b/docs/pt/docs/tutorial/schema-extra-example.md index dd95d4c7d..5d3498d7d 100644 --- a/docs/pt/docs/tutorial/schema-extra-example.md +++ b/docs/pt/docs/tutorial/schema-extra-example.md @@ -8,9 +8,7 @@ Aqui estão várias formas de se fazer isso. Você pode declarar um `example` para um modelo Pydantic usando `Config` e `schema_extra`, conforme descrito em Documentação do Pydantic: Schema customization: -```Python hl_lines="15-23" -{!../../docs_src/schema_extra_example/tutorial001.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial001.py hl[15:23] *} Essas informações extras serão adicionadas como se encontram no **JSON Schema** de resposta desse modelo e serão usadas na documentação da API. @@ -28,9 +26,7 @@ Ao usar `Field ()` com modelos Pydantic, você também pode declarar informaçõ Você pode usar isso para adicionar um `example` para cada campo: -```Python hl_lines="4 10-13" -{!../../docs_src/schema_extra_example/tutorial002.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial002.py hl[4,10:13] *} /// warning | Atenção @@ -56,9 +52,7 @@ você também pode declarar um dado `example` ou um grupo de `examples` com info Aqui nós passamos um `example` dos dados esperados por `Body()`: -```Python hl_lines="21-26" -{!../../docs_src/schema_extra_example/tutorial003.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial003.py hl[21:26] *} ### Exemplo na UI da documentação @@ -79,9 +73,7 @@ Cada `dict` de exemplo específico em `examples` pode conter: * `value`: O próprio exemplo mostrado, ex: um `dict`. * `externalValue`: alternativa ao `value`, uma URL apontando para o exemplo. Embora isso possa não ser suportado por tantas ferramentas quanto `value`. -```Python hl_lines="22-48" -{!../../docs_src/schema_extra_example/tutorial004.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial004.py hl[22:48] *} ### Exemplos na UI da documentação diff --git a/docs/pt/docs/tutorial/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md index 02871c90a..f4dea8e14 100644 --- a/docs/pt/docs/tutorial/security/first-steps.md +++ b/docs/pt/docs/tutorial/security/first-steps.md @@ -19,9 +19,7 @@ Vamos primeiro usar o código e ver como funciona, e depois voltaremos para ente ## Crie um `main.py` Copie o exemplo em um arquivo `main.py`: -```Python -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py *} ## Execute-o @@ -135,9 +133,7 @@ Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um Quando nós criamos uma instância da classe `OAuth2PasswordBearer`, nós passamos pelo parâmetro `tokenUrl` Esse parâmetro contém a URL que o client (o frontend rodando no browser do usuário) vai usar para mandar o `username` e `senha` para obter um token. -```Python hl_lines="6" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[6] *} /// tip | Dica @@ -179,9 +175,7 @@ Então, pode ser usado com `Depends`. Agora você pode passar aquele `oauth2_scheme` em uma dependência com `Depends`. -```Python hl_lines="10" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} Esse dependência vai fornecer uma `str` que é atribuído ao parâmetro `token da *função do path operation* diff --git a/docs/pt/docs/tutorial/security/simple-oauth2.md b/docs/pt/docs/tutorial/security/simple-oauth2.md index 4e55f8c25..1cf05785e 100644 --- a/docs/pt/docs/tutorial/security/simple-oauth2.md +++ b/docs/pt/docs/tutorial/security/simple-oauth2.md @@ -52,57 +52,7 @@ Agora vamos usar os utilitários fornecidos pelo **FastAPI** para lidar com isso Primeiro, importe `OAuth2PasswordRequestForm` e use-o como uma dependência com `Depends` na *operação de rota* para `/token`: -//// tab | Python 3.10+ - -```Python hl_lines="4 78" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 78" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 79" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="2 74" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="4 76" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *} `OAuth2PasswordRequestForm` é uma dependência de classe que declara um corpo de formulário com: @@ -150,57 +100,7 @@ Se não existir tal usuário, retornaremos um erro dizendo "Incorrect username o Para o erro, usamos a exceção `HTTPException`: -//// tab | Python 3.10+ - -```Python hl_lines="3 79-81" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3 79-81" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3 80-82" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="1 75-77" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="3 77-79" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *} ### Confira a password (senha) @@ -226,57 +126,7 @@ Se o seu banco de dados for roubado, o ladrão não terá as senhas em texto sim Assim, o ladrão não poderá tentar usar essas mesmas senhas em outro sistema (como muitos usuários usam a mesma senha em todos os lugares, isso seria perigoso). -//// tab | Python 3.10+ - -```Python hl_lines="82-85" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="82-85" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="83-86" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="78-81" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="80-83" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *} #### Sobre `**user_dict` @@ -318,57 +168,7 @@ Mas, por enquanto, vamos nos concentrar nos detalhes específicos de que precisa /// -//// tab | Python 3.10+ - -```Python hl_lines="87" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="87" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="88" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="83" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="85" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *} /// tip | Dica @@ -394,57 +194,7 @@ Ambas as dependências retornarão apenas um erro HTTP se o usuário não existi Portanto, em nosso endpoint, só obteremos um usuário se o usuário existir, tiver sido autenticado corretamente e estiver ativo: -//// tab | Python 3.10+ - -```Python hl_lines="58-66 69-74 94" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="58-66 69-74 94" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="59-67 70-75 95" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="56-64 67-70 88" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="58-66 69-72 90" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *} /// info | Informação diff --git a/docs/pt/docs/tutorial/static-files.md b/docs/pt/docs/tutorial/static-files.md index aba4b8221..0660078f4 100644 --- a/docs/pt/docs/tutorial/static-files.md +++ b/docs/pt/docs/tutorial/static-files.md @@ -7,9 +7,7 @@ Você pode servir arquivos estáticos automaticamente de um diretório usando `S * Importe `StaticFiles`. * "Monte" uma instância de `StaticFiles()` em um caminho específico. -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} /// note | Detalhes técnicos diff --git a/docs/pt/docs/tutorial/testing.md b/docs/pt/docs/tutorial/testing.md index 4f8eaa299..8eb2f29b7 100644 --- a/docs/pt/docs/tutorial/testing.md +++ b/docs/pt/docs/tutorial/testing.md @@ -30,9 +30,7 @@ Use o objeto `TestClient` da mesma forma que você faz com `httpx`. Escreva instruções `assert` simples com as expressões Python padrão que você precisa verificar (novamente, `pytest` padrão). -```Python hl_lines="2 12 15-18" -{!../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} /// tip | Dica @@ -78,9 +76,7 @@ Digamos que você tenha uma estrutura de arquivo conforme descrito em [Aplicativ No arquivo `main.py` você tem seu aplicativo **FastAPI**: -```Python -{!../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### Arquivo de teste @@ -96,9 +92,7 @@ Então você poderia ter um arquivo `test_main.py` com seus testes. Ele poderia Como esse arquivo está no mesmo pacote, você pode usar importações relativas para importar o objeto `app` do módulo `main` (`main.py`): -```Python hl_lines="3" -{!../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py hl[3] *} ...e ter o código para os testes como antes. @@ -182,9 +176,7 @@ Prefira usar a versão `Annotated` se possível. Você pode então atualizar `test_main.py` com os testes estendidos: -```Python -{!> ../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} Sempre que você precisar que o cliente passe informações na requisição e não souber como, você pode pesquisar (no Google) como fazer isso no `httpx`, ou até mesmo como fazer isso com `requests`, já que o design do HTTPX é baseado no design do Requests. diff --git a/docs/ru/docs/python-types.md b/docs/ru/docs/python-types.md index e5905304a..b1d4715fd 100644 --- a/docs/ru/docs/python-types.md +++ b/docs/ru/docs/python-types.md @@ -22,9 +22,8 @@ Python имеет поддержку необязательных аннотац Давайте начнем с простого примера: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Вызов этой программы выводит: @@ -38,9 +37,8 @@ John Doe * Преобразует первую букву содержимого каждой переменной в верхний регистр с `title()`. * Соединяет их через пробел. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Отредактируем пример @@ -82,9 +80,8 @@ John Doe Это аннотации типов: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Это не то же самое, что объявление значений по умолчанию, например: @@ -112,9 +109,8 @@ John Doe Проверьте эту функцию, она уже имеет аннотации типов: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Поскольку редактор знает типы переменных, вы получаете не только дополнение, но и проверки ошибок: @@ -122,9 +118,8 @@ John Doe Теперь вы знаете, что вам нужно исправить, преобразовав `age` в строку с `str(age)`: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Объявление типов @@ -143,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Generic-типы с параметрами типов @@ -161,9 +155,8 @@ John Doe Импортируйте `List` из `typing` (с заглавной `L`): -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + Объявите переменную с тем же синтаксисом двоеточия (`:`). @@ -171,9 +164,8 @@ John Doe Поскольку список является типом, содержащим некоторые внутренние типы, вы помещаете их в квадратные скобки: -```Python hl_lines="4" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + /// tip @@ -199,9 +191,8 @@ John Doe Вы бы сделали то же самое, чтобы объявить `tuple` и `set`: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + Это означает: @@ -216,9 +207,8 @@ John Doe Второй параметр типа предназначен для значений `dict`: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + Это означает: @@ -255,15 +245,13 @@ John Doe Допустим, у вас есть класс `Person` с полем `name`: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Тогда вы можете объявить переменную типа `Person`: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + И снова вы получаете полную поддержку редактора: @@ -283,9 +271,8 @@ John Doe Взято из официальной документации Pydantic: -```Python -{!../../docs_src/python_types/tutorial011.py!} -``` +{* ../../docs_src/python_types/tutorial011.py *} + /// info diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md index a4f98f643..bf2e9dec3 100644 --- a/docs/ru/docs/tutorial/background-tasks.md +++ b/docs/ru/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ Сначала импортируйте `BackgroundTasks`, потом добавьте в функцию параметр с типом `BackgroundTasks`: -```Python hl_lines="1 13" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** создаст объект класса `BackgroundTasks` для вас и запишет его в параметр. @@ -33,17 +31,13 @@ Так как операция записи не использует `async` и `await`, мы определим ее как обычную `def`: -```Python hl_lines="6-9" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## Добавление фоновой задачи Внутри функции вызовите метод `.add_task()` у объекта *background tasks* и передайте ему функцию, которую хотите выполнить в фоне: -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` принимает следующие аргументы: @@ -57,21 +51,7 @@ **FastAPI** знает, что нужно сделать в каждом случае и как переиспользовать тот же объект `BackgroundTasks`, так чтобы все фоновые задачи собрались и запустились вместе в фоне: -//// tab | Python 3.10+ - -```Python hl_lines="11 13 20 23" -{!> ../../docs_src/background_tasks/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002.py!} -``` - -//// +{* ../../docs_src/background_tasks/tutorial002_py310.py hl[11,13,20,23] *} В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен. diff --git a/docs/ru/docs/tutorial/body-fields.md b/docs/ru/docs/tutorial/body-fields.md index 0c4cbb09c..5ed5f59fc 100644 --- a/docs/ru/docs/tutorial/body-fields.md +++ b/docs/ru/docs/tutorial/body-fields.md @@ -6,21 +6,7 @@ Сначала вы должны импортировать его: -//// tab | Python 3.10+ - -```Python hl_lines="2" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_py310.py hl[2] *} /// warning | Внимание @@ -32,21 +18,7 @@ Вы можете использовать функцию `Field` с атрибутами модели: -//// tab | Python 3.10+ - -```Python hl_lines="9-12" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_py310.py hl[9:12] *} Функция `Field` работает так же, как `Query`, `Path` и `Body`, у неё такие же параметры и т.д. diff --git a/docs/ru/docs/tutorial/body-multiple-params.md b/docs/ru/docs/tutorial/body-multiple-params.md index 594e1dbca..9300aa1bd 100644 --- a/docs/ru/docs/tutorial/body-multiple-params.md +++ b/docs/ru/docs/tutorial/body-multiple-params.md @@ -8,57 +8,7 @@ Вы также можете объявить параметры тела запроса как необязательные, установив значение по умолчанию, равное `None`: -//// tab | Python 3.10+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="17-19" -{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать версию с `Annotated`, если это возможно. - -/// - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} /// note | Заметка @@ -81,21 +31,7 @@ Но вы также можете объявить множество параметров тела запроса, например `item` и `user`: -//// tab | Python 3.10+ - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} В этом случае **FastAPI** заметит, что в функции есть более одного параметра тела (два параметра, которые являются моделями Pydantic). @@ -136,57 +72,7 @@ Но вы можете указать **FastAPI** обрабатывать его, как ещё один ключ тела запроса, используя `Body`: -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} В этом случае, **FastAPI** будет ожидать тело запроса в формате: @@ -226,57 +112,7 @@ q: str | None = None Например: -//// tab | Python 3.10+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="28" -{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="25" -{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *} /// info | Информация @@ -298,57 +134,7 @@ item: Item = Body(embed=True) так же, как в этом примере: -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} В этом случае **FastAPI** будет ожидать тело запроса в формате: diff --git a/docs/ru/docs/tutorial/body-nested-models.md b/docs/ru/docs/tutorial/body-nested-models.md index 9abd4f432..430092892 100644 --- a/docs/ru/docs/tutorial/body-nested-models.md +++ b/docs/ru/docs/tutorial/body-nested-models.md @@ -6,21 +6,7 @@ Вы можете определять атрибут как подтип. Например, тип `list` в Python: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} Это приведёт к тому, что обьект `tags` преобразуется в список, несмотря на то что тип его элементов не объявлен. @@ -34,9 +20,7 @@ Но в версиях Python до 3.9 (начиная с 3.6) сначала вам необходимо импортировать `List` из стандартного модуля `typing` в Python: -```Python hl_lines="1" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### Объявление `list` с указанием типов для вложенных элементов @@ -65,29 +49,7 @@ my_list: List[str] Таким образом, в нашем примере мы можем явно указать тип данных для поля `tags` как "список строк": -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} ## Типы множеств @@ -97,29 +59,7 @@ my_list: List[str] Тогда мы можем обьявить поле `tags` как множество строк: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 14" -{!> ../../docs_src/body_nested_models/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} С помощью этого, даже если вы получите запрос с повторяющимися данными, они будут преобразованы в множество уникальных элементов. @@ -141,57 +81,13 @@ my_list: List[str] Например, мы можем определить модель `Image`: -//// tab | Python 3.10+ - -```Python hl_lines="7-9" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} ### Использование вложенной модели в качестве типа Также мы можем использовать эту модель как тип атрибута: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} Это означает, что **FastAPI** будет ожидать тело запроса, аналогичное этому: @@ -224,29 +120,7 @@ my_list: List[str] Например, так как в модели `Image` у нас есть поле `url`, то мы можем объявить его как тип `HttpUrl` из модуля Pydantic вместо типа `str`: -//// tab | Python 3.10+ - -```Python hl_lines="2 8" -{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} Строка будет проверена на соответствие допустимому URL-адресу и задокументирована в JSON схему / OpenAPI. @@ -254,29 +128,7 @@ my_list: List[str] Вы также можете использовать модели Pydantic в качестве типов вложенных в `list`, `set` и т.д: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} Такая реализация будет ожидать (конвертировать, валидировать, документировать и т.д) JSON-содержимое в следующем формате: @@ -314,29 +166,7 @@ my_list: List[str] Вы можете определять модели с произвольным уровнем вложенности: -//// tab | Python 3.10+ - -```Python hl_lines="7 12 18 21 25" -{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} /// info | Информация @@ -360,21 +190,7 @@ images: list[Image] например так: -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/body_nested_models/tutorial008.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} ## Универсальная поддержка редактора @@ -404,21 +220,7 @@ images: list[Image] В этом случае вы принимаете `dict`, пока у него есть ключи типа `int` со значениями типа `float`: -//// tab | Python 3.9+ - -```Python hl_lines="7" -{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/body_nested_models/tutorial009.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} /// tip | Совет diff --git a/docs/ru/docs/tutorial/body-updates.md b/docs/ru/docs/tutorial/body-updates.md index c80952f70..99f475a41 100644 --- a/docs/ru/docs/tutorial/body-updates.md +++ b/docs/ru/docs/tutorial/body-updates.md @@ -6,29 +6,7 @@ Вы можете использовать функцию `jsonable_encoder` для преобразования входных данных в JSON, так как нередки случаи, когда работать можно только с простыми типами данных (например, для хранения в NoSQL-базе данных). -//// tab | Python 3.10+ - -```Python hl_lines="28-33" -{!> ../../docs_src/body_updates/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *} `PUT` используется для получения данных, которые должны полностью заменить существующие данные. @@ -74,29 +52,7 @@ В результате будет сгенерирован словарь, содержащий только те данные, которые были заданы при создании модели `item`, без учета значений по умолчанию. Затем вы можете использовать это для создания словаря только с теми данными, которые были установлены (отправлены в запросе), опуская значения по умолчанию: -//// tab | Python 3.10+ - -```Python hl_lines="32" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *} ### Использование параметра `update` в Pydantic @@ -104,29 +60,7 @@ Например, `stored_item_model.copy(update=update_data)`: -//// tab | Python 3.10+ - -```Python hl_lines="33" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *} ### Кратко о частичном обновлении @@ -143,29 +77,7 @@ * Сохранить данные в своей БД. * Вернуть обновленную модель. -//// tab | Python 3.10+ - -```Python hl_lines="28-35" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *} /// tip | Подсказка diff --git a/docs/ru/docs/tutorial/body.md b/docs/ru/docs/tutorial/body.md index 62927f0d1..2c9110226 100644 --- a/docs/ru/docs/tutorial/body.md +++ b/docs/ru/docs/tutorial/body.md @@ -22,9 +22,7 @@ Первое, что вам необходимо сделать, это импортировать `BaseModel` из пакета `pydantic`: -```Python hl_lines="4" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[4] *} ## Создание вашей собственной модели @@ -32,9 +30,7 @@ Используйте аннотации типов Python для всех атрибутов: -```Python hl_lines="7-11" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[7:11] *} Также как и при описании параметров запроса, когда атрибут модели имеет значение по умолчанию, он является необязательным. Иначе он обязателен. Используйте `None`, чтобы сделать его необязательным без использования конкретных значений по умолчанию. @@ -62,9 +58,7 @@ Чтобы добавить параметр к вашему *обработчику*, объявите его также, как вы объявляли параметры пути или параметры запроса: -```Python hl_lines="18" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[18] *} ...и укажите созданную модель в качестве типа параметра, `Item`. @@ -131,9 +125,7 @@ Внутри функции вам доступны все атрибуты объекта модели напрямую: -```Python hl_lines="21" -{!../../docs_src/body/tutorial002.py!} -``` +{* ../../docs_src/body/tutorial002.py hl[21] *} ## Тело запроса + параметры пути @@ -141,9 +133,7 @@ **FastAPI** распознает, какие параметры функции соответствуют параметрам пути и должны быть **получены из пути**, а какие параметры функции, объявленные как модели Pydantic, должны быть **получены из тела запроса**. -```Python hl_lines="17-18" -{!../../docs_src/body/tutorial003.py!} -``` +{* ../../docs_src/body/tutorial003.py hl[17:18] *} ## Тело запроса + параметры пути + параметры запроса @@ -151,9 +141,7 @@ **FastAPI** распознает каждый из них и возьмет данные из правильного источника. -```Python hl_lines="18" -{!../../docs_src/body/tutorial004.py!} -``` +{* ../../docs_src/body/tutorial004.py hl[18] *} Параметры функции распознаются следующим образом: diff --git a/docs/ru/docs/tutorial/cookie-params.md b/docs/ru/docs/tutorial/cookie-params.md index 88533f7f8..d1ed943d7 100644 --- a/docs/ru/docs/tutorial/cookie-params.md +++ b/docs/ru/docs/tutorial/cookie-params.md @@ -6,21 +6,7 @@ Сначала импортируйте `Cookie`: -//// tab | Python 3.10+ - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_py310.py hl[1] *} ## Объявление параметров `Cookie` @@ -28,21 +14,7 @@ Первое значение - это значение по умолчанию, вы можете передать все дополнительные параметры проверки или аннотации: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_py310.py hl[7] *} /// note | Технические детали diff --git a/docs/ru/docs/tutorial/cors.md b/docs/ru/docs/tutorial/cors.md index 622cd5a98..e8bf04576 100644 --- a/docs/ru/docs/tutorial/cors.md +++ b/docs/ru/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * Отдельных HTTP-методов (`POST`, `PUT`) или всех вместе, используя `"*"`. * Отдельных HTTP-заголовков или всех вместе, используя `"*"`. -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} `CORSMiddleware` использует для параметров "запрещающие" значения по умолчанию, поэтому вам нужно явным образом разрешить использование отдельных источников, методов или заголовков, чтобы браузеры могли использовать их в кросс-доменном контексте. diff --git a/docs/ru/docs/tutorial/debugging.md b/docs/ru/docs/tutorial/debugging.md index 0feeaa20c..05806f087 100644 --- a/docs/ru/docs/tutorial/debugging.md +++ b/docs/ru/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ В вашем FastAPI приложении, импортируйте и вызовите `uvicorn` напрямую: -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### Описание `__name__ == "__main__"` diff --git a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md index 486ff9ea9..8037872b9 100644 --- a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,57 +6,7 @@ В предыдущем примере мы возвращали `словарь` из нашей зависимости: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *} Но затем мы получаем `словарь` в параметре `commons` *функции операции пути*. И мы знаем, что редакторы не могут обеспечить достаточную поддержку для `словаря`, поскольку они не могут знать их ключи и типы значений. @@ -117,165 +67,15 @@ fluffy = Cat(name="Mr Fluffy") Теперь мы можем изменить зависимость `common_parameters`, указанную выше, на класс `CommonQueryParams`: -//// tab | Python 3.10+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="12-16" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9-13" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *} Обратите внимание на метод `__init__`, используемый для создания экземпляра класса: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *} ...имеет те же параметры, что и ранее используемая функция `common_parameters`: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="6" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *} Эти параметры и будут использоваться **FastAPI** для "решения" зависимости. @@ -291,57 +91,7 @@ fluffy = Cat(name="Mr Fluffy") Теперь вы можете объявить свою зависимость, используя этот класс. -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *} **FastAPI** вызывает класс `CommonQueryParams`. При этом создается "экземпляр" этого класса, который будет передан в качестве параметра `commons` в вашу функцию. @@ -435,57 +185,7 @@ commons = Depends(CommonQueryParams) ...как тут: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *} Но объявление типа приветствуется, так как в этом случае ваш редактор будет знать, что будет передано в качестве параметра `commons`, и тогда он сможет помочь вам с автодополнением, проверкой типов и т.д: @@ -572,57 +272,7 @@ commons: CommonQueryParams = Depends() Аналогичный пример будет выглядеть следующим образом: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *} ...и **FastAPI** будет знать, что делать. diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 305ce46cb..f9b9dec25 100644 --- a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,35 +14,7 @@ Это должен быть `list` состоящий из `Depends()`: -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 без Annotated - -/// подсказка - -Рекомендуется использовать версию с Annotated, если возможно. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *} Зависимости из dependencies выполнятся так же, как и обычные зависимости. Но их значения (если они были) не будут переданы в *функцию операции пути*. @@ -72,69 +44,13 @@ Они могут объявлять требования к запросу (например заголовки) или другие подзависимости: -//// tab | Python 3.9+ - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7 12" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 без Annotated - -/// подсказка - -Рекомендуется использовать версию с Annotated, если возможно. - -/// - -```Python hl_lines="6 11" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *} ### Вызов исключений Зависимости из dependencies могут вызывать исключения с помощью `raise`, как и обычные зависимости: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 без Annotated - -/// подсказка - -Рекомендуется использовать версию с Annotated, если возможно. - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *} ### Возвращаемые значения @@ -142,35 +58,7 @@ Таким образом, вы можете переиспользовать обычную зависимость (возвращающую значение), которую вы уже используете где-то в другом месте, и хотя значение не будет использоваться, зависимость будет выполнена: -//// tab | Python 3.9+ - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 без Annotated - -/// подсказка - -Рекомендуется использовать версию с Annotated, если возможно. - -/// - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *} ## Dependencies для группы *операций путей* diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md index 83f8ec0d2..e64f6777c 100644 --- a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md @@ -29,21 +29,15 @@ FastAPI поддерживает зависимости, которые выпо Перед созданием ответа будет выполнен только код до и включая `yield`. -```Python hl_lines="2-4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *} Полученное значение и есть то, что будет внедрено в функцию операции пути и другие зависимости: -```Python hl_lines="4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} Код, следующий за оператором `yield`, выполняется после доставки ответа: -```Python hl_lines="5-6" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *} /// tip | Подсказка @@ -63,9 +57,7 @@ FastAPI поддерживает зависимости, которые выпо Таким же образом можно использовать `finally`, чтобы убедиться, что обязательные шаги при выходе выполнены, независимо от того, было ли исключение или нет. -```Python hl_lines="3 5" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *} ## Подзависимости с `yield` @@ -75,35 +67,7 @@ FastAPI поддерживает зависимости, которые выпо Например, `dependency_c` может иметь зависимость от `dependency_b`, а `dependency_b` от `dependency_a`: -//// tab | Python 3.9+ - -```Python hl_lines="6 14 22" -{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="5 13 21" -{!> ../../docs_src/dependencies/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="4 12 20" -{!> ../../docs_src/dependencies/tutorial008.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *} И все они могут использовать `yield`. @@ -111,35 +75,7 @@ FastAPI поддерживает зависимости, которые выпо И, в свою очередь, `dependency_b` нуждается в том, чтобы значение из `dependency_a` (здесь `dep_a`) было доступно для ее завершающего кода. -//// tab | Python 3.9+ - -```Python hl_lines="18-19 26-27" -{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="17-18 25-26" -{!> ../../docs_src/dependencies/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="16-17 24-25" -{!> ../../docs_src/dependencies/tutorial008.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *} Точно так же можно иметь часть зависимостей с `yield`, часть с `return`, и какие-то из них могут зависеть друг от друга. @@ -303,9 +239,7 @@ with open("./somefile.txt") as f: Вы также можете использовать их внутри зависимостей **FastAPI** с `yield`, используя операторы `with` или `async with` внутри функции зависимости: -```Python hl_lines="1-9 13" -{!../../docs_src/dependencies/tutorial010.py!} -``` +{* ../../docs_src/dependencies/tutorial010.py hl[1:9,13] *} /// tip | Подсказка diff --git a/docs/ru/docs/tutorial/dependencies/global-dependencies.md b/docs/ru/docs/tutorial/dependencies/global-dependencies.md index a4dfeb8ac..5d2e70f6e 100644 --- a/docs/ru/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/global-dependencies.md @@ -6,35 +6,7 @@ В этом случае они будут применяться ко всем *операциям пути* в приложении: -//// tab | Python 3.9+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | Подсказка - -Рекомендуется использовать 'Annotated' версию, если это возможно. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/dependencies/tutorial012.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[16] *} Все способы [добавления зависимостей в *декораторах операций пути*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} по-прежнему применимы, но в данном случае зависимости применяются ко всем *операциям пути* приложения. diff --git a/docs/ru/docs/tutorial/dependencies/index.md b/docs/ru/docs/tutorial/dependencies/index.md index b6cf7c780..28790bd5a 100644 --- a/docs/ru/docs/tutorial/dependencies/index.md +++ b/docs/ru/docs/tutorial/dependencies/index.md @@ -29,57 +29,7 @@ Давайте для начала сфокусируемся на зависимостях. Это просто функция, которая может принимать все те же параметры, что и *функции обработки пути*: -//// 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 | Подсказка - -Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Подсказка - -Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - -/// - -```Python hl_lines="8-11" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *} **И всё.** @@ -111,113 +61,13 @@ ### 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 | Подсказка - -Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Подсказка - -Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} ### Объявите зависимость в "зависимом" Точно так же, как вы использовали `Body`, `Query` и т.д. с вашей *функцией обработки пути* для параметров, используйте `Depends` с новым параметром: -//// 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 | Подсказка - -Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - -/// - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Подсказка - -Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - -/// - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} `Depends` работает немного иначе. Вы передаёте в `Depends` одиночный параметр, который будет похож на функцию. @@ -270,29 +120,7 @@ commons: Annotated[dict, Depends(common_parameters)] Но потому что мы используем `Annotated`, мы можем хранить `Annotated` значение в переменной и использовать его в нескольких местах: -//// 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 | Подсказка diff --git a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md index 0e8cb20e7..5e8de0c4a 100644 --- a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md @@ -10,57 +10,7 @@ Можно создать первую зависимость следующим образом: -//// tab | Python 3.10+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="9-10" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.6 без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *} Она объявляет необязательный параметр запроса `q` как строку, а затем возвращает его. @@ -70,57 +20,7 @@ Затем можно создать еще одну функцию зависимости, которая в то же время содержит внутри себя первую зависимость (таким образом, она тоже является "зависимой"): -//// tab | Python 3.10+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="14" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.6 без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *} Остановимся на объявленных параметрах: @@ -133,57 +33,7 @@ Затем мы можем использовать зависимость вместе с: -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="24" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.6 без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *} /// info | Дополнительная информация diff --git a/docs/ru/docs/tutorial/encoder.md b/docs/ru/docs/tutorial/encoder.md index 523644ac8..4ed5039b3 100644 --- a/docs/ru/docs/tutorial/encoder.md +++ b/docs/ru/docs/tutorial/encoder.md @@ -20,21 +20,7 @@ Она принимает объект, например, модель Pydantic, и возвращает его версию, совместимую с JSON: -//// tab | Python 3.10+ - -```Python hl_lines="4 21" -{!> ../../docs_src/encoder/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="5 22" -{!> ../../docs_src/encoder/tutorial001.py!} -``` - -//// +{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *} В данном примере она преобразует Pydantic модель в `dict`, а `datetime` - в `str`. diff --git a/docs/ru/docs/tutorial/extra-data-types.md b/docs/ru/docs/tutorial/extra-data-types.md index 82cb0ff7a..6d6d4aa9f 100644 --- a/docs/ru/docs/tutorial/extra-data-types.md +++ b/docs/ru/docs/tutorial/extra-data-types.md @@ -55,36 +55,8 @@ Вот пример *операции пути* с параметрами, который демонстрирует некоторые из вышеперечисленных типов. -//// tab | Python 3.8 и выше - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// - -//// tab | Python 3.10 и выше - -```Python hl_lines="1 2 11-15" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001.py hl[1,3,12:16] *} Обратите внимание, что параметры внутри функции имеют свой естественный тип данных, и вы, например, можете выполнять обычные манипуляции с датами, такие как: -//// tab | Python 3.8 и выше - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// - -//// tab | Python 3.10 и выше - -```Python hl_lines="17-18" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001.py hl[18:19] *} diff --git a/docs/ru/docs/tutorial/extra-models.md b/docs/ru/docs/tutorial/extra-models.md index 241f70779..5b51aa402 100644 --- a/docs/ru/docs/tutorial/extra-models.md +++ b/docs/ru/docs/tutorial/extra-models.md @@ -20,21 +20,7 @@ Ниже изложена основная идея того, как могут выглядеть эти модели с полями для паролей, а также описаны места, где они используются: -//// tab | Python 3.10+ - -```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../docs_src/extra_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../docs_src/extra_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *} ### Про `**user_in.dict()` @@ -168,21 +154,7 @@ UserInDB( В этом случае мы можем определить только различия между моделями (с `password` в чистом виде, с `hashed_password` и без пароля): -//// tab | Python 3.10+ - -```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../docs_src/extra_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../docs_src/extra_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *} ## `Union` или `anyOf` @@ -198,21 +170,7 @@ UserInDB( /// -//// tab | Python 3.10+ - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *} ### `Union` в Python 3.10 @@ -234,21 +192,7 @@ some_variable: PlaneItem | CarItem Для этого используйте `typing.List` из стандартной библиотеки Python (или просто `list` в Python 3.9 и выше): -//// tab | Python 3.9+ - -```Python hl_lines="18" -{!> ../../docs_src/extra_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 20" -{!> ../../docs_src/extra_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *} ## Ответ с произвольным `dict` @@ -258,21 +202,7 @@ some_variable: PlaneItem | CarItem В этом случае вы можете использовать `typing.Dict` (или просто `dict` в Python 3.9 и выше): -//// tab | Python 3.9+ - -```Python hl_lines="6" -{!> ../../docs_src/extra_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 8" -{!> ../../docs_src/extra_models/tutorial005.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *} ## Резюме diff --git a/docs/ru/docs/tutorial/first-steps.md b/docs/ru/docs/tutorial/first-steps.md index 309f26c4f..cb3d19a71 100644 --- a/docs/ru/docs/tutorial/first-steps.md +++ b/docs/ru/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Самый простой FastAPI файл может выглядеть так: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Скопируйте в файл `main.py`. @@ -133,9 +131,7 @@ OpenAPI описывает схему API. Эта схема содержит о ### Шаг 1: импортируйте `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` это класс в Python, который предоставляет всю функциональность для API. @@ -149,9 +145,7 @@ OpenAPI описывает схему API. Эта схема содержит о ### Шаг 2: создайте экземпляр `FastAPI` -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} Переменная `app` является экземпляром класса `FastAPI`. @@ -171,9 +165,7 @@ $ uvicorn main:app --reload Если создать такое приложение: -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} И поместить его в `main.py`, тогда вызов `uvicorn` будет таким: @@ -250,9 +242,7 @@ https://example.com/items/foo #### Определите *декоратор операции пути (path operation decorator)* -```Python hl_lines="6" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} Декоратор `@app.get("/")` указывает **FastAPI**, что функция, прямо под ним, отвечает за обработку запросов, поступающих по адресу: @@ -306,9 +296,7 @@ https://example.com/items/foo * **операция**: `get`. * **функция**: функция ниже "декоратора" (ниже `@app.get("/")`). -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} Это обычная Python функция. @@ -320,9 +308,7 @@ https://example.com/items/foo Вы также можете определить ее как обычную функцию вместо `async def`: -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} /// note | Технические детали @@ -332,9 +318,7 @@ https://example.com/items/foo ### Шаг 5: верните результат -```Python hl_lines="8" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} Вы можете вернуть `dict`, `list`, отдельные значения `str`, `int` и т.д. diff --git a/docs/ru/docs/tutorial/handling-errors.md b/docs/ru/docs/tutorial/handling-errors.md index a06644376..c596abe1f 100644 --- a/docs/ru/docs/tutorial/handling-errors.md +++ b/docs/ru/docs/tutorial/handling-errors.md @@ -25,9 +25,7 @@ ### Импортируйте `HTTPException` -```Python hl_lines="1" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} ### Вызовите `HTTPException` в своем коде @@ -41,9 +39,7 @@ В данном примере, когда клиент запрашивает элемент по несуществующему ID, возникает исключение со статус-кодом `404`: -```Python hl_lines="11" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} ### Возвращаемый ответ @@ -81,9 +77,7 @@ Но в случае, если это необходимо для продвинутого сценария, можно добавить пользовательские заголовки: -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial002.py!} -``` +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} ## Установка пользовательских обработчиков исключений @@ -95,9 +89,7 @@ Можно добавить собственный обработчик исключений с помощью `@app.exception_handler()`: -```Python hl_lines="5-7 13-18 24" -{!../../docs_src/handling_errors/tutorial003.py!} -``` +{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *} Здесь, если запросить `/unicorns/yolo`, то *операция пути* вызовет `UnicornException`. @@ -135,9 +127,7 @@ Обработчик исключения получит объект `Request` и исключение. -```Python hl_lines="2 14-16" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *} Теперь, если перейти к `/items/foo`, то вместо стандартной JSON-ошибки с: @@ -188,9 +178,7 @@ path -> item_id Например, для этих ошибок можно вернуть обычный текстовый ответ вместо JSON: -```Python hl_lines="3-4 9-11 22" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *} /// note | Технические детали @@ -206,9 +194,7 @@ path -> item_id Вы можете использовать его при разработке приложения для регистрации тела и его отладки, возврата пользователю и т.д. -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial005.py!} -``` +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} Теперь попробуйте отправить недействительный элемент, например: @@ -266,8 +252,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException Если вы хотите использовать исключение вместе с теми же обработчиками исключений по умолчанию из **FastAPI**, вы можете импортировать и повторно использовать обработчики исключений по умолчанию из `fastapi.exception_handlers`: -```Python hl_lines="2-5 15 21" -{!../../docs_src/handling_errors/tutorial006.py!} -``` +{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *} В этом примере вы просто `выводите в терминал` ошибку с очень выразительным сообщением, но идея вам понятна. Вы можете использовать исключение, а затем просто повторно использовать стандартные обработчики исключений. diff --git a/docs/ru/docs/tutorial/header-params.md b/docs/ru/docs/tutorial/header-params.md index 904709b04..e892cfc07 100644 --- a/docs/ru/docs/tutorial/header-params.md +++ b/docs/ru/docs/tutorial/header-params.md @@ -6,57 +6,7 @@ Сперва импортируйте `Header`: -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[3] *} ## Объявление параметров `Header` @@ -64,57 +14,7 @@ Первое значение является значением по умолчанию, вы можете передать все дополнительные параметры валидации или аннотации: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *} /// note | Технические детали @@ -146,57 +46,7 @@ Если по какой-либо причине вам необходимо отключить автоматическое преобразование подчеркиваний в дефисы, установите для параметра `convert_underscores` в `Header` значение `False`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/header_params/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/header_params/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/header_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial002_an_py310.py hl[10] *} /// warning | Внимание @@ -214,71 +64,7 @@ Например, чтобы объявить заголовок `X-Token`, который может появляться более одного раза, вы можете написать: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial003_an_py310.py hl[9] *} Если вы взаимодействуете с этой *операцией пути*, отправляя два HTTP-заголовка, таких как: diff --git a/docs/ru/docs/tutorial/metadata.md b/docs/ru/docs/tutorial/metadata.md index ae739a043..f07073508 100644 --- a/docs/ru/docs/tutorial/metadata.md +++ b/docs/ru/docs/tutorial/metadata.md @@ -17,9 +17,7 @@ Вы можете задать их следующим образом: -```Python hl_lines="3-16 19-31" -{!../../docs_src/metadata/tutorial001.py!} -``` +{* ../../docs_src/metadata/tutorial001.py hl[3:16,19:31] *} /// tip | Подсказка @@ -51,9 +49,7 @@ Создайте метаданные для ваших тегов и передайте их в параметре `openapi_tags`: -```Python hl_lines="3-16 18" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} Помните, что вы можете использовать Markdown внутри описания, к примеру "login" будет отображен жирным шрифтом (**login**) и "fancy" будет отображаться курсивом (_fancy_). @@ -66,9 +62,7 @@ ### Используйте собственные теги Используйте параметр `tags` с вашими *операциями пути* (и `APIRouter`ами), чтобы присвоить им различные теги: -```Python hl_lines="21 26" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} /// info | Дополнительная информация @@ -96,9 +90,7 @@ К примеру, чтобы задать её отображение по адресу `/api/v1/openapi.json`: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial002.py!} -``` +{* ../../docs_src/metadata/tutorial002.py hl[3] *} Если вы хотите отключить схему OpenAPI полностью, вы можете задать `openapi_url=None`, это также отключит пользовательские интерфейсы документации, которые его использует. @@ -115,6 +107,4 @@ К примеру, чтобы задать отображение Swagger UI по адресу `/documentation` и отключить ReDoc: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial003.py!} -``` +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/ru/docs/tutorial/path-operation-configuration.md b/docs/ru/docs/tutorial/path-operation-configuration.md index ac12b7084..af471ca69 100644 --- a/docs/ru/docs/tutorial/path-operation-configuration.md +++ b/docs/ru/docs/tutorial/path-operation-configuration.md @@ -16,29 +16,7 @@ Но если вы не помните, для чего нужен каждый числовой код, вы можете использовать сокращенные константы в параметре `status`: -//// tab | Python 3.10+ - -```Python hl_lines="1 15" -{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *} Этот код состояния будет использован в ответе и будет добавлен в схему OpenAPI. @@ -54,29 +32,7 @@ Вы можете добавлять теги к вашим *операциям пути*, добавив параметр `tags` с `list` заполненным `str`-значениями (обычно в нём только одна строка): -//// tab | Python 3.10+ - -```Python hl_lines="15 20 25" -{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *} Они будут добавлены в схему OpenAPI и будут использованы в автоматической документации интерфейса: @@ -90,37 +46,13 @@ **FastAPI** поддерживает это так же, как и в случае с обычными строками: -```Python hl_lines="1 8-10 13 18" -{!../../docs_src/path_operation_configuration/tutorial002b.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *} ## Краткое и развёрнутое содержание Вы можете добавить параметры `summary` и `description`: -//// tab | Python 3.10+ - -```Python hl_lines="18-19" -{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[18:19] *} ## Описание из строк документации @@ -128,29 +60,7 @@ Вы можете использовать Markdown в строке документации, и он будет интерпретирован и отображён корректно (с учетом отступа в строке документации). -//// tab | Python 3.10+ - -```Python hl_lines="17-25" -{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *} Он будет использован в интерактивной документации: @@ -160,29 +70,7 @@ Вы можете указать описание ответа с помощью параметра `response_description`: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[19] *} /// info | Дополнительная информация @@ -204,9 +92,7 @@ OpenAPI указывает, что каждой *операции пути* не Если вам необходимо пометить *операцию пути* как устаревшую, при этом не удаляя её, передайте параметр `deprecated`: -```Python hl_lines="16" -{!../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} Он будет четко помечен как устаревший в интерактивной документации: diff --git a/docs/ru/docs/tutorial/path-params-numeric-validations.md b/docs/ru/docs/tutorial/path-params-numeric-validations.md index ed19576a2..dca267f78 100644 --- a/docs/ru/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ru/docs/tutorial/path-params-numeric-validations.md @@ -6,57 +6,7 @@ Сначала импортируйте `Path` из `fastapi`, а также импортируйте `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+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```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 @@ Например, чтобы указать значение метаданных `title` для path-параметра `item_id`, вы можете написать: -//// 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+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```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 | Примечание @@ -174,21 +74,7 @@ Path-параметр всегда является обязательным, п Но имейте в виду, что если вы используете `Annotated`, вы не столкнётесь с этой проблемой, так как вы не используете `Query()` или `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] *} ## Задайте нужный вам порядок параметров, полезные приёмы @@ -213,29 +99,13 @@ Path-параметр всегда является обязательным, п Python не будет ничего делать с `*`, но он будет знать, что все следующие параметры являются именованными аргументами (парами ключ-значение), также известными как kwargs, даже если у них нет значений по умолчанию. -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ### Лучше с `Annotated` Имейте в виду, что если вы используете `Annotated`, то, поскольку вы не используете значений по умолчанию для параметров функции, то у вас не возникнет подобной проблемы и вам не придётся использовать `*`. -//// 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] *} ## Валидация числовых данных: больше или равно @@ -243,35 +113,7 @@ Python не будет ничего делать с `*`, но он будет з В этом примере при указании `ge=1`, параметр `item_id` должен быть больше или равен `1` ("`g`reater 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+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *} ## Валидация числовых данных: больше и меньше или равно @@ -280,35 +122,7 @@ Python не будет ничего делать с `*`, но он будет з * `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+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *} ## Валидация числовых данных: числа с плавающей точкой, больше и меньше @@ -320,35 +134,7 @@ Python не будет ничего делать с `*`, но он будет з То же самое справедливо и для 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+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *} ## Резюме diff --git a/docs/ru/docs/tutorial/path-params.md b/docs/ru/docs/tutorial/path-params.md index ba23ba5ea..5c2d82a65 100644 --- a/docs/ru/docs/tutorial/path-params.md +++ b/docs/ru/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ Вы можете определить "параметры" или "переменные" пути, используя синтаксис форматированных строк Python: -```Python hl_lines="6-7" -{!../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} Значение параметра пути `item_id` будет передано в функцию в качестве аргумента `item_id`. @@ -18,9 +16,7 @@ Вы можете объявить тип параметра пути в функции, используя стандартные аннотации типов Python. -```Python hl_lines="7" -{!../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} Здесь, `item_id` объявлен типом `int`. @@ -122,17 +118,13 @@ Поскольку *операции пути* выполняются в порядке их объявления, необходимо, чтобы путь для `/users/me` был объявлен раньше, чем путь для `/users/{user_id}`: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} Иначе путь для `/users/{user_id}` также будет соответствовать `/users/me`, "подразумевая", что он получает параметр `user_id` со значением `"me"`. Аналогично, вы не можете переопределить операцию с путем: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003b.py!} -``` +{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *} Первый будет выполняться всегда, так как путь совпадает первым. @@ -148,9 +140,7 @@ Затем создайте атрибуты класса с фиксированными допустимыми значениями: -```Python hl_lines="1 6-9" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} /// info | Дополнительная информация @@ -168,9 +158,7 @@ Определите *параметр пути*, используя в аннотации типа класс перечисления (`ModelName`), созданный ранее: -```Python hl_lines="16" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### Проверьте документацию @@ -186,17 +174,13 @@ Вы можете сравнить это значение с *элементом перечисления* класса `ModelName`: -```Python hl_lines="17" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### Получение *значения перечисления* Можно получить фактическое значение (в данном случае - `str`) с помощью `model_name.value` или в общем случае `your_enum_member.value`: -```Python hl_lines="20" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} /// tip | Подсказка @@ -210,9 +194,7 @@ Они будут преобразованы в соответствующие значения (в данном случае - строки) перед их возвратом клиенту: -```Python hl_lines="18 21 23" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} Вы отправите клиенту такой JSON-ответ: ```JSON @@ -250,9 +232,7 @@ OpenAPI не поддерживает способов объявления *п Можете использовать так: -```Python hl_lines="6" -{!../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} /// tip | Подсказка diff --git a/docs/ru/docs/tutorial/query-params-str-validations.md b/docs/ru/docs/tutorial/query-params-str-validations.md index f76570ce8..32a98ff22 100644 --- a/docs/ru/docs/tutorial/query-params-str-validations.md +++ b/docs/ru/docs/tutorial/query-params-str-validations.md @@ -4,21 +4,7 @@ Давайте рассмотрим следующий пример: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *} Query-параметр `q` имеет тип `Union[str, None]` (или `str | None` в Python 3.10). Это означает, что входной параметр будет типа `str`, но может быть и `None`. Ещё параметр имеет значение по умолчанию `None`, из-за чего FastAPI определит параметр как необязательный. @@ -113,21 +99,7 @@ q: Annotated[Union[str, None]] = None Теперь, когда у нас есть `Annotated`, где мы можем добавить больше метаданных, добавим `Query` со значением параметра `max_length` равным 50: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[9] *} Обратите внимание, что значение по умолчанию всё ещё `None`, так что параметр остаётся необязательным. @@ -151,21 +123,7 @@ q: Annotated[Union[str, None]] = None Вот как вы могли бы использовать `Query()` в качестве значения по умолчанию параметра вашей функции, установив для параметра `max_length` значение 50: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002_py310.py hl[7] *} В таком случае (без использования `Annotated`), мы заменили значение по умолчанию с `None` на `Query()` в функции. Теперь нам нужно установить значение по умолчанию для query-параметра `Query(default=None)`, что необходимо для тех же целей, как когда ранее просто указывалось значение по умолчанию (по крайней мере, для FastAPI). @@ -265,113 +223,13 @@ q: str = Query(default="rick") Вы также можете добавить параметр `min_length`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial003_an_py310.py hl[10] *} ## Регулярные выражения Вы можете определить регулярное выражение, которому должен соответствовать параметр: -//// tab | Python 3.10+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/query_params_str_validations/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *} Данное регулярное выражение проверяет, что полученное значение параметра: @@ -389,35 +247,7 @@ q: str = Query(default="rick") Например, вы хотите для параметра запроса `q` указать, что он должен состоять минимум из 3 символов (`min_length=3`) и иметь значение по умолчанию `"fixedquery"`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial005.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *} /// note | Технические детали @@ -459,77 +289,13 @@ q: Union[str, None] = Query(default=None, min_length=3) В таком случае, чтобы сделать query-параметр `Query` обязательным, вы можете просто не указывать значение по умолчанию: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006.py!} -``` - -/// tip | Подсказка - -Обратите внимание, что даже когда `Query()` используется как значение по умолчанию для параметра функции, мы не передаём `default=None` в `Query()`. - -Лучше будет использовать версию с `Annotated`. 😉 - -/// - -//// +{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} ### Обязательный параметр с Ellipsis (`...`) Альтернативный способ указать обязательность параметра запроса - это указать параметр `default` через многоточие `...`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial006b_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006b.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py hl[9] *} /// info | Дополнительная информация @@ -547,57 +313,7 @@ q: Union[str, None] = Query(default=None, min_length=3) Чтобы этого добиться, вам нужно определить `None` как валидный тип для параметра запроса, но также указать `default=...`: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} /// tip | Подсказка @@ -609,35 +325,7 @@ Pydantic, мощь которого используется в FastAPI для Если вас смущает `...`, вы можете использовать `Required` из Pydantic: -//// tab | Python 3.9+ - -```Python hl_lines="4 10" -{!> ../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="2 9" -{!> ../../docs_src/query_params_str_validations/tutorial006d_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="2 8" -{!> ../../docs_src/query_params_str_validations/tutorial006d.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006d_an_py39.py hl[4,10] *} /// tip | Подсказка @@ -651,71 +339,7 @@ Pydantic, мощь которого используется в FastAPI для Например, query-параметр `q` может быть указан в URL несколько раз. И если вы ожидаете такой формат запроса, то можете указать это следующим образом: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} -``` - -//// - -//// tab | Python 3.9+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *} Затем, получив такой URL: @@ -750,49 +374,7 @@ http://localhost:8000/items/?q=foo&q=bar Вы также можете указать тип `list` со списком значений по умолчанию на случай, если вам их не предоставят: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.9+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *} Если вы перейдёте по ссылке: @@ -815,35 +397,7 @@ http://localhost:8000/items/ Вы также можете использовать `list` напрямую вместо `List[str]` (или `list[str]` в Python 3.9+): -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial013_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial013.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *} /// note | Технические детали @@ -869,111 +423,11 @@ http://localhost:8000/items/ Вы можете указать название query-параметра, используя параметр `title`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *} Добавить описание, используя параметр `description`: -//// tab | Python 3.10+ - -```Python hl_lines="14" -{!> ../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/query_params_str_validations/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/query_params_str_validations/tutorial008.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *} ## Псевдонимы параметров @@ -993,57 +447,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Тогда вы можете объявить `псевдоним`, и этот псевдоним будет использоваться для поиска значения параметра запроса: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial009_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *} ## Устаревшие параметры @@ -1053,57 +457,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Тогда для `Query` укажите параметр `deprecated=True`: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/query_params_str_validations/tutorial010_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="16" -{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="18" -{!> ../../docs_src/query_params_str_validations/tutorial010.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *} В документации это будет отображено следующим образом: @@ -1113,57 +467,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Чтобы исключить query-параметр из генерируемой OpenAPI схемы (а также из системы автоматической генерации документации), укажите в `Query` параметр `include_in_schema=False`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *} ## Резюме diff --git a/docs/ru/docs/tutorial/query-params.md b/docs/ru/docs/tutorial/query-params.md index 2c697224c..547d9831d 100644 --- a/docs/ru/docs/tutorial/query-params.md +++ b/docs/ru/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ Когда вы объявляете параметры функции, которые не являются параметрами пути, они автоматически интерпретируются как "query"-параметры. -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} Query-параметры представляют из себя набор пар ключ-значение, которые идут после знака `?` в URL-адресе, разделенные символами `&`. @@ -63,21 +61,7 @@ http://127.0.0.1:8000/items/?skip=20 Аналогично, вы можете объявлять необязательные query-параметры, установив их значение по умолчанию, равное `None`: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} В этом случае, параметр `q` будет не обязательным и будет иметь значение `None` по умолчанию. @@ -91,21 +75,7 @@ http://127.0.0.1:8000/items/?skip=20 Вы также можете объявлять параметры с типом `bool`, которые будут преобразованы соответственно: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} В этом случае, если вы сделаете запрос: @@ -148,21 +118,7 @@ http://127.0.0.1:8000/items/foo?short=yes Они будут обнаружены по именам: -//// tab | Python 3.10+ - -```Python hl_lines="6 8" -{!> ../../docs_src/query_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 10" -{!> ../../docs_src/query_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Обязательные query-параметры @@ -172,9 +128,7 @@ http://127.0.0.1:8000/items/foo?short=yes Но если вы хотите сделать query-параметр обязательным, вы можете просто не указывать значение по умолчанию: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Здесь параметр запроса `needy` является обязательным параметром с типом данных `str`. @@ -218,21 +172,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Конечно, вы можете определить некоторые параметры как обязательные, некоторые - со значением по умполчанию, а некоторые - полностью необязательные: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params/tutorial006.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} В этом примере, у нас есть 3 параметра запроса: diff --git a/docs/ru/docs/tutorial/request-files.md b/docs/ru/docs/tutorial/request-files.md index 836d6efed..2cfa4e1dc 100644 --- a/docs/ru/docs/tutorial/request-files.md +++ b/docs/ru/docs/tutorial/request-files.md @@ -16,69 +16,13 @@ Импортируйте `File` и `UploadFile` из модуля `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} ## Определите параметры `File` Создайте параметры `File` так же, как вы это делаете для `Body` или `Form`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="8" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} /// info | Дополнительная информация @@ -106,35 +50,7 @@ Определите параметр файла с типом `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="13" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} Использование `UploadFile` имеет ряд преимуществ перед `bytes`: @@ -217,91 +133,13 @@ contents = myfile.file.read() Вы можете сделать загрузку файла необязательной, используя стандартные аннотации типов и установив значение по умолчанию `None`: -//// tab | Python 3.10+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="10 18" -{!> ../../docs_src/request_files/tutorial001_02_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="7 15" -{!> ../../docs_src/request_files/tutorial001_02_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} ## `UploadFile` с дополнительными метаданными Вы также можете использовать `File()` вместе с `UploadFile`, например, для установки дополнительных метаданных: -//// tab | Python 3.9+ - -```Python hl_lines="9 15" -{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="8 14" -{!> ../../docs_src/request_files/tutorial001_03_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="7 13" -{!> ../../docs_src/request_files/tutorial001_03.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} ## Загрузка нескольких файлов @@ -311,49 +149,7 @@ contents = myfile.file.read() Для этого необходимо объявить список `bytes` или `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="11 16" -{!> ../../docs_src/request_files/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.9+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/request_files/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`. @@ -369,49 +165,7 @@ contents = myfile.file.read() Так же, как и раньше, вы можете использовать `File()` для задания дополнительных параметров, даже для `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="11 18-20" -{!> ../../docs_src/request_files/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="12 19-21" -{!> ../../docs_src/request_files/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.9+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="9 16" -{!> ../../docs_src/request_files/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="11 18" -{!> ../../docs_src/request_files/tutorial003.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} ## Резюме diff --git a/docs/ru/docs/tutorial/request-forms-and-files.md b/docs/ru/docs/tutorial/request-forms-and-files.md index fd98ec953..116c0cdb1 100644 --- a/docs/ru/docs/tutorial/request-forms-and-files.md +++ b/docs/ru/docs/tutorial/request-forms-and-files.md @@ -12,69 +12,13 @@ ## Импортируйте `File` и `Form` -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms_and_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *} ## Определите параметры `File` и `Form` Создайте параметры файла и формы таким же образом, как для `Body` или `Query`: -//// tab | Python 3.9+ - -```Python hl_lines="10-12" -{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="9-11" -{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/request_forms_and_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *} Файлы и поля формы будут загружены в виде данных формы, и вы получите файлы и поля формы. diff --git a/docs/ru/docs/tutorial/request-forms.md b/docs/ru/docs/tutorial/request-forms.md index cd17613de..b33ea044b 100644 --- a/docs/ru/docs/tutorial/request-forms.md +++ b/docs/ru/docs/tutorial/request-forms.md @@ -14,69 +14,13 @@ Импортируйте `Form` из `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать 'Annotated' версию, если это возможно. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} ## Определение параметров `Form` Создайте параметры формы так же, как это делается для `Body` или `Query`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать 'Annotated' версию, если это возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} Например, в одном из способов использования спецификации OAuth2 (называемом "потоком пароля") требуется отправить `username` и `password` в виде полей формы. diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md index c55be38ef..b3c29281c 100644 --- a/docs/ru/docs/tutorial/response-model.md +++ b/docs/ru/docs/tutorial/response-model.md @@ -4,29 +4,7 @@ FastAPI позволяет использовать **аннотации типов** таким же способом, как и для ввода данных в **параметры** функции, вы можете использовать модели Pydantic, списки, словари, скалярные типы (такие, как int, bool и т.д.). -//// tab | Python 3.10+ - -```Python hl_lines="16 21" -{!> ../../docs_src/response_model/tutorial001_01_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *} FastAPI будет использовать этот возвращаемый тип для: @@ -59,29 +37,7 @@ FastAPI будет использовать этот возвращаемый т * `@app.delete()` * и др. -//// tab | Python 3.10+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *} /// note | Технические детали @@ -113,21 +69,7 @@ FastAPI будет использовать значение `response_model` д Здесь мы объявили модель `UserIn`, которая хранит пользовательский пароль в открытом виде: -//// tab | Python 3.10+ - -```Python hl_lines="7 9" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *} /// info | Информация @@ -139,21 +81,7 @@ FastAPI будет использовать значение `response_model` д Далее мы используем нашу модель в аннотациях типа как для аргумента функции, так и для выходного значения: -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *} Теперь всякий раз, когда клиент создает пользователя с паролем, API будет возвращать его пароль в ответе. @@ -171,57 +99,15 @@ FastAPI будет использовать значение `response_model` д Вместо этого мы можем создать входную модель, хранящую пароль в открытом виде и выходную модель без пароля: -//// tab | Python 3.10+ - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *} В таком случае, даже несмотря на то, что наша *функция операции пути* возвращает тот же самый объект пользователя с паролем, полученным на вход: -//// tab | Python 3.10+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *} ...мы указали в `response_model` модель `UserOut`, в которой отсутствует поле, содержащее пароль - и он будет исключен из ответа: -//// tab | Python 3.10+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *} Таким образом **FastAPI** позаботится о фильтрации ответа и исключит из него всё, что не указано в выходной модели (при помощи Pydantic). @@ -245,21 +131,7 @@ FastAPI будет использовать значение `response_model` д И в таких случаях мы можем использовать классы и наследование, чтобы пользоваться преимуществами **аннотаций типов** и получать более полную статическую проверку типов. Но при этом все так же получать **фильтрацию ответа** от FastAPI. -//// tab | Python 3.10+ - -```Python hl_lines="7-10 13-14 18" -{!> ../../docs_src/response_model/tutorial003_01_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-13 15-16 20" -{!> ../../docs_src/response_model/tutorial003_01.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *} Таким образом, мы получаем поддержку редактора кода и mypy в части типов, сохраняя при этом фильтрацию данных от FastAPI. @@ -301,9 +173,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Самый частый сценарий использования - это [возвращать Response напрямую, как описано в расширенной документации](../advanced/response-directly.md){.internal-link target=_blank}. -```Python hl_lines="8 10-11" -{!> ../../docs_src/response_model/tutorial003_02.py!} -``` +{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *} Это поддерживается FastAPI по-умолчанию, т.к. аннотация проставлена в классе (или подклассе) `Response`. @@ -313,9 +183,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Вы также можете указать подкласс `Response` в аннотации типа: -```Python hl_lines="8-9" -{!> ../../docs_src/response_model/tutorial003_03.py!} -``` +{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *} Это сработает, потому что `RedirectResponse` является подклассом `Response` и FastAPI автоматически обработает этот простейший случай. @@ -325,21 +193,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма То же самое произошло бы, если бы у вас было что-то вроде Union различных типов и один или несколько из них не являлись бы допустимыми типами для Pydantic. Например, такой вариант приведет к ошибке 💥: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/response_model/tutorial003_04_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/response_model/tutorial003_04.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *} ...такой код вызовет ошибку, потому что в аннотации указан неподдерживаемый Pydantic тип. А также этот тип не является классом или подклассом `Response`. @@ -351,21 +205,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма В таком случае, вы можете отключить генерацию модели ответа, указав `response_model=None`: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/response_model/tutorial003_05_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/response_model/tutorial003_05.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *} Тогда FastAPI не станет генерировать модель ответа и вы сможете сохранить такую аннотацию типа, которая вам требуется, никак не влияя на работу FastAPI. 🤓 @@ -373,29 +213,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Модель ответа может иметь значения по умолчанию, например: -//// tab | Python 3.10+ - -```Python hl_lines="9 11-12" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *} * `description: Union[str, None] = None` (или `str | None = None` в Python 3.10), где `None` является значением по умолчанию. * `tax: float = 10.5`, где `10.5` является значением по умолчанию. @@ -409,29 +227,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Установите для *декоратора операции пути* параметр `response_model_exclude_unset=True`: -//// tab | Python 3.10+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *} и тогда значения по умолчанию не будут включены в ответ. В нем будут только те поля, значения которых фактически были установлены. @@ -520,21 +316,7 @@ FastAPI достаточно умен (на самом деле, это засл /// -//// tab | Python 3.10+ - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial005.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *} /// tip | Подсказка @@ -548,21 +330,7 @@ FastAPI достаточно умен (на самом деле, это засл Если вы забыли про `set` и использовали структуру `list` или `tuple`, FastAPI автоматически преобразует этот объект в `set`, чтобы обеспечить корректную работу: -//// tab | Python 3.10+ - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial006.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *} ## Резюме diff --git a/docs/ru/docs/tutorial/response-status-code.md b/docs/ru/docs/tutorial/response-status-code.md index f08b15379..b46f656f3 100644 --- a/docs/ru/docs/tutorial/response-status-code.md +++ b/docs/ru/docs/tutorial/response-status-code.md @@ -8,9 +8,7 @@ * `@app.delete()` * и других. -```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 @@ FastAPI знает об этом и создаст документацию Open Рассмотрим предыдущий пример еще раз: -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201` – это код статуса "Создано". @@ -86,9 +82,7 @@ FastAPI знает об этом и создаст документацию Open Для удобства вы можете использовать переменные из `fastapi.status`. -```Python hl_lines="1 6" -{!../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} Они содержат те же числовые значения, но позволяют использовать подсказки редактора для выбора кода статуса: diff --git a/docs/ru/docs/tutorial/schema-extra-example.md b/docs/ru/docs/tutorial/schema-extra-example.md index daa264afc..f17b24349 100644 --- a/docs/ru/docs/tutorial/schema-extra-example.md +++ b/docs/ru/docs/tutorial/schema-extra-example.md @@ -8,21 +8,7 @@ Вы можете объявить ключ `example` для модели Pydantic, используя класс `Config` и переменную `schema_extra`, как описано в Pydantic документации: Настройка схемы: -//// tab | Python 3.10+ - -```Python hl_lines="13-21" -{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15-23" -{!> ../../docs_src/schema_extra_example/tutorial001.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:21] *} Эта дополнительная информация будет включена в **JSON Schema** выходных данных для этой модели, и она будет использоваться в документации к API. @@ -40,21 +26,7 @@ Вы можете использовать это, чтобы добавить аргумент `example` для каждого поля: -//// tab | Python 3.10+ - -```Python hl_lines="2 8-11" -{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10-13" -{!> ../../docs_src/schema_extra_example/tutorial002.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *} /// warning | Внимание @@ -80,57 +52,7 @@ Здесь мы передаём аргумент `example`, как пример данных ожидаемых в параметре `Body()`: -//// tab | Python 3.10+ - -```Python hl_lines="22-27" -{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="22-27" -{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23-28" -{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать версию с `Annotated`, если это возможно. - -/// - -```Python hl_lines="18-23" -{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать версию с `Annotated`, если это возможно. - -/// - -```Python hl_lines="20-25" -{!> ../../docs_src/schema_extra_example/tutorial003.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:27] *} ### Аргумент "example" в UI документации @@ -151,57 +73,7 @@ * `value`: Это конкретный пример, который отображается, например, в виде типа `dict`. * `externalValue`: альтернатива параметру `value`, URL-адрес, указывающий на пример. Хотя это может не поддерживаться таким же количеством инструментов разработки и тестирования API, как параметр `value`. -//// tab | Python 3.10+ - -```Python hl_lines="23-49" -{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23-49" -{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24-50" -{!> ../../docs_src/schema_extra_example/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать версию с `Annotated`, если это возможно. - -/// - -```Python hl_lines="19-45" -{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать версию с `Annotated`, если это возможно. - -/// - -```Python hl_lines="21-47" -{!> ../../docs_src/schema_extra_example/tutorial004.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:49] *} ### Аргумент "examples" в UI документации diff --git a/docs/ru/docs/tutorial/security/first-steps.md b/docs/ru/docs/tutorial/security/first-steps.md index 484dfceff..e55f48b89 100644 --- a/docs/ru/docs/tutorial/security/first-steps.md +++ b/docs/ru/docs/tutorial/security/first-steps.md @@ -20,35 +20,7 @@ Скопируйте пример в файл `main.py`: -//// tab | Python 3.9+ - -```Python -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py *} ## Запуск @@ -152,35 +124,7 @@ OAuth2 был разработан для того, чтобы бэкэнд ил При создании экземпляра класса `OAuth2PasswordBearer` мы передаем в него параметр `tokenUrl`. Этот параметр содержит URL, который клиент (фронтенд, работающий в браузере пользователя) будет использовать для отправки `имени пользователя` и `пароля` с целью получения токена. -//// tab | Python 3.9+ - -```Python hl_lines="8" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="6" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *} /// tip | Подсказка @@ -218,35 +162,7 @@ oauth2_scheme(some, parameters) Теперь вы можете передать ваш `oauth2_scheme` в зависимость с помощью `Depends`. -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} Эта зависимость будет предоставлять `строку`, которая присваивается параметру `token` в *функции операции пути*. diff --git a/docs/ru/docs/tutorial/static-files.md b/docs/ru/docs/tutorial/static-files.md index 0287fb017..c06eb858b 100644 --- a/docs/ru/docs/tutorial/static-files.md +++ b/docs/ru/docs/tutorial/static-files.md @@ -7,9 +7,7 @@ * Импортируйте `StaticFiles`. * "Примонтируйте" экземпляр `StaticFiles()` с указанием определенной директории. -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} /// note | Технические детали diff --git a/docs/ru/docs/tutorial/testing.md b/docs/ru/docs/tutorial/testing.md index 0485ef801..2c0f93d48 100644 --- a/docs/ru/docs/tutorial/testing.md +++ b/docs/ru/docs/tutorial/testing.md @@ -26,9 +26,7 @@ Напишите простое утверждение с `assert` дабы проверить истинность Python-выражения (это тоже стандарт `pytest`). -```Python hl_lines="2 12 15-18" -{!../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} /// tip | Подсказка @@ -74,9 +72,7 @@ Здесь файл `main.py` является "точкой входа" в Ваше приложение и содержит инициализацию Вашего приложения **FastAPI**: -```Python -{!../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### Файл тестов @@ -92,9 +88,8 @@ Так как оба файла находятся в одной директории, для импорта объекта приложения из файла `main` в файл `test_main` Вы можете использовать относительный импорт: -```Python hl_lines="3" -{!../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py hl[3] *} + ...и писать дальше тесты, как и раньше. @@ -178,9 +173,8 @@ Теперь обновим файл `test_main.py`, добавив в него тестов: -```Python -{!> ../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} + Если Вы не знаете, как передать информацию в запросе, можете воспользоваться поисковиком (погуглить) и задать вопрос: "Как передать информацию в запросе с помощью `httpx`", можно даже спросить: "Как передать информацию в запросе с помощью `requests`", поскольку дизайн HTTPX основан на дизайне Requests. diff --git a/docs/tr/docs/advanced/testing-websockets.md b/docs/tr/docs/advanced/testing-websockets.md index 12b6ab60f..ddacca449 100644 --- a/docs/tr/docs/advanced/testing-websockets.md +++ b/docs/tr/docs/advanced/testing-websockets.md @@ -4,9 +4,7 @@ WebSockets testi yapmak için `TestClient`'ı kullanabilirsiniz. Bu işlem için, `TestClient`'ı bir `with` ifadesinde kullanarak WebSocket'e bağlanabilirsiniz: -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} /// note | Not diff --git a/docs/tr/docs/advanced/wsgi.md b/docs/tr/docs/advanced/wsgi.md index bc8da16df..00815a4b2 100644 --- a/docs/tr/docs/advanced/wsgi.md +++ b/docs/tr/docs/advanced/wsgi.md @@ -12,9 +12,7 @@ Ardından WSGI (örneğin Flask) uygulamanızı middleware ile sarmalayın. Son olarak da bir yol altında bağlama işlemini gerçekleştirin. -```Python hl_lines="2-3 23" -{!../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,23] *} ## Kontrol Edelim diff --git a/docs/tr/docs/python-types.md b/docs/tr/docs/python-types.md index 308dfa6fb..b44aa3b9d 100644 --- a/docs/tr/docs/python-types.md +++ b/docs/tr/docs/python-types.md @@ -22,9 +22,8 @@ Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, Basit bir örnek ile başlayalım: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Programın çıktısı: @@ -38,9 +37,8 @@ Fonksiyon sırayla şunları yapar: * `title()` ile değişkenlerin ilk karakterlerini büyütür. * Değişkenleri aralarında bir boşlukla beraber Birleştirir. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Düzenle @@ -82,9 +80,8 @@ Bu kadar. İşte bunlar "tip belirteçleri": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Bu, aşağıdaki gibi varsayılan değerleri bildirmekle aynı şey değildir: @@ -112,9 +109,8 @@ Aradığınızı bulana kadar seçenekleri kaydırabilirsiniz: Bu fonksiyon, zaten tür belirteçlerine sahip: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama değil, hata kontrolleri de sağlar: @@ -122,9 +118,8 @@ Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama de Artık `age` değişkenini `str(age)` olarak kullanmanız gerektiğini biliyorsunuz: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Tip bildirme @@ -143,9 +138,8 @@ Yalnızca `str` değil, tüm standart Python tiplerinin bildirebilirsiniz. * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Tip parametreleri ile Generic tipler @@ -161,9 +155,8 @@ Bu tür tip belirteçlerini desteklemek için özel olarak mevcuttur. From `typing`, import `List` (büyük harf olan `L` ile): -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + Değişkenin tipini yine iki nokta üstüste (`:`) ile belirleyin. @@ -171,9 +164,8 @@ tip olarak `List` kullanın. Liste, bazı dahili tipleri içeren bir tür olduğundan, bunları köşeli parantez içine alırsınız: -```Python hl_lines="4" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + /// tip | Ipucu @@ -199,9 +191,8 @@ Ve yine, editör bunun bir `str` ​​olduğunu biliyor ve bunun için destek s `Tuple` ve `set`lerin tiplerini bildirmek için de aynısını yapıyoruz: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + Bu şu anlama geliyor: @@ -216,9 +207,8 @@ Bir `dict` tanımlamak için virgülle ayrılmış iki parametre verebilirsiniz. İkinci parametre ise `dict` değerinin `value` değeri içindir: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + Bu şu anlama gelir: @@ -255,15 +245,13 @@ Bir değişkenin tipini bir sınıf ile bildirebilirsiniz. Diyelim ki `name` değerine sahip `Person` sınıfınız var: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Sonra bir değişkeni 'Person' tipinde tanımlayabilirsiniz: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + Ve yine bütün editör desteğini alırsınız: @@ -283,9 +271,8 @@ Ve ortaya çıkan nesne üzerindeki bütün editör desteğini alırsınız. Resmi Pydantic dokümanlarından alınmıştır: -```Python -{!../../docs_src/python_types/tutorial011.py!} -``` +{* ../../docs_src/python_types/tutorial011.py *} + /// info diff --git a/docs/tr/docs/tutorial/cookie-params.md b/docs/tr/docs/tutorial/cookie-params.md index 56bcc0c86..f07508c2f 100644 --- a/docs/tr/docs/tutorial/cookie-params.md +++ b/docs/tr/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ Öncelikle, `Cookie`'yi projenize dahil edin: -//// 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 | İpucu - -Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | İpucu - -Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## `Cookie` Parametrelerini Tanımlayın @@ -64,57 +14,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. İlk değer varsayılan değerdir; tüm ekstra doğrulama veya belirteç parametrelerini kullanabilirsiniz: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | İpucu - -Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | İpucu - -Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} /// note | Teknik Detaylar diff --git a/docs/tr/docs/tutorial/first-steps.md b/docs/tr/docs/tutorial/first-steps.md index da9057204..2d2949b50 100644 --- a/docs/tr/docs/tutorial/first-steps.md +++ b/docs/tr/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ En sade FastAPI dosyası şu şekilde görünür: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Yukarıdaki içeriği bir `main.py` dosyasına kopyalayalım. @@ -133,9 +131,7 @@ Ayrıca, API'ınızla iletişim kuracak önyüz, mobil veya IoT uygulamaları gi ### Adım 1: `FastAPI`yı Projemize Dahil Edelim -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI`, API'niz için tüm işlevselliği sağlayan bir Python sınıfıdır. @@ -149,9 +145,7 @@ Ayrıca, API'ınızla iletişim kuracak önyüz, mobil veya IoT uygulamaları gi ### Adım 2: Bir `FastAPI` "Örneği" Oluşturalım -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} Burada `app` değişkeni `FastAPI` sınıfının bir örneği olacaktır. @@ -171,9 +165,7 @@ $ uvicorn main:app --reload Uygulamanızı aşağıdaki gibi oluşturursanız: -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} Ve bunu `main.py` dosyasına yerleştirirseniz eğer `uvicorn` komutunu şu şekilde çalıştırabilirsiniz: @@ -250,9 +242,7 @@ Biz de onları "**operasyonlar**" olarak adlandıracağız. #### Bir *Yol Operasyonu Dekoratörü* Tanımlayalım -```Python hl_lines="6" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} `@app.get("/")` dekoratörü, **FastAPI**'a hemen altındaki fonksiyonun aşağıdaki durumlardan sorumlu olduğunu söyler: @@ -306,9 +296,7 @@ Aşağıdaki, bizim **yol operasyonu fonksiyonumuzdur**: * **operasyon**: `get` * **fonksiyon**: "dekoratör"ün (`@app.get("/")`'in) altındaki fonksiyondur. -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} Bu bir Python fonksiyonudur. @@ -320,9 +308,7 @@ Bu durumda bu fonksiyon bir `async` fonksiyondur. Bu fonksiyonu `async def` yerine normal bir fonksiyon olarak da tanımlayabilirsiniz. -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} /// note | Not @@ -332,9 +318,7 @@ Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurr ### Adım 5: İçeriği Geri Döndürün -```Python hl_lines="8" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} Bir `dict`, `list` veya `str`, `int` gibi tekil değerler döndürebilirsiniz. diff --git a/docs/tr/docs/tutorial/path-params.md b/docs/tr/docs/tutorial/path-params.md index c883c2f9f..e1707a5d9 100644 --- a/docs/tr/docs/tutorial/path-params.md +++ b/docs/tr/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ Yol "parametrelerini" veya "değişkenlerini" Python string biçimlemede kullanılan sözdizimi ile tanımlayabilirsiniz. -```Python hl_lines="6-7" -{!../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} Yol parametresi olan `item_id`'nin değeri, fonksiyonunuza `item_id` argümanı olarak aktarılacaktır. @@ -18,9 +16,7 @@ Eğer bu örneği çalıştırıp ../../docs_src/query_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} Bu durumda, `q` fonksiyon parametresi isteğe bağlı olacak ve varsayılan değer olarak `None` alacaktır. @@ -91,21 +75,7 @@ Ayrıca, dikkatinizi çekerim ki; **FastAPI**, `item_id` parametresinin bir yol Aşağıda görüldüğü gibi dönüştürülmek üzere `bool` tipleri de tanımlayabilirsiniz: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} Bu durumda, eğer şu adrese giderseniz: @@ -148,21 +118,7 @@ Ve parametreleri, herhangi bir sıraya koymanıza da gerek yoktur. İsimlerine göre belirleneceklerdir: -//// tab | Python 3.10+ - -```Python hl_lines="6 8" -{!> ../../docs_src/query_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 10" -{!> ../../docs_src/query_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Zorunlu Sorgu Parametreleri @@ -172,9 +128,7 @@ Parametre için belirli bir değer atamak istemeyip parametrenin sadece isteğe Fakat, bir sorgu parametresini zorunlu yapmak istiyorsanız varsayılan bir değer atamamanız yeterli olacaktır: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Burada `needy` parametresi `str` tipinden oluşan zorunlu bir sorgu parametresidir. @@ -220,21 +174,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Ve elbette, bazı parametreleri zorunlu, bazılarını varsayılan değerli ve bazılarını tamamen opsiyonel olarak tanımlayabilirsiniz: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params/tutorial006.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} Bu durumda, 3 tane sorgu parametresi var olacaktır: diff --git a/docs/tr/docs/tutorial/request-forms.md b/docs/tr/docs/tutorial/request-forms.md index 4ed8ac021..e4e04f5f9 100644 --- a/docs/tr/docs/tutorial/request-forms.md +++ b/docs/tr/docs/tutorial/request-forms.md @@ -14,69 +14,13 @@ Formları kullanmak için öncelikle ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} ## `Form` Parametrelerini Tanımlayın Form parametrelerini `Body` veya `Query` için yaptığınız gibi oluşturun: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} Örneğin, OAuth2 spesifikasyonunun kullanılabileceği ("şifre akışı" olarak adlandırılan) yollardan birinde, form alanları olarak "username" ve "password" gönderilmesi gerekir. diff --git a/docs/tr/docs/tutorial/static-files.md b/docs/tr/docs/tutorial/static-files.md index da8bed86a..db30f13bc 100644 --- a/docs/tr/docs/tutorial/static-files.md +++ b/docs/tr/docs/tutorial/static-files.md @@ -7,9 +7,7 @@ * `StaticFiles` sınıfını projenize dahil edin. * Bir `StaticFiles()` örneğini belirli bir yola bağlayın. -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} /// note | Teknik Detaylar diff --git a/docs/uk/docs/python-types.md b/docs/uk/docs/python-types.md index 573b5372c..676bafb15 100644 --- a/docs/uk/docs/python-types.md +++ b/docs/uk/docs/python-types.md @@ -22,9 +22,8 @@ Python підтримує додаткові "підказки типу" ("type Давайте почнемо з простого прикладу: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Виклик цієї програми виводить: @@ -38,9 +37,8 @@ John Doe * Конвертує кожну літеру кожного слова у верхній регістр за допомогою `title()`. * Конкатенує їх разом із пробілом по середині. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Редагуйте це @@ -82,9 +80,8 @@ John Doe Це "type hints": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Це не те саме, що оголошення значень за замовчуванням, як це було б з: @@ -112,9 +109,8 @@ John Doe Перевірте цю функцію, вона вже має анотацію типу: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Оскільки редактор знає типи змінних, ви не тільки отримаєте автозаповнення, ви також отримаєте перевірку помилок: @@ -122,9 +118,8 @@ John Doe Тепер ви знаєте, щоб виправити це, вам потрібно перетворити `age` у строку з допомогою `str(age)`: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Оголошення типів @@ -143,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Generic-типи з параметрами типів @@ -406,15 +400,13 @@ John Doe Скажімо, у вас є клас `Person` з імʼям: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Потім ви можете оголосити змінну типу `Person`: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + І знову ж таки, ви отримуєте всю підтримку редактора: diff --git a/docs/uk/docs/tutorial/body-fields.md b/docs/uk/docs/tutorial/body-fields.md index c286744a8..7ddd9d104 100644 --- a/docs/uk/docs/tutorial/body-fields.md +++ b/docs/uk/docs/tutorial/body-fields.md @@ -6,57 +6,7 @@ Спочатку вам потрібно імпортувати це: -//// tab | Python 3.10+ - -```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 - -Варто користуватись `Annotated` версією, якщо це можливо. - -/// - -```Python hl_lines="2" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Варто користуватись `Annotated` версією, якщо це можливо. - -/// - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} /// warning @@ -68,57 +18,7 @@ Ви можете використовувати `Field` з атрибутами моделі: -//// 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 - -Варто користуватись `Annotated` версією, якщо це можливо.. - -/// - -```Python hl_lines="9-12" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Варто користуватись `Annotated` версією, якщо це можливо.. - -/// - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} `Field` працює так само, як `Query`, `Path` і `Body`, у нього такі самі параметри тощо. diff --git a/docs/uk/docs/tutorial/body.md b/docs/uk/docs/tutorial/body.md index 1e4188831..38fed7bb8 100644 --- a/docs/uk/docs/tutorial/body.md +++ b/docs/uk/docs/tutorial/body.md @@ -22,21 +22,7 @@ Спочатку вам потрібно імпортувати `BaseModel` з `pydantic`: -//// tab | Python 3.8 і вище - -```Python hl_lines="4" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// - -//// tab | Python 3.10 і вище - -```Python hl_lines="2" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial001.py hl[4] *} ## Створіть свою модель даних @@ -44,21 +30,7 @@ Використовуйте стандартні типи Python для всіх атрибутів: -//// tab | Python 3.8 і вище - -```Python hl_lines="7-11" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// - -//// tab | Python 3.10 і вище - -```Python hl_lines="5-9" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial001.py hl[7:11] *} Так само, як і при оголошенні параметрів запиту, коли атрибут моделі має значення за замовчуванням, він не є обов’язковим. В іншому випадку це потрібно. Використовуйте `None`, щоб зробити його необов'язковим. @@ -86,21 +58,7 @@ Щоб додати модель даних до вашої *операції шляху*, оголосіть її так само, як ви оголосили параметри шляху та запиту: -//// tab | Python 3.8 і вище - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// - -//// tab | Python 3.10 і вище - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial001.py hl[18] *} ...і вкажіть її тип як модель, яку ви створили, `Item`. @@ -167,21 +125,7 @@ Усередині функції ви можете отримати прямий доступ до всіх атрибутів об’єкта моделі: -//// tab | Python 3.8 і вище - -```Python hl_lines="21" -{!> ../../docs_src/body/tutorial002.py!} -``` - -//// - -//// tab | Python 3.10 і вище - -```Python hl_lines="19" -{!> ../../docs_src/body/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial002.py hl[21] *} ## Тіло запиту + параметри шляху @@ -189,21 +133,7 @@ **FastAPI** розпізнає, що параметри функції, які відповідають параметрам шляху, мають бути **взяті з шляху**, а параметри функції, які оголошуються як моделі Pydantic, **взяті з тіла запиту**. -//// tab | Python 3.8 і вище - -```Python hl_lines="17-18" -{!> ../../docs_src/body/tutorial003.py!} -``` - -//// - -//// tab | Python 3.10 і вище - -```Python hl_lines="15-16" -{!> ../../docs_src/body/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial003.py hl[17:18] *} ## Тіло запиту + шлях + параметри запиту @@ -211,21 +141,7 @@ **FastAPI** розпізнає кожен з них і візьме дані з потрібного місця. -//// tab | Python 3.8 і вище - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial004.py!} -``` - -//// - -//// tab | Python 3.10 і вище - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial004.py hl[18] *} Параметри функції будуть розпізнаватися наступним чином: diff --git a/docs/uk/docs/tutorial/cookie-params.md b/docs/uk/docs/tutorial/cookie-params.md index 229f81b63..b320645cb 100644 --- a/docs/uk/docs/tutorial/cookie-params.md +++ b/docs/uk/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ Спочатку імпортуйте `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 - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## Визначення параметрів `Cookie` @@ -64,57 +14,7 @@ Перше значення це значення за замовчуванням, ви можете також передати всі додаткові параметри валідації чи анотації: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} /// note | Технічні Деталі diff --git a/docs/uk/docs/tutorial/encoder.md b/docs/uk/docs/tutorial/encoder.md index 77b0baf4d..f202c7989 100644 --- a/docs/uk/docs/tutorial/encoder.md +++ b/docs/uk/docs/tutorial/encoder.md @@ -20,21 +20,7 @@ Вона приймає об'єкт, такий як Pydantic model, і повертає його версію, сумісну з JSON: -//// 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] *} У цьому прикладі вона конвертує Pydantic model у `dict`, а `datetime` у `str`. diff --git a/docs/uk/docs/tutorial/extra-data-types.md b/docs/uk/docs/tutorial/extra-data-types.md index 5e6c364e4..5da942b6e 100644 --- a/docs/uk/docs/tutorial/extra-data-types.md +++ b/docs/uk/docs/tutorial/extra-data-types.md @@ -55,108 +55,8 @@ Ось приклад *path operation* з параметрами, використовуючи деякі з вищезазначених типів. -//// tab | Python 3.10+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 3 13-17" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="1 2 11-15" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="1 2 12-16" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} Зверніть увагу, що параметри всередині функції мають свій звичайний тип даних, і ви можете, наприклад, виконувати звичайні маніпуляції з датами, такі як: -//// tab | Python 3.10+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-20" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="17-18" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/uk/docs/tutorial/first-steps.md b/docs/uk/docs/tutorial/first-steps.md index 63fec207d..e910c4ccc 100644 --- a/docs/uk/docs/tutorial/first-steps.md +++ b/docs/uk/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Найпростіший файл FastAPI може виглядати так: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Скопіюйте це до файлу `main.py`. @@ -157,9 +155,7 @@ OpenAPI описує схему для вашого API. І ця схема вк ### Крок 1: імпортуємо `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` це клас у Python, який надає всю функціональність для API. @@ -173,9 +169,7 @@ OpenAPI описує схему для вашого API. І ця схема вк ### Крок 2: створюємо екземпляр `FastAPI` -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} Змінна `app` є екземпляром класу `FastAPI`. Це буде головна точка для створення і взаємодії з API. @@ -242,9 +236,7 @@ https://example.com/items/foo #### Визначте декоратор операції шляху (path operation decorator) -```Python hl_lines="6" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} Декоратор `@app.get("/")` вказує **FastAPI**, що функція нижче, відповідає за обробку запитів, які надходять до неї: * шлях `/` @@ -297,9 +289,7 @@ https://example.com/items/foo * **операція**: це `get`. * **функція**: це функція, яка знаходиться нижче "декоратора" (нижче `@app.get("/")`). -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} Це звичайна функція Python. @@ -311,9 +301,7 @@ FastAPI викликатиме її щоразу, коли отримає зап Ви також можете визначити її як звичайну функцію замість `async def`: -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} /// note | Примітка @@ -323,9 +311,7 @@ FastAPI викликатиме її щоразу, коли отримає зап ### Крок 5: поверніть результат -```Python hl_lines="8" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} Ви можете повернути `dict`, `list`, а також окремі значення `str`, `int`, ітд. diff --git a/docs/vi/docs/python-types.md b/docs/vi/docs/python-types.md index 275b0eb39..403e89930 100644 --- a/docs/vi/docs/python-types.md +++ b/docs/vi/docs/python-types.md @@ -22,9 +22,8 @@ Nếu bạn là một chuyên gia về Python, và bạn đã biết mọi thứ Hãy bắt đầu với một ví dụ đơn giản: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Kết quả khi gọi chương trình này: @@ -38,9 +37,8 @@ Hàm thực hiện như sau: * Chuyển đổi kí tự đầu tiên của mỗi biến sang kiểu chữ hoa với `title()`. * Nối chúng lại với nhau bằng một kí tự trắng ở giữa. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Sửa đổi @@ -82,9 +80,8 @@ Chính là nó. Những thứ đó là "type hints": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Đó không giống như khai báo những giá trị mặc định giống như: @@ -112,9 +109,8 @@ Với cái đó, bạn có thể cuộn, nhìn thấy các lựa chọn, cho đ Kiểm tra hàm này, nó đã có gợi ý kiểu dữ liệu: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Bởi vì trình soạn thảo biết kiểu dữ liệu của các biến, bạn không chỉ có được completion, bạn cũng được kiểm tra lỗi: @@ -122,9 +118,8 @@ Bởi vì trình soạn thảo biết kiểu dữ liệu của các biến, bạ Bây giờ bạn biết rằng bạn phải sửa nó, chuyển `age` sang một xâu với `str(age)`: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Khai báo các kiểu dữ liệu @@ -143,9 +138,8 @@ Bạn có thể sử dụng, ví dụ: * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Các kiểu dữ liệu tổng quát với tham số kiểu dữ liệu @@ -374,9 +368,8 @@ Nó chỉ là về các từ và tên. Nhưng những từ đó có thể ảnh Cho một ví dụ, hãy để ý hàm này: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c.py!} -``` +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} + Tham số `name` được định nghĩa là `Optional[str]`, nhưng nó **không phải là tùy chọn**, bạn không thể gọi hàm mà không có tham số: @@ -392,9 +385,8 @@ say_hi(name=None) # This works, None is valid 🎉 Tin tốt là, khi bạn sử dụng Python 3.10, bạn sẽ không phải lo lắng về điều đó, bạn sẽ có thể sử dụng `|` để định nghĩa hợp của các kiểu dữ liệu một cách đơn giản: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c_py310.py!} -``` +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} + Và sau đó, bạn sẽ không phải lo rằng những cái tên như `Optional` và `Union`. 😎 @@ -457,15 +449,13 @@ Bạn cũng có thể khai báo một lớp như là kiểu dữ liệu của m Hãy nói rằng bạn muốn có một lớp `Person` với một tên: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Sau đó bạn có thể khai báo một biến có kiểu là `Person`: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + Và lại một lần nữa, bạn có được tất cả sự hỗ trợ từ trình soạn thảo: diff --git a/docs/zh/docs/advanced/additional-status-codes.md b/docs/zh/docs/advanced/additional-status-codes.md index b8f9b0837..b048a2a17 100644 --- a/docs/zh/docs/advanced/additional-status-codes.md +++ b/docs/zh/docs/advanced/additional-status-codes.md @@ -14,9 +14,7 @@ 要实现它,导入 `JSONResponse`,然后在其中直接返回你的内容,并将 `status_code` 设置为为你要的值。 -```Python hl_lines="4 25" -{!../../docs_src/additional_status_codes/tutorial001.py!} -``` +{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *} /// warning | 警告 diff --git a/docs/zh/docs/advanced/advanced-dependencies.md b/docs/zh/docs/advanced/advanced-dependencies.md index bd37ecebb..8375bd48e 100644 --- a/docs/zh/docs/advanced/advanced-dependencies.md +++ b/docs/zh/docs/advanced/advanced-dependencies.md @@ -18,9 +18,7 @@ Python 可以把类实例变为**可调用项**。 为此,需要声明 `__call__` 方法: -```Python hl_lines="10" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[10] *} 本例中,**FastAPI** 使用 `__call__` 检查附加参数及子依赖项,稍后,还要调用它向*路径操作函数*传递值。 @@ -28,9 +26,7 @@ Python 可以把类实例变为**可调用项**。 接下来,使用 `__init__` 声明用于**参数化**依赖项的实例参数: -```Python hl_lines="7" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[7] *} 本例中,**FastAPI** 不使用 `__init__`,我们要直接在代码中使用。 @@ -38,9 +34,7 @@ Python 可以把类实例变为**可调用项**。 使用以下代码创建类实例: -```Python hl_lines="16" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[16] *} 这样就可以**参数化**依赖项,它包含 `checker.fixed_content` 的属性 - `"bar"`。 @@ -56,9 +50,7 @@ checker(q="somequery") ……并用*路径操作函数*的参数 `fixed_content_included` 返回依赖项的值: -```Python hl_lines="20" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[20] *} /// tip | 提示 diff --git a/docs/zh/docs/advanced/behind-a-proxy.md b/docs/zh/docs/advanced/behind-a-proxy.md index 5ed6baa82..f8f61c8a3 100644 --- a/docs/zh/docs/advanced/behind-a-proxy.md +++ b/docs/zh/docs/advanced/behind-a-proxy.md @@ -92,9 +92,7 @@ ASGI 规范定义的 `root_path` 就是为了这种用例。 我们在这里的信息里包含 `roo_path` 只是为了演示。 -```Python hl_lines="8" -{!../../docs_src/behind_a_proxy/tutorial001.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *} 然后,用以下命令启动 Uvicorn: @@ -121,9 +119,7 @@ $ uvicorn main:app --root-path /api/v1 还有一种方案,如果不能提供 `--root-path` 或等效的命令行选项,则在创建 FastAPI 应用时要设置 `root_path` 参数。 -```Python hl_lines="3" -{!../../docs_src/behind_a_proxy/tutorial002.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *} 传递 `root_path` 给 `FastAPI` 与传递 `--root-path` 命令行选项给 Uvicorn 或 Hypercorn 一样。 @@ -303,9 +299,7 @@ $ uvicorn main:app --root-path /api/v1 例如: -```Python hl_lines="4-7" -{!../../docs_src/behind_a_proxy/tutorial003.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *} 这段代码生产如下 OpenAPI 概图: @@ -352,9 +346,7 @@ API 文档与所选的服务器进行交互。 如果不想让 **FastAPI** 包含使用 `root_path` 的自动服务器,则要使用参数 `root_path_in_servers=False`: -```Python hl_lines="9" -{!../../docs_src/behind_a_proxy/tutorial004.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *} 这样,就不会在 OpenAPI 概图中包含服务器了。 diff --git a/docs/zh/docs/advanced/custom-response.md b/docs/zh/docs/advanced/custom-response.md index 85ca1d06d..22a9b4b51 100644 --- a/docs/zh/docs/advanced/custom-response.md +++ b/docs/zh/docs/advanced/custom-response.md @@ -24,9 +24,7 @@ 导入你想要使用的 `Response` 类(子类)然后在 *路径操作装饰器* 中声明它。 -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} /// info | 提示 @@ -51,9 +49,7 @@ * 导入 `HTMLResponse`。 * 将 `HTMLResponse` 作为你的 *路径操作* 的 `response_class` 参数传入。 -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial002.py!} -``` +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} /// info | 提示 @@ -71,9 +67,7 @@ 和上面一样的例子,返回一个 `HTMLResponse` 看起来可能是这样: -```Python hl_lines="2 7 19" -{!../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} /// warning | 警告 @@ -97,9 +91,7 @@ 比如像这样: -```Python hl_lines="7 23 21" -{!../../docs_src/custom_response/tutorial004.py!} -``` +{* ../../docs_src/custom_response/tutorial004.py hl[7,23,21] *} 在这个例子中,函数 `generate_html_response()` 已经生成并返回 `Response` 对象而不是在 `str` 中返回 HTML。 @@ -139,9 +131,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它还将包含一个基于 media_type 的 Content-Type 头,并为文本类型附加一个字符集。 -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ### `HTMLResponse` @@ -151,9 +141,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 接受文本或字节并返回纯文本响应。 -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial005.py!} -``` +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} ### `JSONResponse` @@ -176,9 +164,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 /// -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001.py!} -``` +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} /// tip | 小贴士 @@ -190,17 +176,13 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 返回 HTTP 重定向。默认情况下使用 307 状态代码(临时重定向)。 -```Python hl_lines="2 9" -{!../../docs_src/custom_response/tutorial006.py!} -``` +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} ### `StreamingResponse` 采用异步生成器或普通生成器/迭代器,然后流式传输响应主体。 -```Python hl_lines="2 14" -{!../../docs_src/custom_response/tutorial007.py!} -``` +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} #### 对类似文件的对象使用 `StreamingResponse` @@ -208,9 +190,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 包括许多与云存储,视频处理等交互的库。 -```Python hl_lines="2 10-12 14" -{!../../docs_src/custom_response/tutorial008.py!} -``` +{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *} /// tip | 小贴士 @@ -231,9 +211,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 文件响应将包含适当的 `Content-Length`,`Last-Modified` 和 `ETag` 的响应头。 -```Python hl_lines="2 10" -{!../../docs_src/custom_response/tutorial009.py!} -``` +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} ## 额外文档 diff --git a/docs/zh/docs/advanced/dataclasses.md b/docs/zh/docs/advanced/dataclasses.md index 7d977a0c7..c74ce65c3 100644 --- a/docs/zh/docs/advanced/dataclasses.md +++ b/docs/zh/docs/advanced/dataclasses.md @@ -4,9 +4,7 @@ FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 但 FastAPI 还可以使用数据类(`dataclasses`): -```Python hl_lines="1 7-12 19-20" -{!../../docs_src/dataclasses/tutorial001.py!} -``` +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} 这还是借助于 **Pydantic** 及其内置的 `dataclasses`。 @@ -34,9 +32,7 @@ FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 在 `response_model` 参数中使用 `dataclasses`: -```Python hl_lines="1 7-13 19" -{!../../docs_src/dataclasses/tutorial002.py!} -``` +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} 本例把数据类自动转换为 Pydantic 数据类。 diff --git a/docs/zh/docs/advanced/events.md b/docs/zh/docs/advanced/events.md index a34c03f3f..66f5af2e3 100644 --- a/docs/zh/docs/advanced/events.md +++ b/docs/zh/docs/advanced/events.md @@ -14,9 +14,7 @@ 使用 `startup` 事件声明 `app` 启动前运行的函数: -```Python hl_lines="8" -{!../../docs_src/events/tutorial001.py!} -``` +{* ../../docs_src/events/tutorial001.py hl[8] *} 本例中,`startup` 事件处理器函数为项目数据库(只是**字典**)提供了一些初始值。 @@ -28,9 +26,7 @@ 使用 `shutdown` 事件声明 `app` 关闭时运行的函数: -```Python hl_lines="6" -{!../../docs_src/events/tutorial002.py!} -``` +{* ../../docs_src/events/tutorial002.py hl[6] *} 此处,`shutdown` 事件处理器函数在 `log.txt` 中写入一行文本 `Application shutdown`。 diff --git a/docs/zh/docs/advanced/generate-clients.md b/docs/zh/docs/advanced/generate-clients.md index baf131361..bcb9ba2bf 100644 --- a/docs/zh/docs/advanced/generate-clients.md +++ b/docs/zh/docs/advanced/generate-clients.md @@ -16,21 +16,7 @@ 让我们从一个简单的 FastAPI 应用开始: -//// tab | Python 3.9+ - -```Python hl_lines="7-9 12-13 16-17 21" -{!> ../../docs_src/generate_clients/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../docs_src/generate_clients/tutorial001.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *} 请注意,*路径操作* 定义了他们所用于请求数据和回应数据的模型,所使用的模型是`Item` 和 `ResponseMessage`。 @@ -135,21 +121,7 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app 例如,您可以有一个用 `items` 的部分和另一个用于 `users` 的部分,它们可以用标签来分隔: -//// tab | Python 3.9+ - -```Python hl_lines="21 26 34" -{!> ../../docs_src/generate_clients/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23 28 36" -{!> ../../docs_src/generate_clients/tutorial002.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *} ### 生成带有标签的 TypeScript 客户端 @@ -196,21 +168,7 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** 然后,你可以将这个自定义函数作为 `generate_unique_id_function` 参数传递给 **FastAPI**: -//// tab | Python 3.9+ - -```Python hl_lines="6-7 10" -{!> ../../docs_src/generate_clients/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8-9 12" -{!> ../../docs_src/generate_clients/tutorial003.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *} ### 使用自定义操作ID生成TypeScript客户端 @@ -232,9 +190,7 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** 我们可以将 OpenAPI JSON 下载到一个名为`openapi.json`的文件中,然后使用以下脚本**删除此前缀的标签**: -```Python -{!../../docs_src/generate_clients/tutorial004.py!} -``` +{* ../../docs_src/generate_clients/tutorial004.py *} 通过这样做,操作ID将从类似于 `items-get_items` 的名称重命名为 `get_items` ,这样客户端生成器就可以生成更简洁的方法名称。 diff --git a/docs/zh/docs/advanced/middleware.md b/docs/zh/docs/advanced/middleware.md index 78a7d559c..c7b15b929 100644 --- a/docs/zh/docs/advanced/middleware.md +++ b/docs/zh/docs/advanced/middleware.md @@ -57,17 +57,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 任何传向 `http` 或 `ws` 的请求都会被重定向至安全方案。 -```Python hl_lines="2 6" -{!../../docs_src/advanced_middleware/tutorial001.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} ## `TrustedHostMiddleware` 强制所有传入请求都必须正确设置 `Host` 请求头,以防 HTTP 主机头攻击。 -```Python hl_lines="2 6-8" -{!../../docs_src/advanced_middleware/tutorial002.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} 支持以下参数: @@ -81,9 +77,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 中间件会处理标准响应与流响应。 -```Python hl_lines="2 6" -{!../../docs_src/advanced_middleware/tutorial003.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} 支持以下参数: diff --git a/docs/zh/docs/advanced/openapi-callbacks.md b/docs/zh/docs/advanced/openapi-callbacks.md index 601cbdb5d..f021eb10a 100644 --- a/docs/zh/docs/advanced/openapi-callbacks.md +++ b/docs/zh/docs/advanced/openapi-callbacks.md @@ -31,9 +31,7 @@ API 的用户 (外部开发者)要在您的 API 内使用 POST 请求创建 这部分代码很常规,您对绝大多数代码应该都比较熟悉了: -```Python hl_lines="10-14 37-54" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[10:14,37:54] *} /// tip | 提示 @@ -92,9 +90,7 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) 首先,新建包含一些用于回调的 `APIRouter`。 -```Python hl_lines="5 26" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[5,26] *} ### 创建回调*路径操作* @@ -105,9 +101,7 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) * 声明要接收的请求体,例如,`body: InvoiceEvent` * 还要声明要返回的响应,例如,`response_model=InvoiceEventReceived` -```Python hl_lines="17-19 22-23 29-33" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[17:19,22:23,29:33] *} 回调*路径操作*与常规*路径操作*有两点主要区别: @@ -175,9 +169,7 @@ JSON 请求体包含如下内容: 现在使用 API *路径操作装饰器*的参数 `callbacks`,从回调路由传递属性 `.routes`(实际上只是路由/路径操作的**列表**): -```Python hl_lines="36" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[36] *} /// tip | 提示 diff --git a/docs/zh/docs/advanced/path-operation-advanced-configuration.md b/docs/zh/docs/advanced/path-operation-advanced-configuration.md index 0d77dd69e..12600eddb 100644 --- a/docs/zh/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/zh/docs/advanced/path-operation-advanced-configuration.md @@ -12,9 +12,7 @@ 务必确保每个操作路径的 `operation_id` 都是唯一的。 -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### 使用 *路径操作函数* 的函数名作为 operationId @@ -22,9 +20,7 @@ 你应该在添加了所有 *路径操作* 之后执行此操作。 -```Python hl_lines="2 12 13 14 15 16 17 18 19 20 21 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12,13,14,15,16,17,18,19,20,21,24] *} /// tip @@ -44,9 +40,7 @@ 使用参数 `include_in_schema` 并将其设置为 `False` ,来从生成的 OpenAPI 方案中排除一个 *路径操作*(这样一来,就从自动化文档系统中排除掉了)。 -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## docstring 的高级描述 @@ -57,6 +51,4 @@ 剩余部分不会出现在文档中,但是其他工具(比如 Sphinx)可以使用剩余部分。 -```Python hl_lines="19 20 21 22 23 24 25 26 27 28 29" -{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19,20,21,22,23,24,25,26,27,28,29] *} diff --git a/docs/zh/docs/advanced/response-change-status-code.md b/docs/zh/docs/advanced/response-change-status-code.md index c38f80f1f..cc1f2a73e 100644 --- a/docs/zh/docs/advanced/response-change-status-code.md +++ b/docs/zh/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ 然后你可以在这个*临时*响应对象中设置`status_code`。 -```Python hl_lines="1 9 12" -{!../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} 然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。 diff --git a/docs/zh/docs/advanced/response-cookies.md b/docs/zh/docs/advanced/response-cookies.md index 2d56c6e9b..d4b93d003 100644 --- a/docs/zh/docs/advanced/response-cookies.md +++ b/docs/zh/docs/advanced/response-cookies.md @@ -4,9 +4,7 @@ 你可以在 *路径函数* 中定义一个类型为 `Response`的参数,这样你就可以在这个临时响应对象中设置cookie了。 -```Python hl_lines="1 8-9" -{!../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} 而且你还可以根据你的需要响应不同的对象,比如常用的 `dict`,数据库model等。 @@ -24,9 +22,7 @@ 然后设置Cookies,并返回: -```Python hl_lines="10-12" -{!../../docs_src/response_cookies/tutorial001.py!} -``` +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} /// tip diff --git a/docs/zh/docs/advanced/response-directly.md b/docs/zh/docs/advanced/response-directly.md index 934f60ef6..4d9cd53f2 100644 --- a/docs/zh/docs/advanced/response-directly.md +++ b/docs/zh/docs/advanced/response-directly.md @@ -35,9 +35,7 @@ 对于这些情况,在将数据传递给响应之前,你可以使用 `jsonable_encoder` 来转换你的数据。 -```Python hl_lines="4 6 20 21" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[4,6,20,21] *} /// note | 技术细节 @@ -57,9 +55,7 @@ 你可以把你的 XML 内容放到一个字符串中,放到一个 `Response` 中,然后返回。 -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ## 说明 diff --git a/docs/zh/docs/advanced/response-headers.md b/docs/zh/docs/advanced/response-headers.md index e7861ad0c..fe2cb0da8 100644 --- a/docs/zh/docs/advanced/response-headers.md +++ b/docs/zh/docs/advanced/response-headers.md @@ -5,9 +5,7 @@ 你可以在你的*路径操作函数*中声明一个`Response`类型的参数(就像你可以为cookies做的那样)。 然后你可以在这个*临时*响应对象中设置头部。 -```Python hl_lines="1 7-8" -{!../../docs_src/response_headers/tutorial002.py!} -``` +{* ../../docs_src/response_headers/tutorial002.py hl[1,7:8] *} 然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。 @@ -20,9 +18,8 @@ 你也可以在直接返回`Response`时添加头部。 按照[直接返回响应](response-directly.md){.internal-link target=_blank}中所述创建响应,并将头部作为附加参数传递: -```Python hl_lines="10-12" -{!../../docs_src/response_headers/tutorial001.py!} -``` + +{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *} /// note | 技术细节 diff --git a/docs/zh/docs/advanced/security/http-basic-auth.md b/docs/zh/docs/advanced/security/http-basic-auth.md index 06c6dbbab..599429f9d 100644 --- a/docs/zh/docs/advanced/security/http-basic-auth.md +++ b/docs/zh/docs/advanced/security/http-basic-auth.md @@ -20,35 +20,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 * 返回类型为 `HTTPBasicCredentials` 的对象: * 包含发送的 `username` 与 `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+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="2 6 10" -{!> ../../docs_src/security/tutorial006.py!} -``` - -//// +{* ../../docs_src/security/tutorial006_an_py39.py hl[4,8,12] *} 第一次打开 URL(或在 API 文档中点击 **Execute** 按钮)时,浏览器要求输入用户名与密码: @@ -68,35 +40,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 然后我们可以使用 `secrets.compare_digest()` 来确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。 -//// tab | Python 3.9+ - -```Python hl_lines="1 12-24" -{!> ../../docs_src/security/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 12-24" -{!> ../../docs_src/security/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="1 11-21" -{!> ../../docs_src/security/tutorial007.py!} -``` - -//// +{* ../../docs_src/security/tutorial007_an_py39.py hl[1,12:24] *} 这类似于: @@ -160,32 +104,4 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": 检测到凭证不正确后,返回 `HTTPException` 及状态码 401(与无凭证时返回的内容一样),并添加请求头 `WWW-Authenticate`,让浏览器再次显示登录提示: -//// tab | Python 3.9+ - -```Python hl_lines="26-30" -{!> ../../docs_src/security/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="26-30" -{!> ../../docs_src/security/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="23-27" -{!> ../../docs_src/security/tutorial007.py!} -``` - -//// +{* ../../docs_src/security/tutorial007_an_py39.py hl[26:30] *} diff --git a/docs/zh/docs/advanced/security/oauth2-scopes.md b/docs/zh/docs/advanced/security/oauth2-scopes.md index b26522113..c3f593684 100644 --- a/docs/zh/docs/advanced/security/oauth2-scopes.md +++ b/docs/zh/docs/advanced/security/oauth2-scopes.md @@ -62,9 +62,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 首先,快速浏览一下以下代码与**用户指南**中 [OAuth2 实现密码哈希与 Bearer JWT 令牌验证](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}一章中代码的区别。以下代码使用 OAuth2 作用域: -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[2,4,8,12,46,64,105,107:115,121:124,128:134,139,153] *} 下面,我们逐步说明修改的代码内容。 @@ -74,9 +72,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 `scopes` 参数接收**字典**,键是作用域、值是作用域的描述: -```Python hl_lines="62-65" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[62:65] *} 因为声明了作用域,所以登录或授权时会在 API 文档中显示。 @@ -102,9 +98,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 /// -```Python hl_lines="153" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[153] *} ## 在*路径操作*与依赖项中声明作用域 @@ -130,9 +124,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 /// -```Python hl_lines="4 139 166" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[4,139,166] *} /// info | 技术细节 @@ -158,9 +150,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 `SecuriScopes` 类与 `Request` 类似(`Request` 用于直接提取请求对象)。 -```Python hl_lines="8 105" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[8,105] *} ## 使用 `scopes` @@ -174,9 +164,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 该异常包含了作用域所需的(如有),以空格分割的字符串(使用 `scope_str`)。该字符串要放到包含作用域的 `WWW-Authenticate` 请求头中(这也是规范的要求)。 -```Python hl_lines="105 107-115" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[105,107:115] *} ## 校验 `username` 与数据形状 @@ -192,9 +180,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 还可以使用用户名验证用户,如果没有用户,也会触发之前创建的异常。 -```Python hl_lines="46 116-127" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[46,116:127] *} ## 校验 `scopes` @@ -202,9 +188,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 为此,要使用包含所有作用域**字符串列表**的 `security_scopes.scopes`, 。 -```Python hl_lines="128-134" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[128:134] *} ## 依赖项树与作用域 diff --git a/docs/zh/docs/advanced/settings.md b/docs/zh/docs/advanced/settings.md index 4d35731cb..e33da136f 100644 --- a/docs/zh/docs/advanced/settings.md +++ b/docs/zh/docs/advanced/settings.md @@ -150,9 +150,7 @@ Hello World from Python 您可以使用与 Pydantic 模型相同的验证功能和工具,比如不同的数据类型和使用 `Field()` 进行附加验证。 -```Python hl_lines="2 5-8 11" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} /// tip @@ -168,9 +166,7 @@ Hello World from Python 然后,您可以在应用程序中使用新的 `settings` 对象: -```Python hl_lines="18-20" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} ### 运行服务器 @@ -204,15 +200,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 例如,您可以创建一个名为 `config.py` 的文件,其中包含以下内容: -```Python -{!../../docs_src/settings/app01/config.py!} -``` +{* ../../docs_src/settings/app01/config.py *} 然后在一个名为 `main.py` 的文件中使用它: -```Python hl_lines="3 11-13" -{!../../docs_src/settings/app01/main.py!} -``` +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} /// tip @@ -230,9 +222,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 根据前面的示例,您的 `config.py` 文件可能如下所示: -```Python hl_lines="10" -{!../../docs_src/settings/app02/config.py!} -``` +{* ../../docs_src/settings/app02/config.py hl[10] *} 请注意,现在我们不创建默认实例 `settings = Settings()`。 @@ -240,35 +230,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 现在我们创建一个依赖项,返回一个新的 `config.Settings()`。 -//// tab | Python 3.9+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ 非注解版本 - -/// tip - -如果可能,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="5 11-12" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *} /// tip @@ -280,43 +242,13 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 然后,我们可以将其作为依赖项从“路径操作函数”中引入,并在需要时使用它。 -//// tab | Python 3.9+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ 非注解版本 - -/// tip - -如果可能,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="16 18-20" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *} ### 设置和测试 然后,在测试期间,通过创建 `get_settings` 的依赖项覆盖,很容易提供一个不同的设置对象: -```Python hl_lines="9-10 13 21" -{!../../docs_src/settings/app02/test_main.py!} -``` +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} 在依赖项覆盖中,我们在创建新的 `Settings` 对象时为 `admin_email` 设置了一个新值,然后返回该新对象。 @@ -357,9 +289,7 @@ APP_NAME="ChimichangApp" 然后,您可以使用以下方式更新您的 `config.py`: -```Python hl_lines="9-10" -{!../../docs_src/settings/app03/config.py!} -``` +{* ../../docs_src/settings/app03/config.py hl[9:10] *} 在这里,我们在 Pydantic 的 `Settings` 类中创建了一个名为 `Config` 的类,并将 `env_file` 设置为我们想要使用的 dotenv 文件的文件名。 @@ -392,35 +322,7 @@ def get_settings(): 但是,由于我们在顶部使用了 `@lru_cache` 装饰器,因此只有在第一次调用它时,才会创建 `Settings` 对象一次。 ✔️ -//// tab | Python 3.9+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ 非注解版本 - -/// tip - -如果可能,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="1 10" -{!> ../../docs_src/settings/app03/main.py!} -``` - -//// +{* ../../docs_src/settings/app03_an_py39/main.py hl[1,11] *} 然后,在下一次请求的依赖项中对 `get_settings()` 进行任何后续调用时,它不会执行 `get_settings()` 的内部代码并创建新的 `Settings` 对象,而是返回在第一次调用时返回的相同对象,一次又一次。 diff --git a/docs/zh/docs/advanced/sub-applications.md b/docs/zh/docs/advanced/sub-applications.md index f93ab1d24..c42be2849 100644 --- a/docs/zh/docs/advanced/sub-applications.md +++ b/docs/zh/docs/advanced/sub-applications.md @@ -10,9 +10,7 @@ 首先,创建主(顶层)**FastAPI** 应用及其*路径操作*: -```Python hl_lines="3 6-8" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[3,6:8] *} ### 子应用 @@ -20,9 +18,7 @@ 子应用只是另一个标准 FastAPI 应用,但这个应用是被**挂载**的应用: -```Python hl_lines="11 14-16" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,14:16] *} ### 挂载子应用 @@ -30,9 +26,7 @@ 本例的子应用挂载在 `/subapi` 路径下: -```Python hl_lines="11 19" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,19] *} ### 查看文档 diff --git a/docs/zh/docs/advanced/templates.md b/docs/zh/docs/advanced/templates.md index 7692aa47b..8b7019ede 100644 --- a/docs/zh/docs/advanced/templates.md +++ b/docs/zh/docs/advanced/templates.md @@ -27,9 +27,7 @@ $ pip install jinja2 * 在返回模板的*路径操作*中声明 `Request` 参数 * 使用 `templates` 渲染并返回 `TemplateResponse`, 传递模板的名称、request对象以及一个包含多个键值对(用于Jinja2模板)的"context"字典, -```Python hl_lines="4 11 15-16" -{!../../docs_src/templates/tutorial001.py!} -``` +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:16] *} /// note | 笔记 diff --git a/docs/zh/docs/advanced/testing-dependencies.md b/docs/zh/docs/advanced/testing-dependencies.md index b4b5b32df..620539fd1 100644 --- a/docs/zh/docs/advanced/testing-dependencies.md +++ b/docs/zh/docs/advanced/testing-dependencies.md @@ -28,9 +28,7 @@ 这样一来,**FastAPI** 就会调用覆盖依赖项,不再调用原依赖项。 -```Python hl_lines="26-27 30" -{!../../docs_src/dependency_testing/tutorial001.py!} -``` +{* ../../docs_src/dependency_testing/tutorial001.py hl[26:27,30] *} /// tip | 提示 diff --git a/docs/zh/docs/advanced/testing-events.md b/docs/zh/docs/advanced/testing-events.md index 00e661cd2..71b3739c3 100644 --- a/docs/zh/docs/advanced/testing-events.md +++ b/docs/zh/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ 使用 `TestClient` 和 `with` 语句,在测试中运行事件处理器(`startup` 与 `shutdown`)。 -```Python hl_lines="9-12 20-24" -{!../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/zh/docs/advanced/testing-websockets.md b/docs/zh/docs/advanced/testing-websockets.md index b30939b97..5d713d5f7 100644 --- a/docs/zh/docs/advanced/testing-websockets.md +++ b/docs/zh/docs/advanced/testing-websockets.md @@ -4,9 +4,7 @@ 为此,要在 `with` 语句中使用 `TestClient` 连接 WebSocket。 -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} /// note | 笔记 diff --git a/docs/zh/docs/advanced/using-request-directly.md b/docs/zh/docs/advanced/using-request-directly.md index f01644de6..db0fcafdf 100644 --- a/docs/zh/docs/advanced/using-request-directly.md +++ b/docs/zh/docs/advanced/using-request-directly.md @@ -29,9 +29,7 @@ 此时,需要直接访问请求。 -```Python hl_lines="1 7-8" -{!../../docs_src/using_request_directly/tutorial001.py!} -``` +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} 把*路径操作函数*的参数类型声明为 `Request`,**FastAPI** 就能把 `Request` 传递到参数里。 diff --git a/docs/zh/docs/advanced/websockets.md b/docs/zh/docs/advanced/websockets.md index dcd4cd5a9..d91aacc03 100644 --- a/docs/zh/docs/advanced/websockets.md +++ b/docs/zh/docs/advanced/websockets.md @@ -34,17 +34,13 @@ $ pip install websockets 但这是一种专注于 WebSockets 的服务器端并提供一个工作示例的最简单方式: -```Python hl_lines="2 6-38 41-43" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} ## 创建 `websocket` 在您的 **FastAPI** 应用程序中,创建一个 `websocket`: -```Python hl_lines="1 46-47" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} /// note | 技术细节 @@ -58,9 +54,7 @@ $ pip install websockets 在您的 WebSocket 路由中,您可以使用 `await` 等待消息并发送消息。 -```Python hl_lines="48-52" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} 您可以接收和发送二进制、文本和 JSON 数据。 @@ -109,57 +103,7 @@ $ uvicorn main:app --reload 它们的工作方式与其他 FastAPI 端点/ *路径操作* 相同: -//// tab | Python 3.10+ - -```Python hl_lines="68-69 82" -{!> ../../docs_src/websockets/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="68-69 82" -{!> ../../docs_src/websockets/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="69-70 83" -{!> ../../docs_src/websockets/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ 非带注解版本 - -/// tip - -如果可能,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="66-67 79" -{!> ../../docs_src/websockets/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ 非带注解版本 - -/// tip - -如果可能,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="68-69 81" -{!> ../../docs_src/websockets/tutorial002.py!} -``` - -//// +{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *} /// info @@ -200,21 +144,7 @@ $ uvicorn main:app --reload 当 WebSocket 连接关闭时,`await websocket.receive_text()` 将引发 `WebSocketDisconnect` 异常,您可以捕获并处理该异常,就像本示例中的示例一样。 -//// tab | Python 3.9+ - -```Python hl_lines="79-81" -{!> ../../docs_src/websockets/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="81-83" -{!> ../../docs_src/websockets/tutorial003.py!} -``` - -//// +{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *} 尝试以下操作: diff --git a/docs/zh/docs/advanced/wsgi.md b/docs/zh/docs/advanced/wsgi.md index 92bd998d0..363025a34 100644 --- a/docs/zh/docs/advanced/wsgi.md +++ b/docs/zh/docs/advanced/wsgi.md @@ -12,9 +12,7 @@ 之后将其挂载到某一个路径下。 -```Python hl_lines="2-3 22" -{!../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,22] *} ## 检查 diff --git a/docs/zh/docs/how-to/configure-swagger-ui.md b/docs/zh/docs/how-to/configure-swagger-ui.md index 1a2daeec1..108e0cb95 100644 --- a/docs/zh/docs/how-to/configure-swagger-ui.md +++ b/docs/zh/docs/how-to/configure-swagger-ui.md @@ -18,9 +18,7 @@ FastAPI会将这些配置转换为 **JSON**,使其与 JavaScript 兼容,因 但是你可以通过设置 `syntaxHighlight` 为 `False` 来禁用 Swagger UI 中的语法高亮: -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial001.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *} ...在此之后,Swagger UI 将不会高亮代码: @@ -30,9 +28,7 @@ FastAPI会将这些配置转换为 **JSON**,使其与 JavaScript 兼容,因 同样地,你也可以通过设置键 `"syntaxHighlight.theme"` 来设置语法高亮主题(注意中间有一个点): -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial002.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *} 这个配置会改变语法高亮主题: @@ -44,17 +40,13 @@ FastAPI 包含了一些默认配置参数,适用于大多数用例。 其包括这些默认配置参数: -```Python -{!../../fastapi/openapi/docs.py[ln:7-23]!} -``` +{* ../../fastapi/openapi/docs.py ln[7:23] *} 你可以通过在 `swagger_ui_parameters` 中设置不同的值来覆盖它们。 比如,如果要禁用 `deepLinking`,你可以像这样传递设置到 `swagger_ui_parameters` 中: -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial003.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *} ## 其他 Swagger UI 参数 diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md index dab6bd4c0..5126cb847 100644 --- a/docs/zh/docs/python-types.md +++ b/docs/zh/docs/python-types.md @@ -22,9 +22,8 @@ 让我们从一个简单的例子开始: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + 运行这段程序将输出: @@ -38,9 +37,8 @@ John Doe * 通过 `title()` 将每个参数的第一个字母转换为大写形式。 * 中间用一个空格来拼接它们。 -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### 修改示例 @@ -82,9 +80,8 @@ John Doe 这些就是"类型提示": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + 这和声明默认值是不同的,例如: @@ -112,9 +109,8 @@ John Doe 下面是一个已经有类型提示的函数: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + 因为编辑器已经知道了这些变量的类型,所以不仅能对代码进行补全,还能检查其中的错误: @@ -122,9 +118,8 @@ John Doe 现在你知道了必须先修复这个问题,通过 `str(age)` 把 `age` 转换成字符串: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## 声明类型 @@ -143,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### 嵌套类型 @@ -161,9 +155,8 @@ John Doe 从 `typing` 模块导入 `List`(注意是大写的 `L`): -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + 同样以冒号(`:`)来声明这个变量。 @@ -171,9 +164,8 @@ John Doe 由于列表是带有"子类型"的类型,所以我们把子类型放在方括号中: -```Python hl_lines="4" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + 这表示:"变量 `items` 是一个 `list`,并且这个列表里的每一个元素都是 `str`"。 @@ -191,9 +183,8 @@ John Doe 声明 `tuple` 和 `set` 的方法也是一样的: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + 这表示: @@ -208,9 +199,8 @@ John Doe 第二个子类型声明 `dict` 的所有值: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + 这表示: @@ -224,15 +214,13 @@ John Doe 假设你有一个名为 `Person` 的类,拥有 name 属性: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + 接下来,你可以将一个变量声明为 `Person` 类型: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + 然后,你将再次获得所有的编辑器支持: @@ -252,9 +240,8 @@ John Doe 下面的例子来自 Pydantic 官方文档: -```Python -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py *} + /// info diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md index 9aeb481ef..4cff58bfc 100644 --- a/docs/zh/docs/tutorial/body-fields.md +++ b/docs/zh/docs/tutorial/body-fields.md @@ -6,57 +6,7 @@ 首先,从 Pydantic 中导入 `Field`: -//// tab | Python 3.10+ - -```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 - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="2" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} /// warning | 警告 @@ -68,57 +18,7 @@ 然后,使用 `Field` 定义模型的属性: -//// 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` 的工作方式和 `Query`、`Path`、`Body` 相同,参数也相同。 diff --git a/docs/zh/docs/tutorial/body-multiple-params.md b/docs/zh/docs/tutorial/body-multiple-params.md index c3bc0db9e..b4356fdcb 100644 --- a/docs/zh/docs/tutorial/body-multiple-params.md +++ b/docs/zh/docs/tutorial/body-multiple-params.md @@ -8,57 +8,7 @@ 你还可以通过将默认值设置为 `None` 来将请求体参数声明为可选参数: -//// tab | Python 3.10+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="17-19" -{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} /// note @@ -81,21 +31,7 @@ 但是你也可以声明多个请求体参数,例如 `item` 和 `user`: -//// tab | Python 3.10+ - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} 在这种情况下,**FastAPI** 将注意到该函数中有多个请求体参数(两个 Pydantic 模型参数)。 @@ -137,57 +73,7 @@ 但是你可以使用 `Body` 指示 **FastAPI** 将其作为请求体的另一个键进行处理。 -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} 在这种情况下,**FastAPI** 将期望像这样的请求体: @@ -222,57 +108,7 @@ q: str = None 比如: -//// tab | Python 3.10+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="28" -{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="25" -{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *} /// info @@ -294,57 +130,7 @@ item: Item = Body(embed=True) 比如: -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="15" -{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} 在这种情况下,**FastAPI** 将期望像这样的请求体: diff --git a/docs/zh/docs/tutorial/body-nested-models.md b/docs/zh/docs/tutorial/body-nested-models.md index 316ba9878..df96d96b4 100644 --- a/docs/zh/docs/tutorial/body-nested-models.md +++ b/docs/zh/docs/tutorial/body-nested-models.md @@ -6,21 +6,7 @@ 你可以将一个属性定义为拥有子元素的类型。例如 Python `list`: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} 这将使 `tags` 成为一个由元素组成的列表。不过它没有声明每个元素的类型。 @@ -32,9 +18,7 @@ 首先,从 Python 的标准库 `typing` 模块中导入 `List`: -```Python hl_lines="1" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### 声明具有子类型的 List @@ -55,29 +39,7 @@ my_list: List[str] 因此,在我们的示例中,我们可以将 `tags` 明确地指定为一个「字符串列表」: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} ## Set 类型 @@ -87,29 +49,7 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se 然后我们可以导入 `Set` 并将 `tag` 声明为一个由 `str` 组成的 `set`: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 14" -{!> ../../docs_src/body_nested_models/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} 这样,即使你收到带有重复数据的请求,这些数据也会被转换为一组唯一项。 @@ -131,57 +71,13 @@ Pydantic 模型的每个属性都具有类型。 例如,我们可以定义一个 `Image` 模型: -//// tab | Python 3.10+ - -```Python hl_lines="7-9" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} ### 将子模型用作类型 然后我们可以将其用作一个属性的类型: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} 这意味着 **FastAPI** 将期望类似于以下内容的请求体: @@ -214,29 +110,7 @@ Pydantic 模型的每个属性都具有类型。 例如,在 `Image` 模型中我们有一个 `url` 字段,我们可以把它声明为 Pydantic 的 `HttpUrl`,而不是 `str`: -//// tab | Python 3.10+ - -```Python hl_lines="2 8" -{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} 该字符串将被检查是否为有效的 URL,并在 JSON Schema / OpenAPI 文档中进行记录。 @@ -244,29 +118,7 @@ Pydantic 模型的每个属性都具有类型。 你还可以将 Pydantic 模型用作 `list`、`set` 等的子类型: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} 这将期望(转换,校验,记录文档等)下面这样的 JSON 请求体: @@ -304,29 +156,7 @@ Pydantic 模型的每个属性都具有类型。 你可以定义任意深度的嵌套模型: -//// tab | Python 3.10+ - -```Python hl_lines="7 12 18 21 25" -{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} /// info @@ -344,21 +174,7 @@ images: List[Image] 例如: -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/body_nested_models/tutorial008.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} ## 无处不在的编辑器支持 @@ -388,21 +204,7 @@ images: List[Image] 在下面的例子中,你将接受任意键为 `int` 类型并且值为 `float` 类型的 `dict`: -//// tab | Python 3.9+ - -```Python hl_lines="7" -{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/body_nested_models/tutorial009.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} /// tip diff --git a/docs/zh/docs/tutorial/body-updates.md b/docs/zh/docs/tutorial/body-updates.md index 9372e1dfd..87f88f255 100644 --- a/docs/zh/docs/tutorial/body-updates.md +++ b/docs/zh/docs/tutorial/body-updates.md @@ -6,9 +6,7 @@ 把输入数据转换为以 JSON 格式存储的数据(比如,使用 NoSQL 数据库时),可以使用 `jsonable_encoder`。例如,把 `datetime` 转换为 `str`。 -```Python hl_lines="30-35" -{!../../docs_src/body_updates/tutorial001.py!} -``` +{* ../../docs_src/body_updates/tutorial001.py hl[30:35] *} `PUT` 用于接收替换现有数据的数据。 @@ -56,9 +54,7 @@ 然后再用它生成一个只含已设置(在请求中所发送)数据,且省略了默认值的 `dict`: -```Python hl_lines="34" -{!../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[34] *} ### 使用 Pydantic 的 `update` 参数 @@ -66,9 +62,7 @@ 例如,`stored_item_model.copy(update=update_data)`: -```Python hl_lines="35" -{!../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[35] *} ### 更新部分数据小结 @@ -85,9 +79,7 @@ * 把数据保存至数据库; * 返回更新后的模型。 -```Python hl_lines="30-37" -{!../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[30:37] *} /// tip | 提示 diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md index bf3117beb..3820fc747 100644 --- a/docs/zh/docs/tutorial/body.md +++ b/docs/zh/docs/tutorial/body.md @@ -22,21 +22,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 从 `pydantic` 中导入 `BaseModel`: -//// 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] *} ## 创建数据模型 @@ -44,21 +30,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 使用 Python 标准类型声明所有属性: -//// tab | Python 3.10+ - -```Python hl_lines="5-9" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7-11" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *} 与声明查询参数一样,包含默认值的模型属性是可选的,否则就是必选的。默认值为 `None` 的模型属性也是可选的。 @@ -86,21 +58,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 使用与声明路径和查询参数相同的方式声明请求体,把请求体添加至*路径操作*: -//// 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] *} ……此处,请求体参数的类型为 `Item` 模型。 @@ -167,21 +125,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 在*路径操作*函数内部直接访问模型对象的属性: -//// 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!} -``` - -//// +{* ../../docs_src/body/tutorial002_py310.py hl[19] *} ## 请求体 + 路径参数 @@ -189,21 +133,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 **FastAPI** 能识别与**路径参数**匹配的函数参数,还能识别从**请求体**中获取的类型为 Pydantic 模型的函数参数。 -//// tab | Python 3.10+ - -```Python hl_lines="15-16" -{!> ../../docs_src/body/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17-18" -{!> ../../docs_src/body/tutorial003.py!} -``` - -//// +{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *} ## 请求体 + 路径参数 + 查询参数 @@ -211,21 +141,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 **FastAPI** 能够正确识别这三种参数,并从正确的位置获取数据。 -//// 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] *} 函数参数按如下规则进行识别: diff --git a/docs/zh/docs/tutorial/cookie-params.md b/docs/zh/docs/tutorial/cookie-params.md index 762dca766..495600814 100644 --- a/docs/zh/docs/tutorial/cookie-params.md +++ b/docs/zh/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ 首先,导入 `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 - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## 声明 `Cookie` 参数 @@ -65,57 +15,7 @@ 第一个值是默认值,还可以传递所有验证参数或注释参数: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} /// note | 技术细节 diff --git a/docs/zh/docs/tutorial/cors.md b/docs/zh/docs/tutorial/cors.md index 84c435c97..a4f15f647 100644 --- a/docs/zh/docs/tutorial/cors.md +++ b/docs/zh/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * 特定的 HTTP 方法(`POST`,`PUT`)或者使用通配符 `"*"` 允许所有方法。 * 特定的 HTTP headers 或者使用通配符 `"*"` 允许所有 headers。 -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} 默认情况下,这个 `CORSMiddleware` 实现所使用的默认参数较为保守,所以你需要显式地启用特定的源、方法或者 headers,以便浏览器能够在跨域上下文中使用它们。 diff --git a/docs/zh/docs/tutorial/debugging.md b/docs/zh/docs/tutorial/debugging.md index a5afa1aaa..734b85565 100644 --- a/docs/zh/docs/tutorial/debugging.md +++ b/docs/zh/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ 在你的 FastAPI 应用中直接导入 `uvicorn` 并运行: -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### 关于 `__name__ == "__main__"` diff --git a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md index 917459d1d..f07280790 100644 --- a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,21 +6,7 @@ 在前面的例子中, 我们从依赖项 ("可依赖对象") 中返回了一个 `dict`: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_py310.py hl[7] *} 但是后面我们在路径操作函数的参数 `commons` 中得到了一个 `dict`。 @@ -83,57 +69,15 @@ fluffy = Cat(name="Mr Fluffy") 所以,我们可以将上面的依赖项 "可依赖对象" `common_parameters` 更改为类 `CommonQueryParams`: -//// tab | Python 3.10+ - -```Python hl_lines="9-13" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_py310.py hl[9:13] *} 注意用于创建类实例的 `__init__` 方法: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_py310.py hl[10] *} ...它与我们以前的 `common_parameters` 具有相同的参数: -//// tab | Python 3.10+ - -```Python hl_lines="6" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_py310.py hl[6] *} 这些参数就是 **FastAPI** 用来 "处理" 依赖项的。 @@ -149,21 +93,7 @@ fluffy = Cat(name="Mr Fluffy") 现在,您可以使用这个类来声明你的依赖项了。 -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_py310.py hl[17] *} **FastAPI** 调用 `CommonQueryParams` 类。这将创建该类的一个 "实例",该实例将作为参数 `commons` 被传递给你的函数。 @@ -203,21 +133,7 @@ commons = Depends(CommonQueryParams) ..就像: -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial003_py310.py hl[17] *} 但是声明类型是被鼓励的,因为那样你的编辑器就会知道将传递什么作为参数 `commons` ,然后它可以帮助你完成代码,类型检查,等等: @@ -251,21 +167,7 @@ commons: CommonQueryParams = Depends() 同样的例子看起来像这样: -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial004_py310.py hl[17] *} ... **FastAPI** 会知道怎么处理。 diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index c202c977b..51b3e9fc3 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,9 +14,7 @@ 该参数的值是由 `Depends()` 组成的 `list`: -```Python hl_lines="17" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[17] *} 路径操作装饰器依赖项(以下简称为**“路径装饰器依赖项”**)的执行或解析方式和普通依赖项一样,但就算这些依赖项会返回值,它们的值也不会传递给*路径操作函数*。 @@ -46,17 +44,13 @@ 路径装饰器依赖项可以声明请求的需求项(比如响应头)或其他子依赖项: -```Python hl_lines="6 11" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[6,11] *} ### 触发异常 路径装饰器依赖项与正常的依赖项一样,可以 `raise` 异常: -```Python hl_lines="8 13" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[8,13] *} ### 返回值 @@ -64,9 +58,7 @@ 因此,可以复用在其他位置使用过的、(能返回值的)普通依赖项,即使没有使用这个值,也会执行该依赖项: -```Python hl_lines="9 14" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[9,14] *} ## 为一组路径操作定义依赖项 diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md index 792b6784d..a863bb861 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md @@ -29,21 +29,15 @@ FastAPI支持在完成后执行一些 ../../docs_src/dependencies/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17-18 25-26" -{!> ../../docs_src/dependencies/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | 提示 - -如果可以,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="16-17 24-25" -{!> ../../docs_src/dependencies/tutorial008.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *} 同样,你可以混合使用带有 `yield` 或 `return` 的依赖。 @@ -170,35 +106,7 @@ FastAPI支持在完成后执行一些 ../../docs_src/dependencies/tutorial008c_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14-15" -{!> ../../docs_src/dependencies/tutorial008c_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | 提示 - -如果可以,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="13-14" -{!> ../../docs_src/dependencies/tutorial008c.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *} 在示例代码的情况下,客户端将会收到 *HTTP 500 Internal Server Error* 的响应,因为我们没有抛出 `HTTPException` 或者类似的异常,并且服务器也 **不会有任何日志** 或者其他提示来告诉我们错误是什么。😱 @@ -244,35 +124,7 @@ FastAPI支持在完成后执行一些união entre tipos diferentes onde um ou mais deles não são tipos Pydantic válidos, por exemplo, isso falharia 💥: + +{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *} + +... isso falha porque a anotação de tipo não é um tipo Pydantic e não é apenas uma única classe ou subclasse `Response`, é uma união (qualquer uma das duas) entre um `Response` e ​​um `dict`. + +### Desabilitar modelo de resposta + +Continuando com o exemplo acima, você pode não querer ter a validação de dados padrão, documentação, filtragem, etc. que é realizada pelo FastAPI. + +Mas você pode querer manter a anotação do tipo de retorno na função para obter o suporte de ferramentas como editores e verificadores de tipo (por exemplo, mypy). + +Neste caso, você pode desabilitar a geração do modelo de resposta definindo `response_model=None`: + +{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *} + +Isso fará com que o FastAPI pule a geração do modelo de resposta e, dessa forma, você pode ter quaisquer anotações de tipo de retorno que precisar sem afetar seu aplicativo FastAPI. 🤓 + +## Parâmetros de codificação do modelo de resposta + +Seu modelo de resposta pode ter valores padrão, como: + +{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *} + +* `description: Union[str, None] = None` (ou `str | None = None` no Python 3.10) tem um padrão de `None`. +* `tax: float = 10.5` tem um padrão de `10.5`. +* `tags: List[str] = []` tem um padrão de uma lista vazia: `[]`. + +mas você pode querer omiti-los do resultado se eles não foram realmente armazenados. + +Por exemplo, se você tem modelos com muitos atributos opcionais em um banco de dados NoSQL, mas não quer enviar respostas JSON muito longas cheias de valores padrão. + +### Usar o parâmetro `response_model_exclude_unset` + +Você pode definir o parâmetro `response_model_exclude_unset=True` do *decorador de operação de rota* : + +{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *} + +e esses valores padrão não serão incluídos na resposta, apenas os valores realmente definidos. + +Então, se você enviar uma solicitação para essa *operação de rota* para o item com ID `foo`, a resposta (sem incluir valores padrão) será: + +```JSON +{ +"name": "Foo", +"price": 50.2 +} +``` + +/// info | Informação + +No Pydantic v1, o método era chamado `.dict()`, ele foi descontinuado (mas ainda suportado) no Pydantic v2 e renomeado para `.model_dump()`. + +Os exemplos aqui usam `.dict()` para compatibilidade com Pydantic v1, mas você deve usar `.model_dump()` em vez disso se puder usar Pydantic v2. + +/// + +/// info | Informação + +O FastAPI usa `.dict()` do modelo Pydantic com seu parâmetro `exclude_unset` para chegar a isso. + +/// + +/// info | Informação + +Você também pode usar: + +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` + +conforme descrito na documentação do Pydantic para `exclude_defaults` e `exclude_none`. + +/// + +#### Dados com valores para campos com padrões + +Mas se seus dados tiverem valores para os campos do modelo com valores padrões, como o item com ID `bar`: + +```Python hl_lines="3 5" +{ +"name": "Bar", +"description": "The bartenders", +"price": 62, +"tax": 20.2 +} +``` + +eles serão incluídos na resposta. + +#### Dados com os mesmos valores que os padrões + +Se os dados tiverem os mesmos valores que os padrões, como o item com ID `baz`: + +```Python hl_lines="3 5-6" +{ +"name": "Baz", +"description": None, +"price": 50.2, +"tax": 10.5, +"tags": [] +} +``` + +O FastAPI é inteligente o suficiente (na verdade, o Pydantic é inteligente o suficiente) para perceber que, embora `description`, `tax` e `tags` tenham os mesmos valores que os padrões, eles foram definidos explicitamente (em vez de retirados dos padrões). + +Portanto, eles serão incluídos na resposta JSON. + +/// tip | Dica + +Observe que os valores padrão podem ser qualquer coisa, não apenas `None`. + +Eles podem ser uma lista (`[]`), um `float` de `10.5`, etc. + +/// + +### `response_model_include` e `response_model_exclude` + +Você também pode usar os parâmetros `response_model_include` e `response_model_exclude` do *decorador de operação de rota*. + +Eles pegam um `set` de `str` com o nome dos atributos para incluir (omitindo o resto) ou para excluir (incluindo o resto). + +Isso pode ser usado como um atalho rápido se você tiver apenas um modelo Pydantic e quiser remover alguns dados da saída. + +/// tip | Dica + +Mas ainda é recomendado usar as ideias acima, usando várias classes, em vez desses parâmetros. + +Isso ocorre porque o Schema JSON gerado no OpenAPI do seu aplicativo (e a documentação) ainda será o único para o modelo completo, mesmo que você use `response_model_include` ou `response_model_exclude` para omitir alguns atributos. + +Isso também se aplica ao `response_model_by_alias` que funciona de forma semelhante. + +/// + +{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *} + +/// tip | Dica + +A sintaxe `{"nome", "descrição"}` cria um `conjunto` com esses dois valores. + +É equivalente a `set(["nome", "descrição"])`. + +/// + +#### Usando `list`s em vez de `set`s + +Se você esquecer de usar um `set` e usar uma `lista` ou `tupla` em vez disso, o FastAPI ainda o converterá em um `set` e funcionará corretamente: + +{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *} + +## Recapitulação + +Use o parâmetro `response_model` do *decorador de operação de rota* para definir modelos de resposta e, especialmente, para garantir que dados privados sejam filtrados. + +Use `response_model_exclude_unset` para retornar apenas os valores definidos explicitamente. From a96dddb6fdcb90e0c36fde5c4e21542903625e96 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 26 Nov 2024 22:51:31 +0000 Subject: [PATCH 477/932] =?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 [skip ci] --- 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 e25d4d8e3..e355ff14d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/response-model.md`. PR [#12933](https://github.com/fastapi/fastapi/pull/12933) by [@AndreBBM](https://github.com/AndreBBM). * 🌐 Add Korean translation for `docs/ko/docs/advanced/middlewares.md`. PR [#12753](https://github.com/fastapi/fastapi/pull/12753) by [@nahyunkeem](https://github.com/nahyunkeem). * 🌐 Add Korean translation for `docs/ko/docs/advanced/openapi-webhooks.md`. PR [#12752](https://github.com/fastapi/fastapi/pull/12752) by [@saeye](https://github.com/saeye). * 🌐 Add Chinese translation for `docs/zh/docs/tutorial/query-param-models.md`. PR [#12931](https://github.com/fastapi/fastapi/pull/12931) by [@Vincy1230](https://github.com/Vincy1230). From 478644086ec8aabffd2646b0c096a614f2acfafc Mon Sep 17 00:00:00 2001 From: LKY <74170199+kwang1215@users.noreply.github.com> Date: Thu, 28 Nov 2024 05:03:29 +0900 Subject: [PATCH 478/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/advanced/websockets.md`=20(#12991)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/advanced/websockets.md | 186 ++++++++++++++++++++++++++++ 1 file changed, 186 insertions(+) create mode 100644 docs/ko/docs/advanced/websockets.md diff --git a/docs/ko/docs/advanced/websockets.md b/docs/ko/docs/advanced/websockets.md new file mode 100644 index 000000000..fa60a428b --- /dev/null +++ b/docs/ko/docs/advanced/websockets.md @@ -0,0 +1,186 @@ +# WebSockets + +여러분은 **FastAPI**에서 WebSockets를 사용할 수 있습니다. + +## `WebSockets` 설치 + +[가상 환경](../virtual-environments.md){.internal-link target=_blank)를 생성하고 활성화한 다음, `websockets`를 설치하세요: + +
+ +```console +$ pip install websockets + +---> 100% +``` + +
+ +## WebSockets 클라이언트 + +### 프로덕션 환경에서 + +여러분의 프로덕션 시스템에서는 React, Vue.js 또는 Angular와 같은 최신 프레임워크로 생성된 프런트엔드를 사용하고 있을 가능성이 높습니다. + +백엔드와 WebSockets을 사용해 통신하려면 아마도 프런트엔드의 유틸리티를 사용할 것입니다. + +또는 네이티브 코드로 WebSocket 백엔드와 직접 통신하는 네이티브 모바일 응용 프로그램을 가질 수도 있습니다. + +혹은 WebSocket 엔드포인트와 통신할 수 있는 다른 방법이 있을 수도 있습니다. + +--- + +하지만 이번 예제에서는 일부 자바스크립트를 포함한 간단한 HTML 문서를 사용하겠습니다. 모든 것을 긴 문자열 안에 넣습니다. + +물론, 이는 최적의 방법이 아니며 프로덕션 환경에서는 사용하지 않을 것입니다. + +프로덕션 환경에서는 위에서 설명한 옵션 중 하나를 사용하는 것이 좋습니다. + +그러나 이는 WebSockets의 서버 측에 집중하고 동작하는 예제를 제공하는 가장 간단한 방법입니다: + +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} + +## `websocket` 생성하기 + +**FastAPI** 응용 프로그램에서 `websocket`을 생성합니다: + +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} + +/// note | 기술적 세부사항 + +`from starlette.websockets import WebSocket`을 사용할 수도 있습니다. + +**FastAPI**는 개발자를 위한 편의를 위해 동일한 `WebSocket`을 직접 제공합니다. 하지만 이는 Starlette에서 가져옵니다. + +/// + +## 메시지를 대기하고 전송하기 + +WebSocket 경로에서 메시지를 대기(`await`)하고 전송할 수 있습니다. + +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} + +여러분은 이진 데이터, 텍스트, JSON 데이터를 받을 수 있고 전송할 수 있습니다. + +## 시도해보기 + +파일 이름이 `main.py`라고 가정하고 응용 프로그램을 실행합니다: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +브라우저에서 http://127.0.0.1:8000을 열어보세요. + +간단한 페이지가 나타날 것입니다: + + + +입력창에 메시지를 입력하고 전송할 수 있습니다: + + + +**FastAPI** WebSocket 응용 프로그램이 응답을 돌려줄 것입니다: + + + +여러 메시지를 전송(그리고 수신)할 수 있습니다: + + + +모든 메시지는 동일한 WebSocket 연결을 사용합니다. + +## `Depends` 및 기타 사용하기 + +WebSocket 엔드포인트에서 `fastapi`에서 다음을 가져와 사용할 수 있습니다: + +* `Depends` +* `Security` +* `Cookie` +* `Header` +* `Path` +* `Query` + +이들은 다른 FastAPI 엔드포인트/*경로 작동*과 동일하게 동작합니다: + +{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *} + +/// info | 정보 + +WebSocket에서는 `HTTPException`을 발생시키는 것이 적합하지 않습니다. 대신 `WebSocketException`을 발생시킵니다. + +명세서에 정의된 유효한 코드를 사용하여 종료 코드를 설정할 수 있습니다. + +/// + +### 종속성을 가진 WebSockets 테스트 + +파일 이름이 `main.py`라고 가정하고 응용 프로그램을 실행합니다: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +브라우저에서 http://127.0.0.1:8000을 열어보세요. + +다음과 같은 값을 설정할 수 있습니다: + +* 경로에 사용된 "Item ID". +* 쿼리 매개변수로 사용된 "Token". + +/// tip | 팁 + +쿼리 `token`은 종속성에 의해 처리됩니다. + +/// + +이제 WebSocket에 연결하고 메시지를 전송 및 수신할 수 있습니다: + + + +## 연결 해제 및 다중 클라이언트 처리 + +WebSocket 연결이 닫히면, `await websocket.receive_text()`가 `WebSocketDisconnect` 예외를 발생시킵니다. 이를 잡아 처리할 수 있습니다: + +{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *} + +테스트해보기: + +* 여러 브라우저 탭에서 앱을 엽니다. +* 각 탭에서 메시지를 작성합니다. +* 한 탭을 닫아보세요. + +`WebSocketDisconnect` 예외가 발생하며, 다른 모든 클라이언트가 다음과 같은 메시지를 수신합니다: + +``` +Client #1596980209979 left the chat +``` + +/// tip | 팁 + +위 응용 프로그램은 여러 WebSocket 연결에 메시지를 브로드캐스트하는 방법을 보여주는 간단한 예제입니다. + +그러나 모든 것을 메모리의 단일 리스트로 처리하므로, 프로세스가 실행 중인 동안만 동작하며 단일 프로세스에서만 작동합니다. + +FastAPI와 쉽게 통합할 수 있으면서 더 견고하고 Redis, PostgreSQL 등을 지원하는 도구를 찾고 있다면, encode/broadcaster를 확인하세요. + +/// + +## 추가 정보 + +다음 옵션에 대한 자세한 내용을 보려면 Starlette의 문서를 확인하세요: + +* `WebSocket` 클래스. +* 클래스 기반 WebSocket 처리. From 206037c292d49a944c8a6da29eed350efafd7268 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 27 Nov 2024 20:03:52 +0000 Subject: [PATCH 479/932] =?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 [skip ci] --- 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 e355ff14d..eec061ea5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/advanced/websockets.md`. PR [#12991](https://github.com/fastapi/fastapi/pull/12991) by [@kwang1215](https://github.com/kwang1215). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/response-model.md`. PR [#12933](https://github.com/fastapi/fastapi/pull/12933) by [@AndreBBM](https://github.com/AndreBBM). * 🌐 Add Korean translation for `docs/ko/docs/advanced/middlewares.md`. PR [#12753](https://github.com/fastapi/fastapi/pull/12753) by [@nahyunkeem](https://github.com/nahyunkeem). * 🌐 Add Korean translation for `docs/ko/docs/advanced/openapi-webhooks.md`. PR [#12752](https://github.com/fastapi/fastapi/pull/12752) by [@saeye](https://github.com/saeye). From d75b81ce3f15ff22cbecd7bc399d321de8621889 Mon Sep 17 00:00:00 2001 From: Chol_rang Date: Thu, 28 Nov 2024 07:12:04 +0900 Subject: [PATCH 480/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/advanced/testing-dependencies.md`=20(#?= =?UTF-8?q?12992)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/advanced/testing-dependencies.md | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 docs/ko/docs/advanced/testing-dependencies.md diff --git a/docs/ko/docs/advanced/testing-dependencies.md b/docs/ko/docs/advanced/testing-dependencies.md new file mode 100644 index 000000000..780e19431 --- /dev/null +++ b/docs/ko/docs/advanced/testing-dependencies.md @@ -0,0 +1,53 @@ +# 테스트 의존성 오버라이드 + +## 테스트 중 의존성 오버라이드하기 + +테스트를 진행하다 보면 의존성을 오버라이드해야 하는 경우가 있습니다. + +원래 의존성을 실행하고 싶지 않을 수도 있습니다(또는 그 의존성이 가지고 있는 하위 의존성까지도 실행되지 않길 원할 수 있습니다). + +대신, 테스트 동안(특정 테스트에서만) 사용될 다른 의존성을 제공하고, 원래 의존성이 사용되던 곳에서 사용할 수 있는 값을 제공하기를 원할 수 있습니다. + +### 사용 사례: 외부 서비스 + +예를 들어, 외부 인증 제공자를 호출해야 하는 경우를 생각해봅시다. + +토큰을 보내면 인증된 사용자를 반환합니다. + +제공자는 요청당 요금을 부과할 수 있으며, 테스트를 위해 고정된 모의 사용자가 있는 경우보다 호출하는 데 시간이 더 걸릴 수 있습니다. + +외부 제공자를 한 번만 테스트하고 싶을 수도 있지만 테스트를 실행할 때마다 반드시 호출할 필요는 없습니다. + +이 경우 해당 공급자를 호출하는 종속성을 오버라이드하고 테스트에 대해서만 모의 사용자를 반환하는 사용자 지정 종속성을 사용할 수 있습니다. + +### `app.dependency_overrides` 속성 사용하기 + +이런 경우를 위해 **FastAPI** 응용 프로그램에는 `app.dependency_overrides`라는 속성이 있습니다. 이는 간단한 `dict`입니다. + +테스트를 위해 의존성을 오버라이드하려면, 원래 의존성(함수)을 키로 설정하고 오버라이드할 의존성(다른 함수)을 값으로 설정합니다. + +그럼 **FastAPI**는 원래 의존성 대신 오버라이드된 의존성을 호출합니다. + +{* ../../docs_src/dependency_testing/tutorial001_an_py310.py hl[26:27,30] *} + +/// tip | 팁 + +**FastAPI** 애플리케이션 어디에서든 사용된 의존성에 대해 오버라이드를 설정할 수 있습니다. + +원래 의존성은 *경로 동작 함수*, *경로 동작 데코레이터*(반환값을 사용하지 않는 경우), `.include_router()` 호출 등에서 사용될 수 있습니다. + +FastAPI는 여전히 이를 오버라이드할 수 있습니다. + +/// + +그런 다음, `app.dependency_overrides`를 빈 `dict`로 설정하여 오버라이드를 재설정(제거)할 수 있습니다: + +```python +app.dependency_overrides = {} +``` + +/// tip | 팁 + +특정 테스트에서만 의존성을 오버라이드하고 싶다면, 테스트 시작 시(테스트 함수 내부) 오버라이드를 설정하고 테스트 종료 시(테스트 함수 끝부분) 재설정하면 됩니다. + +/// From 6c7873c77e3846b3ea6db9101af27a236652df09 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 27 Nov 2024 22:12:28 +0000 Subject: [PATCH 481/932] =?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 [skip ci] --- 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 eec061ea5..2bad05f3f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/advanced/testing-dependencies.md`. PR [#12992](https://github.com/fastapi/fastapi/pull/12992) by [@Limsunoh](https://github.com/Limsunoh). * 🌐 Add Korean translation for `docs/ko/docs/advanced/websockets.md`. PR [#12991](https://github.com/fastapi/fastapi/pull/12991) by [@kwang1215](https://github.com/kwang1215). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/response-model.md`. PR [#12933](https://github.com/fastapi/fastapi/pull/12933) by [@AndreBBM](https://github.com/AndreBBM). * 🌐 Add Korean translation for `docs/ko/docs/advanced/middlewares.md`. PR [#12753](https://github.com/fastapi/fastapi/pull/12753) by [@nahyunkeem](https://github.com/nahyunkeem). From 8376228a493e5d8e0296e5750e5d0465e93f63b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E9=9B=B2=E6=98=94=20=28Vincy=20SHI=29?= Date: Thu, 28 Nov 2024 06:14:10 +0800 Subject: [PATCH 482/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Traditional=20Chin?= =?UTF-8?q?ese=20translation=20for=20`docs/zh-hant/docs/tutorial/query-par?= =?UTF-8?q?am-models.md`=20(#12932)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/tutorial/query-param-models.md | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 docs/zh-hant/docs/tutorial/query-param-models.md diff --git a/docs/zh-hant/docs/tutorial/query-param-models.md b/docs/zh-hant/docs/tutorial/query-param-models.md new file mode 100644 index 000000000..76ee74016 --- /dev/null +++ b/docs/zh-hant/docs/tutorial/query-param-models.md @@ -0,0 +1,68 @@ +# 查詢參數模型 + +如果你有一組具有相關性的**查詢參數**,你可以建立一個 **Pydantic 模型**來聲明它們。 + +這將允許你在**多個地方**去**重複使用模型**,並且一次性為所有參數聲明驗證和元資料 (metadata)。😎 + +/// note + +FastAPI 從 `0.115.0` 版本開始支援這個特性。🤓 + +/// + +## 使用 Pydantic 模型的查詢參數 + +在一個 **Pydantic 模型**中聲明你需要的**查詢參數**,然後將參數聲明為 `Query`: + +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} + +**FastAPI** 將會從請求的**查詢參數**中**提取**出**每個欄位**的資料,並將其提供給你定義的 Pydantic 模型。 + +## 查看文件 + +你可以在 `/docs` 頁面的 UI 中查看查詢參數: + +
+ +
+ +## 禁止額外的查詢參數 + +在一些特殊的使用場景中(可能不是很常見),你可能希望**限制**你要收到的查詢參數。 + +你可以使用 Pydantic 的模型設定來 `forbid`(禁止)任何 `extra`(額外)欄位: + +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} + +如果客戶端嘗試在**查詢參數**中發送一些**額外的**資料,他們將會收到一個**錯誤**回應。 + +例如,如果客戶端嘗試發送一個值為 `plumbus` 的 `tool` 查詢參數,如: + +```http +https://example.com/items/?limit=10&tool=plumbus +``` + +他們將收到一個**錯誤**回應,告訴他們查詢參數 `tool` 是不允許的: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus" + } + ] +} +``` + +## 總結 + +你可以使用 **Pydantic 模型**在 **FastAPI** 中聲明**查詢參數**。😎 + +/// tip + +劇透警告:你也可以使用 Pydantic 模型來聲明 cookie 和 headers,但你將在本教學的後面部分閱讀到這部分內容。🤫 + +/// From 297135244d0adee68d5624b3a3cfa35057abdc0e Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 27 Nov 2024 22:14:38 +0000 Subject: [PATCH 483/932] =?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 [skip ci] --- 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 2bad05f3f..f9661c394 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Translations +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/tutorial/query-param-models.md`. PR [#12932](https://github.com/fastapi/fastapi/pull/12932) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Add Korean translation for `docs/ko/docs/advanced/testing-dependencies.md`. PR [#12992](https://github.com/fastapi/fastapi/pull/12992) by [@Limsunoh](https://github.com/Limsunoh). * 🌐 Add Korean translation for `docs/ko/docs/advanced/websockets.md`. PR [#12991](https://github.com/fastapi/fastapi/pull/12991) by [@kwang1215](https://github.com/kwang1215). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/response-model.md`. PR [#12933](https://github.com/fastapi/fastapi/pull/12933) by [@AndreBBM](https://github.com/AndreBBM). From 53c87842b0a756375f93e78027b43b721b3eb9cf Mon Sep 17 00:00:00 2001 From: ILoveTakanashiHoshino <114038930+ILoveSorasakiHina@users.noreply.github.com> Date: Thu, 28 Nov 2024 07:10:08 +0800 Subject: [PATCH 484/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Traditional=20Chin?= =?UTF-8?q?ese=20translation=20for=20`docs/zh-hant/docs/async.md`=20(#1299?= =?UTF-8?q?0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/async.md | 442 +++++++++++++++++++++++++++++++++++++ 1 file changed, 442 insertions(+) create mode 100644 docs/zh-hant/docs/async.md diff --git a/docs/zh-hant/docs/async.md b/docs/zh-hant/docs/async.md new file mode 100644 index 000000000..6ab75d2ab --- /dev/null +++ b/docs/zh-hant/docs/async.md @@ -0,0 +1,442 @@ +# 並行與 async / await + +有關*路徑操作函式*的 `async def` 語法的細節與非同步 (asynchronous) 程式碼、並行 (concurrency) 與平行 (parallelism) 的一些背景知識。 + +## 趕時間嗎? + +TL;DR: + +如果你正在使用要求你以 `await` 語法呼叫的第三方函式庫,例如: + +```Python +results = await some_library() +``` + +然後,使用 `async def` 宣告你的*路徑操作函式*: + + +```Python hl_lines="2" +@app.get('/') +async def read_results(): + results = await some_library() + return results +``` + +/// note | 注意 + +你只能在 `async def` 建立的函式內使用 `await`。 + +/// + +--- + +如果你使用的是第三方函式庫並且它需要與某些外部資源(例如資料庫、API、檔案系統等)進行通訊,但不支援 `await`(目前大多數資料庫函式庫都是這樣),在這種情況下,你可以像平常一樣使用 `def` 宣告*路徑操作函式*,如下所示: + +```Python hl_lines="2" +@app.get('/') +def results(): + results = some_library() + return results +``` + +--- + +如果你的應用程式不需要與外部資源進行任何通訊並等待其回應,請使用 `async def`。 + +--- + +如果你不確定該用哪個,直接用 `def` 就好。 + +--- + +**注意**:你可以在*路徑操作函式*中混合使用 `def` 和 `async def` ,並使用最適合你需求的方式來定義每個函式。FastAPI 會幫你做正確的處理。 + +無論如何,在上述哪種情況下,FastAPI 仍將以非同步方式運行,並且速度非常快。 + +但透過遵循上述步驟,它將能進行一些效能最佳化。 + +## 技術細節 + +現代版本的 Python 支援使用 **「協程」** 的 **`async` 和 `await`** 語法來寫 **「非同步程式碼」**。 + +接下來我們逐一介紹: + +* **非同步程式碼** +* **`async` 和 `await`** +* **協程** + +## 非同步程式碼 + +非同步程式碼僅意味著程式語言 💬 有辦法告訴電腦/程式 🤖 在程式碼中的某個點,它 🤖 需要等待某些事情完成。讓我們假設這些事情被稱為「慢速檔案」📝。 + +因此,在等待「慢速檔案」📝 完成的這段時間,電腦可以去處理一些其他工作。 + +接著程式 🤖 會在有空檔時回來查看是否有等待的工作已經完成,並執行必要的後續操作。 + +接下來,它 🤖 完成第一個工作(例如我們的「慢速檔案」📝)並繼續執行相關的所有操作。 +這個「等待其他事情」通常指的是一些相對較慢的(與處理器和 RAM 記憶體的速度相比)的 I/O 操作,比如說: + +* 透過網路傳送來自用戶端的資料 +* 從網路接收來自用戶端的資料 +* 從磁碟讀取檔案內容 +* 將內容寫入磁碟 +* 遠端 API 操作 +* 資料庫操作 +* 資料庫查詢 +* 等等 + +由於大部分的執行時間都消耗在等待 I/O 操作上,因此這些操作被稱為 "I/O 密集型" 操作。 + +之所以稱為「非同步」,是因為電腦/程式不需要與那些耗時的任務「同步」,等待任務完成的精確時間,然後才能取得結果並繼續工作。 + +相反地,非同步系統在任務完成後,可以讓任務稍微等一下(幾微秒),等待電腦/程式完成手頭上的其他工作,然後再回來取得結果繼續進行。 + +相對於「非同步」(asynchronous),「同步」(synchronous)也常被稱作「順序性」(sequential),因為電腦/程式會依序執行所有步驟,即便這些步驟涉及等待,才會切換到其他任務。 + +### 並行與漢堡 + +上述非同步程式碼的概念有時也被稱為「並行」,它不同於「平行」。 + +並行和平行都與 "不同的事情或多或少同時發生" 有關。 + +但並行和平行之間的細節是完全不同的。 + +為了理解差異,請想像以下有關漢堡的故事: + +### 並行漢堡 + +你和你的戀人去速食店,排隊等候時,收銀員正在幫排在你前面的人點餐。😍 + + + +輪到你了,你給你與你的戀人點了兩個豪華漢堡。🍔🍔 + + + +收銀員通知廚房準備你的漢堡(儘管他們還在為前面其他顧客準備食物)。 + + + +之後你完成付款。💸 + +收銀員給你一個號碼牌。 + + + +在等待漢堡的同時,你可以與戀人選一張桌子,然後坐下來聊很長一段時間(因為漢堡十分豪華,準備特別費工。) + +這段時間,你還能欣賞你的戀人有多麼的可愛、聰明與迷人。✨😍✨ + + + +當你和戀人邊聊天邊等待時,你會不時地查看櫃檯上的顯示的號碼,確認是否已經輪到你了。 + +然後在某個時刻,終於輪到你了。你走到櫃檯,拿了漢堡,然後回到桌子上。 + + + +你和戀人享用這頓大餐,整個過程十分開心✨ + + + +/// info + +漂亮的插畫來自 Ketrina Thompson. 🎨 + +/// + +--- + +想像你是故事中的電腦或程式 🤖。 + +當你排隊時,你在放空😴,等待輪到你,沒有做任何「生產性」的事情。但這沒關係,因為收銀員只是接單(而不是準備食物),所以排隊速度很快。 + +然後,當輪到你時,你開始做真正「有生產力」的工作,處理菜單,決定你想要什麼,替戀人選擇餐點,付款,確認你給了正確的帳單或信用卡,檢查你是否被正確收費,確認訂單中的項目是否正確等等。 + +但是,即使你還沒有拿到漢堡,你與收銀員的工作已經「暫停」了 ⏸,因為你必須等待 🕙 漢堡準備好。 + +但當你離開櫃檯,坐到桌子旁,拿著屬於你的號碼等待時,你可以把注意力 🔀 轉移到戀人身上,並開始「工作」⏯ 🤓——也就是和戀人調情 😍。這時你又開始做一些非常「有生產力」的事情。 + +接著,收銀員 💁 將你的號碼顯示在櫃檯螢幕上,並告訴你「漢堡已經做好了」。但你不會瘋狂地立刻跳起來,因為顯示的號碼變成了你的。你知道沒有人會搶走你的漢堡,因為你有自己的號碼,他們也有他們的號碼。 + +所以你會等戀人講完故事(完成當前的工作 ⏯/正在進行的任務 🤓),然後微笑著溫柔地說你要去拿漢堡了 ⏸。 + +然後你走向櫃檯 🔀,回到已經完成的最初任務 ⏯,拿起漢堡,說聲謝謝,並帶回桌上。這就結束了與櫃檯的互動步驟/任務 ⏹,接下來會產生一個新的任務,「吃漢堡」 🔀 ⏯,而先前的「拿漢堡」任務已經完成了 ⏹。 + +### 平行漢堡 + +現在,讓我們來想像這裡不是「並行漢堡」,而是「平行漢堡」。 + +你和戀人一起去吃平行的速食餐。 + +你們站在隊伍中,前面有幾位(假設有 8 位)既是收銀員又是廚師的員工,他們同時接單並準備餐點。 + +所有排在你前面的人都在等著他們的漢堡準備好後才會離開櫃檯,因為每位收銀員在接完單後,馬上會去準備漢堡,然後才回來處理下一個訂單。 + + + +終於輪到你了,你為你和你的戀人點了兩個非常豪華的漢堡。 + +你付款了 💸。 + + + +收銀員走進廚房準備食物。 + +你站在櫃檯前等待 🕙,以免其他人先拿走你的漢堡,因為這裡沒有號碼牌系統。 + + + +由於你和戀人都忙著不讓別人搶走你的漢堡,等漢堡準備好時,你根本無法專心和戀人互動。😞 + +這是「同步」(synchronous)工作,你和收銀員/廚師 👨‍🍳 是「同步化」的。你必須等到 🕙 收銀員/廚師 👨‍🍳 完成漢堡並交給你的那一刻,否則別人可能會拿走你的餐點。 + + + +最終,經過長時間的等待 🕙,收銀員/廚師 👨‍🍳 拿著漢堡回來了。 + + + +你拿著漢堡,和你的戀人回到餐桌。 + +你們僅僅是吃完漢堡,然後就結束了。⏹ + + + +整個過程中沒有太多的談情說愛,因為大部分時間 🕙 都花在櫃檯前等待。😞 + +/// info + +漂亮的插畫來自 Ketrina Thompson. 🎨 + +/// + +--- + +在這個平行漢堡的情境下,你是一個程式 🤖 且有兩個處理器(你和戀人),兩者都在等待 🕙 並專注於等待櫃檯上的餐點 🕙,等待的時間非常長。 + +這家速食店有 8 個處理器(收銀員/廚師)。而並行漢堡店可能只有 2 個處理器(一位收銀員和一位廚師)。 + +儘管如此,最終的體驗並不是最理想的。😞 + +--- + +這是與漢堡類似的故事。🍔 + +一個更「現實」的例子,想像一間銀行。 + +直到最近,大多數銀行都有多位出納員 👨‍💼👨‍💼👨‍💼👨‍💼,以及一條長長的隊伍 🕙🕙🕙🕙🕙🕙🕙🕙。 + +所有的出納員都在一個接一個地滿足每位客戶的所有需求 👨‍💼⏯。 + +你必須長時間排隊 🕙,不然就會失去機會。 + +所以,你不會想帶你的戀人 😍 一起去銀行辦事 🏦。 + +### 漢堡結論 + +在「和戀人一起吃速食漢堡」的這個場景中,由於有大量的等待 🕙,使用並行系統 ⏸🔀⏯ 更有意義。 + +這也是大多數 Web 應用的情況。 + +許多用戶正在使用你的應用程式,而你的伺服器則在等待 🕙 這些用戶不那麼穩定的網路來傳送請求。 + +接著,再次等待 🕙 回應。 + +這種「等待」 🕙 通常以微秒來衡量,但累加起來,最終還是花費了很多等待時間。 + +這就是為什麼對於 Web API 來說,使用非同步程式碼 ⏸🔀⏯ 是非常有意義的。 + +這種類型的非同步性正是 NodeJS 成功的原因(儘管 NodeJS 不是平行的),這也是 Go 語言作為程式語言的一個強大優勢。 + +這與 **FastAPI** 所能提供的性能水平相同。 + +你可以同時利用並行性和平行性,進一步提升效能,這比大多數已測試的 NodeJS 框架都更快,並且與 Go 語言相當,而 Go 是一種更接近 C 的編譯語言(感謝 Starlette)。 + +### 並行比平行更好嗎? + +不是的!這不是故事的本意。 + +並行與平行不同。並行在某些 **特定** 的需要大量等待的情境下表現更好。正因如此,並行在 Web 應用程式開發中通常比平行更有優勢。但並不是所有情境都如此。 + +因此,為了平衡報導,想像下面這個短故事 + +> 你需要打掃一間又大又髒的房子。 + +*是的,這就是全部的故事。* + +--- + +這裡沒有任何需要等待 🕙 的地方,只需要在房子的多個地方進行大量的工作。 + +你可以像漢堡的例子那樣輪流進行,先打掃客廳,再打掃廚房,但由於你不需要等待 🕙 任何事情,只需要持續地打掃,輪流並不會影響任何結果。 + +無論輪流執行與否(並行),你都需要相同的工時完成任務,同時需要執行相同工作量。 + +但是,在這種情境下,如果你可以邀請8位前收銀員/廚師(現在是清潔工)來幫忙,每個人(加上你)負責房子的某個區域,這樣你就可以 **平行** 地更快完成工作。 + +在這個場景中,每個清潔工(包括你)都是一個處理器,完成工作的一部分。 + +由於大多數的執行時間都花在實際的工作上(而不是等待),而電腦中的工作由 CPU 完成,因此這些問題被稱為「CPU 密集型」。 + +--- + +常見的 CPU 密集型操作範例包括那些需要進行複雜數學計算的任務。 + +例如: + +* **音訊**或**圖像處理**; +* **電腦視覺**:一張圖片由數百萬個像素組成,每個像素有 3 個值/顏色,處理這些像素通常需要同時進行大量計算; +* **機器學習**: 通常需要大量的「矩陣」和「向量」運算。想像一個包含數字的巨大電子表格,並所有的數字同時相乘; +* **深度學習**: 這是機器學習的子領域,同樣適用。只不過這不僅僅是一張數字表格,而是大量的數據集合,並且在很多情況下,你會使用特殊的處理器來構建或使用這些模型。 + +### 並行 + 平行: Web + 機器學習 + +使用 **FastAPI**,你可以利用並行的優勢,這在 Web 開發中非常常見(這也是 NodeJS 的最大吸引力)。 + +但你也可以利用平行與多行程 (multiprocessing)(讓多個行程同時運行) 的優勢來處理機器學習系統中的 **CPU 密集型**工作。 + +這一點,再加上 Python 是 **資料科學**、機器學習,尤其是深度學習的主要語言,讓 **FastAPI** 成為資料科學/機器學習 Web API 和應用程式(以及許多其他應用程式)的絕佳選擇。 + +想了解如何在生產環境中實現這種平行性,請參見 [部屬](deployment/index.md){.internal-link target=_blank}。 + +## `async` 和 `await` + +現代 Python 版本提供一種非常直觀的方式定義非同步程式碼。這使得它看起來就像正常的「順序」程式碼,並在適當的時機「等待」。 + +當某個操作需要等待才能回傳結果,並且支援這些新的 Python 特性時,你可以像這樣編寫程式碼: + +```Python +burgers = await get_burgers(2) +``` + +這裡的關鍵是 `await`。它告訴 Python 必須等待 ⏸ `get_burgers(2)` 完成它的工作 🕙, 然後將結果儲存在 `burgers` 中。如此,Python 就可以在此期間去處理其他事情 🔀 ⏯ (例如接收另一個請求)。 + +要讓 `await` 運作,它必須位於支持非同步功能的函式內。為此,只需使用 `async def` 宣告函式: + +```Python hl_lines="1" +async def get_burgers(number: int): + # Do some asynchronous stuff to create the burgers + return burgers +``` + +...而不是 `def`: + +```Python hl_lines="2" +# This is not asynchronous +def get_sequential_burgers(number: int): + # Do some sequential stuff to create the burgers + return burgers +``` + +使用 `async def`,Python Python 知道在該函式內需要注意 `await`,並且它可以「暫停」 ⏸ 執行該函式,然後執行其他任務 🔀 後回來。 + +當你想要呼叫 `async def` 函式時,必須使用「await」。因此,這樣寫將無法運行: + +```Python +# This won't work, because get_burgers was defined with: async def +burgers = get_burgers(2) +``` + +--- + +如果你正在使用某個函式庫,它告訴你可以使用 `await` 呼叫它,那麼你需要用 `async def` 定義*路徑操作函式*,如: + +```Python hl_lines="2-3" +@app.get('/burgers') +async def read_burgers(): + burgers = await get_burgers(2) + return burgers +``` + +### 更多技術細節 + +你可能已經注意到,`await` 只能在 `async def` 定義的函式內使用。 + +但同時,使用 `async def` 定義的函式本身也必須被「等待」。所以,帶有 `async def` 函式只能在其他使用 `async def` 定義的函式內呼叫。 + +那麼,這就像「先有雞還是先有蛋」的問題,要如何呼叫第一個 `async` 函式呢? + +如果你使用 FastAPI,無需擔心這個問題,因為「第一個」函式將是你的*路徑操作函式*,FastAPI 會知道如何正確處理這個問題。 + +但如果你想在沒有 FastAPI 的情況下使用 `async` / `await`,你也可以這樣做。 + +### 編寫自己的非同步程式碼 + +Starlette (和 **FastAPI**) 是基於 AnyIO 實作的,這使得它們與 Python 標準函式庫相容 asyncioTrio。 + +特別是,你可以直接使用 AnyIO 來處理更複雜的並行使用案例,這些案例需要你在自己的程式碼中使用更高階的模式。 + +即使你不使用 **FastAPI**,你也可以使用 AnyIO 來撰寫自己的非同步應用程式,並獲得高相容性及一些好處(例如結構化並行)。 + +### 其他形式的非同步程式碼 + +使用 `async` 和 `await` 的風格在語言中相對較新。 + +但它使處理異步程式碼變得更加容易。 + +相同的語法(或幾乎相同的語法)最近也被包含在現代 JavaScript(無論是瀏覽器還是 NodeJS)中。 + +但在此之前,處理異步程式碼要更加複雜和困難。 + +在較舊的 Python 版本中,你可能會使用多執行緒或 Gevent。但這些程式碼要更難以理解、調試和思考。 + +在較舊的 NodeJS / 瀏覽器 JavaScript 中,你會使用「回呼」,這可能會導致回呼地獄。 + +## 協程 + +**協程** 只是 `async def` 函式所回傳的非常特殊的事物名稱。Python 知道它是一個類似函式的東西,可以啟動它,並且在某個時刻它會結束,但它也可能在內部暫停 ⏸,只要遇到 `await`。 + +這種使用 `async` 和 `await` 的非同步程式碼功能通常被概括為「協程」。這與 Go 語言的主要特性「Goroutines」相似。 + +## 結論 + +讓我們再次回顧之前的句子: + +> 現代版本的 Python 支持使用 **"協程"** 的 **`async` 和 `await`** 語法來寫 **"非同步程式碼"**。 + +現在應該能明白其含意了。✨ + +這些就是驅動 FastAPI(通過 Starlette)運作的原理,也讓它擁有如此驚人的效能。 + +## 非常技術性的細節 + +/// warning + +你大概可以跳過這段。 + +這裡是有關 FastAPI 內部技術細節。 + +如果你有相當多的技術背景(例如協程、執行緒、阻塞等),並且對 FastAPI 如何處理 `async def` 與常規 `def` 感到好奇,請繼續閱讀。 + +/// + +### 路徑操作函数 + +當你使用 `def` 而不是 `async def` 宣告*路徑操作函式*時,該函式會在外部的執行緒池(threadpool)中執行,然後等待結果,而不是直接呼叫(因為這樣會阻塞伺服器)。 + +如果你來自於其他不以這種方式運作的非同步框架,而且你習慣於使用普通的 `def` 定義僅進行簡單計算的*路徑操作函式*,目的是獲得微小的性能增益(大約 100 奈秒),請注意,在 FastAPI 中,效果會完全相反。在這些情況下,最好使用 `async def`除非你的*路徑操作函式*執行阻塞的 I/O 的程式碼。 + +不過,在這兩種情況下,**FastAPI** [仍然很快](index.md#_11){.internal-link target=_blank}至少與你之前的框架相當(或者更快)。 + +### 依賴項(Dependencies) + +同樣適用於[依賴項](tutorial/dependencies/index.md){.internal-link target=_blank}。如果依賴項是一個標準的 `def` 函式,而不是 `async def`,那麼它在外部的執行緒池被運行。 + +### 子依賴項 + +你可以擁有多個相互依賴的依賴項和[子依賴項](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} (作為函式定義的參數),其中一些可能是用 `async def` 宣告,也可能是用 `def` 宣告。它們仍然可以正常運作,用 `def` 定義的那些將會在外部的執行緒中呼叫(來自執行緒池),而不是被「等待」。 + +### 其他輔助函式 + +你可以直接呼叫任何使用 `def` 或 `async def` 建立的其他輔助函式,FastAPI 不會影響你呼叫它們的方式。 + +這與 FastAPI 為你呼叫*路徑操作函式*和依賴項的邏輯有所不同。 + +如果你的輔助函式是用 `def` 宣告的,它將會被直接呼叫(按照你在程式碼中撰寫的方式),而不是在執行緒池中。如果該函式是用 `async def` 宣告,那麼你在呼叫時應該使用 `await` 等待其結果。 + +--- + +再一次強調,這些都是非常技術性的細節,如果你特地在尋找這些資訊,這些內容可能會對你有幫助。 + +否則,只需遵循上面提到的指引即可:趕時間嗎?. From 8255edfecfe539f09c2655016ea3ef3e4fb50881 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 27 Nov 2024 23:10:31 +0000 Subject: [PATCH 485/932] =?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 [skip ci] --- 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 f9661c394..65d19ed21 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Translations +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/async.md`. PR [#12990](https://github.com/fastapi/fastapi/pull/12990) by [@ILoveSorasakiHina](https://github.com/ILoveSorasakiHina). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/tutorial/query-param-models.md`. PR [#12932](https://github.com/fastapi/fastapi/pull/12932) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Add Korean translation for `docs/ko/docs/advanced/testing-dependencies.md`. PR [#12992](https://github.com/fastapi/fastapi/pull/12992) by [@Limsunoh](https://github.com/Limsunoh). * 🌐 Add Korean translation for `docs/ko/docs/advanced/websockets.md`. PR [#12991](https://github.com/fastapi/fastapi/pull/12991) by [@kwang1215](https://github.com/kwang1215). From 4f8157588e47f909276e0474f6926740a2e55b9c Mon Sep 17 00:00:00 2001 From: Abdullah Hashim Date: Wed, 4 Dec 2024 01:37:12 +0300 Subject: [PATCH 486/932] =?UTF-8?q?=F0=9F=90=9B=20Preserve=20traceback=20w?= =?UTF-8?q?hen=20exception=20is=20raised=20in=20sync=20dependency=20with?= =?UTF-8?q?=20`yield`=20(#5823)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Marcelo Trylesinski --- fastapi/concurrency.py | 4 ++-- tests/test_exception_handlers.py | 23 ++++++++++++++++++++++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/fastapi/concurrency.py b/fastapi/concurrency.py index 894bd3ed1..3202c7078 100644 --- a/fastapi/concurrency.py +++ b/fastapi/concurrency.py @@ -1,7 +1,7 @@ from contextlib import asynccontextmanager as asynccontextmanager from typing import AsyncGenerator, ContextManager, TypeVar -import anyio +import anyio.to_thread from anyio import CapacityLimiter from starlette.concurrency import iterate_in_threadpool as iterate_in_threadpool # noqa from starlette.concurrency import run_in_threadpool as run_in_threadpool # noqa @@ -28,7 +28,7 @@ async def contextmanager_in_threadpool( except Exception as e: ok = bool( await anyio.to_thread.run_sync( - cm.__exit__, type(e), e, None, limiter=exit_limiter + cm.__exit__, type(e), e, e.__traceback__, limiter=exit_limiter ) ) if not ok: diff --git a/tests/test_exception_handlers.py b/tests/test_exception_handlers.py index 67a4becec..6a3cbd830 100644 --- a/tests/test_exception_handlers.py +++ b/tests/test_exception_handlers.py @@ -1,5 +1,5 @@ import pytest -from fastapi import FastAPI, HTTPException +from fastapi import Depends, FastAPI, HTTPException from fastapi.exceptions import RequestValidationError from fastapi.testclient import TestClient from starlette.responses import JSONResponse @@ -28,6 +28,18 @@ app = FastAPI( client = TestClient(app) +def raise_value_error(): + raise ValueError() + + +def dependency_with_yield(): + yield raise_value_error() + + +@app.get("/dependency-with-yield", dependencies=[Depends(dependency_with_yield)]) +def with_yield(): ... + + @app.get("/http-exception") def route_with_http_exception(): raise HTTPException(status_code=400) @@ -65,3 +77,12 @@ def test_override_server_error_exception_response(): response = client.get("/server-error") assert response.status_code == 500 assert response.json() == {"exception": "server-error"} + + +def test_traceback_for_dependency_with_yield(): + client = TestClient(app, raise_server_exceptions=True) + with pytest.raises(ValueError) as exc_info: + client.get("/dependency-with-yield") + last_frame = exc_info.traceback[-1] + assert str(last_frame.path) == __file__ + assert last_frame.lineno == raise_value_error.__code__.co_firstlineno From 905ec1eddefe311365ef02b3dcd8a8a0d4b7a75a Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 3 Dec 2024 22:37:38 +0000 Subject: [PATCH 487/932] =?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 [skip ci] --- 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 65d19ed21..6cd6810ac 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Fixes + +* 🐛 Preserve traceback when exception is raised in sync dependency with `yield`. PR [#5823](https://github.com/fastapi/fastapi/pull/5823) by [@sombek](https://github.com/sombek). + ### Refactors * ♻️ Update tests and internals for compatibility with Pydantic >=2.10. PR [#12971](https://github.com/fastapi/fastapi/pull/12971) by [@tamird](https://github.com/tamird). From bb8c2a64981d3e806575a445115f29eddf014c77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 3 Dec 2024 23:40:01 +0100 Subject: [PATCH 488/932] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?5.6?= 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 6cd6810ac..a786985d2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.115.6 + ### Fixes * 🐛 Preserve traceback when exception is raised in sync dependency with `yield`. PR [#5823](https://github.com/fastapi/fastapi/pull/5823) by [@sombek](https://github.com/sombek). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 12faea987..823957822 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.5" +__version__ = "0.115.6" from starlette import status as status From 293d7c3bf887280a9111bac712c4a5360a8948ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 3 Dec 2024 23:45:53 +0100 Subject: [PATCH 489/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a786985d2..cf754efa3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,7 +11,7 @@ hide: ### Fixes -* 🐛 Preserve traceback when exception is raised in sync dependency with `yield`. PR [#5823](https://github.com/fastapi/fastapi/pull/5823) by [@sombek](https://github.com/sombek). +* 🐛 Preserve traceback when an exception is raised in sync dependency with `yield`. PR [#5823](https://github.com/fastapi/fastapi/pull/5823) by [@sombek](https://github.com/sombek). ### Refactors From 4881d1e225445faa196f2de58c4ce02dd32f5837 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 4 Dec 2024 15:38:39 +0100 Subject: [PATCH 490/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20docs=20for=20`f?= =?UTF-8?q?astapi-cli`=20(#13031)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/en/docs/fastapi-cli.md | 74 +++++++++++++++++-------------------- tests/test_fastapi_cli.py | 2 +- 2 files changed, 34 insertions(+), 42 deletions(-) diff --git a/docs/en/docs/fastapi-cli.md b/docs/en/docs/fastapi-cli.md index e27bebcb4..654d2fe91 100644 --- a/docs/en/docs/fastapi-cli.md +++ b/docs/en/docs/fastapi-cli.md @@ -9,47 +9,39 @@ To run your FastAPI app for development, you can use the `fastapi dev` command:
```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 dev main.py + + FastAPI Starting development server 🚀 + + Searching for package file structure from directories with + __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with the + following code: + + from main import app + + app Using import string: main:app + + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: + + 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 [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. ```
diff --git a/tests/test_fastapi_cli.py b/tests/test_fastapi_cli.py index 20c928157..a5c10778a 100644 --- a/tests/test_fastapi_cli.py +++ b/tests/test_fastapi_cli.py @@ -22,7 +22,7 @@ def test_fastapi_cli(): encoding="utf-8", ) assert result.returncode == 1, result.stdout - assert "Using path non_existent_file.py" in result.stdout + assert "Path does not exist non_existent_file.py" in result.stdout def test_fastapi_cli_not_installed(): From 551c5613a9d70c9ec69e7119ee39a35d3dac0326 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 4 Dec 2024 14:39:05 +0000 Subject: [PATCH 491/932] =?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 [skip ci] --- 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 cf754efa3..d7ab35807 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Update docs for `fastapi-cli`. PR [#13031](https://github.com/fastapi/fastapi/pull/13031) by [@tiangolo](https://github.com/tiangolo). + ## 0.115.6 ### Fixes From 0b7b222e4985444a47f21d15ddbda43408c74534 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 4 Dec 2024 16:00:08 +0100 Subject: [PATCH 492/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20sponsors:=20rem?= =?UTF-8?q?ove=20Codacy=20(#13032)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 - docs/en/data/sponsors.yml | 3 --- 2 files changed, 4 deletions(-) diff --git a/README.md b/README.md index 62eeda03b..7973f341b 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,6 @@ The key features are: - diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 1c83579e2..e66d592f5 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -45,9 +45,6 @@ silver: - url: https://www.svix.com/ title: Svix - Webhooks as a service img: https://fastapi.tiangolo.com/img/sponsors/svix.svg - - url: https://www.codacy.com/?utm_source=github&utm_medium=sponsors&utm_id=pioneers - title: Take code reviews from hours to minutes - img: https://fastapi.tiangolo.com/img/sponsors/codacy.png - url: https://www.stainlessapi.com/?utm_source=fastapi&utm_medium=referral title: Stainless | Generate best-in-class SDKs img: https://fastapi.tiangolo.com/img/sponsors/stainless.png From d4e29ea3fef8008508169c6807440788ed7ae5f4 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 4 Dec 2024 15:00:32 +0000 Subject: [PATCH 493/932] =?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 [skip ci] --- 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 d7ab35807..378f157f6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,10 @@ hide: * 📝 Update docs for `fastapi-cli`. PR [#13031](https://github.com/fastapi/fastapi/pull/13031) by [@tiangolo](https://github.com/tiangolo). +### Internal + +* 📝 Update sponsors: remove Codacy. PR [#13032](https://github.com/fastapi/fastapi/pull/13032) by [@tiangolo](https://github.com/tiangolo). + ## 0.115.6 ### Fixes From cc4db3294aeec3256d9e7319b0aa534a34ed3db8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 4 Dec 2024 16:10:05 +0100 Subject: [PATCH 494/932] =?UTF-8?q?=F0=9F=94=A7=20Update=20team=20members?= =?UTF-8?q?=20(#13033)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/members.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/docs/en/data/members.yml b/docs/en/data/members.yml index a3a6b912d..cf016eae1 100644 --- a/docs/en/data/members.yml +++ b/docs/en/data/members.yml @@ -14,9 +14,6 @@ members: - login: YuriiMotov avatar_url: https://avatars.githubusercontent.com/u/109919500 url: https://github.com/YuriiMotov -- login: estebanx64 - avatar_url: https://avatars.githubusercontent.com/u/10840422 - url: https://github.com/estebanx64 - login: patrick91 avatar_url: https://avatars.githubusercontent.com/u/667029 url: https://github.com/patrick91 From f9514ac4b263be971c50f7e0f719b7a6d361e192 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 4 Dec 2024 15:10:29 +0000 Subject: [PATCH 495/932] =?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 [skip ci] --- 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 378f157f6..d57b411e5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Internal +* 🔧 Update team members. PR [#13033](https://github.com/fastapi/fastapi/pull/13033) by [@tiangolo](https://github.com/tiangolo). * 📝 Update sponsors: remove Codacy. PR [#13032](https://github.com/fastapi/fastapi/pull/13032) by [@tiangolo](https://github.com/tiangolo). ## 0.115.6 From 01c6b41c52432c894368bef4bde8eb63be0279ff Mon Sep 17 00:00:00 2001 From: YungYueh ChanLee Date: Mon, 9 Dec 2024 20:20:58 +0800 Subject: [PATCH 496/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Traditional=20Chin?= =?UTF-8?q?ese=20translation=20for=20`docs/zh-hant/docs/tutorial/first-ste?= =?UTF-8?q?ps.md`=20(#12467)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/tutorial/first-steps.md | 331 ++++++++++++++++++++++ 1 file changed, 331 insertions(+) create mode 100644 docs/zh-hant/docs/tutorial/first-steps.md diff --git a/docs/zh-hant/docs/tutorial/first-steps.md b/docs/zh-hant/docs/tutorial/first-steps.md new file mode 100644 index 000000000..a557fa369 --- /dev/null +++ b/docs/zh-hant/docs/tutorial/first-steps.md @@ -0,0 +1,331 @@ +# 第一步 + +最簡單的 FastAPI 檔案可能看起來像這樣: + +{* ../../docs_src/first_steps/tutorial001.py *} + +將其複製到一個名為 `main.py` 的文件中。 + +執行即時重新載入伺服器(live server): + +
+ +```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. +``` + +
+ +在輸出中,有一列類似於: + +```hl_lines="4" +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +那列顯示了你的應用程式正在本地端機器上運行的 URL。 + +### 查看它 + +在瀏覽器中打開 http://127.0.0.1:8000. + +你將看到如下的 JSON 回應: + +```JSON +{"message": "Hello World"} +``` + +### 互動式 API 文件 + +現在,前往 http://127.0.0.1:8000/docs. + +你將看到自動的互動式 API 文件(由 Swagger UI 提供): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### 替代 API 文件 + +現在,前往 http://127.0.0.1:8000/redoc. + +你將看到另一種自動文件(由 ReDoc 提供): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +### OpenAPI + +**FastAPI** 使用定義 API 的 **OpenAPI** 標準來生成一個 「schema」 與你的所有 API。 + +#### 「Schema」 + +「schema」是對某個事物的定義或描述。它並不是實作它的程式碼,而僅僅是一個抽象的描述。 + +#### API 「schema」 + +在這種情況下,OpenAPI 是一個規範,它規定了如何定義 API 的 schema。 + +這個 schema 定義包含了你的 API 路徑、可能接收的參數等內容。 + +#### 資料 「schema」 + +「schema」這個術語也可能指某些資料的結構,比如 JSON 內容的結構。 + +在這種情況下,它指的是 JSON 的屬性、資料型別等。 + +#### OpenAPI 和 JSON Schema + +OpenAPI 定義了 API 的 schema。這個 schema 包含了使用 **JSON Schema** 定義的資料,這是 JSON 資料 schema 的標準。 + +#### 檢查 `openapi.json` + +如果你好奇原始的 OpenAPI schema 長什麼樣子,FastAPI 會自動生成一個包含所有 API 描述的 JSON (schema)。 + +你可以直接在 http://127.0.0.1:8000/openapi.json 查看它。 + +它會顯示一個 JSON,類似於: + +```JSON +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + + + +... +``` + +#### OpenAPI 的用途 + +OpenAPI schema 驅動了兩個互動式文件系統。 + +而且有許多替代方案,所有這些都是基於 OpenAPI。你可以輕鬆地將任何這些替代方案添加到使用 **FastAPI** 建置的應用程式中。 + +你也可以用它自動生成程式碼,讓前端、手機應用程式或物聯網設備等與你的 API 進行通訊。 + +## 逐步回顧 + +### 第一步:引入 `FastAPI` + +{* ../../docs_src/first_steps/tutorial001.py h1[1] *} + +`FastAPI` 是一個 Python 類別,提供所有 API 的全部功能。 + +/// note | Technical Details + +`FastAPI` 是一個直接繼承自 `Starlette` 的類別。 + +你同樣可以透過 `FastAPI` 來使用 Starlette 所有的功能。 + +/// + +### 第二步:建立一個 `FastAPI` 「實例」 + +{* ../../docs_src/first_steps/tutorial001.py h1[3] *} + +這裡的 `app` 變數將會是 `FastAPI` 類別的「實例」。 + +這將是你建立所有 API 的主要互動點。 + +### 第三步:建立一個 *路徑操作* + +#### 路徑 + +這裡的「路徑」指的是 URL 中自第一個 `/` 以後的部分。 + +例如,在 URL 中: + +``` +https://example.com/items/foo +``` + +……的路徑將會是: + +``` +/items/foo +``` + +/// info + +「路徑」也常被稱為「端點 endpoint」或「路由 route」。 + +/// + +在建置 API 時,「路徑」是分離「關注點」和「資源」的主要方式。 + +#### 操作 + +這裡的「操作」指的是 HTTP 的「方法」之一。 + +其中包括: + +* `POST` +* `GET` +* `PUT` +* `DELETE` + +……以及更少見的: + +* `OPTIONS` +* `HEAD` +* `PATCH` +* `TRACE` + +在 HTTP 協定中,你可以使用這些「方法」之一(或更多)與每個路徑進行通信。 + +--- + +在建置 API 時,你通常使用這些特定的 HTTP 方法來執行特定的動作。 + +通常你使用: + +* `POST`:用來建立資料。 +* `GET`:用來讀取資料。 +* `PUT`:用來更新資料。 +* `DELETE`:用來刪除資料。 + +所以,在 OpenAPI 中,每個 HTTP 方法都被稱為「操作」。 + +我們將會稱它們為「**操作**」。 + +#### 定義一個 *路徑操作裝飾器* + +{* ../../docs_src/first_steps/tutorial001.py h1[6] *} + +`@app.get("/")` 告訴 **FastAPI** 那個函式負責處理請求: + +* 路徑 `/` +* 使用 get操作 + +/// info | `@decorator` Info + +Python 中的 `@something` 語法被稱為「裝飾器」。 + +你把它放在一個函式上面。像一個漂亮的裝飾帽子(我猜這是術語的來源)。 + +一個「裝飾器」會對下面的函式做一些事情。 + +在這種情況下,這個裝飾器告訴 **FastAPI** 那個函式對應於 **路徑** `/` 和 **操作** `get`. + +這就是「**路徑操作裝飾器**」。 + +/// + +你也可以使用其他的操作: + +* `@app.post()` +* `@app.put()` +* `@app.delete()` + +以及更少見的: + +* `@app.options()` +* `@app.head()` +* `@app.patch()` +* `@app.trace()` + +/// tip + +你可以自由地使用每個操作(HTTP 方法)。 + +**FastAPI** 不強制任何特定的意義。 + +這裡的資訊作為一個指南,而不是要求。 + +例如,當使用 GraphQL 時,你通常只使用 `POST` 操作。 + +/// + +### 第四步:定義 **路徑操作函式** + +這是我們的「**路徑操作函式**」: + +* **path**: 是 `/`. +* **operation**: 是 `get`. +* **function**: 是裝飾器下面的函式(在 `@app.get("/")` 下面)。 + +{* ../../docs_src/first_steps/tutorial001.py h1[7] *} + +這就是一個 Python 函式。 + +它將會在 **FastAPI** 收到一個請求時被呼叫,使用 `GET` 操作。 + +在這種情況下,它是一個 `async` 函式。 + +--- + +你可以將它定義為一個正常的函式,而不是 `async def`: + +{* ../../docs_src/first_steps/tutorial003.py h1[7] *} + +/// note + +如果你不知道差別,請查看 [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +/// + +### 第五步:回傳內容 + +{* ../../docs_src/first_steps/tutorial001.py h1[8] *} + +你可以返回一個 `dict`、`list`、單個值作為 `str`、`int` 等。 + +你也可以返回 Pydantic 模型(稍後你會看到更多關於這方面的內容)。 + +有很多其他物件和模型會自動轉換為 JSON(包括 ORMs,等等)。試用你最喜歡的,很有可能它們已經有支援。 + +## 回顧 + +* 引入 `FastAPI`. +* 建立一個 `app` 實例。 +* 寫一個 **路徑操作裝飾器** 使用裝飾器像 `@app.get("/")`。 +* 定義一個 **路徑操作函式**;例如,`def root(): ...`。 +* 使用命令 `fastapi dev` 執行開發伺服器。 From 131b6dc21f71a91cdf9e4313f1ecea13bc3118a1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 12:21:23 +0000 Subject: [PATCH 497/932] =?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 [skip ci] --- 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 d57b411e5..462440826 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,10 @@ hide: * 📝 Update docs for `fastapi-cli`. PR [#13031](https://github.com/fastapi/fastapi/pull/13031) by [@tiangolo](https://github.com/tiangolo). +### Translations + +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/tutorial/first-steps.md`. PR [#12467](https://github.com/fastapi/fastapi/pull/12467) by [@codingjenny](https://github.com/codingjenny). + ### Internal * 🔧 Update team members. PR [#13033](https://github.com/fastapi/fastapi/pull/13033) by [@tiangolo](https://github.com/tiangolo). From 80409272089f7671d497368d5170cdaeb203ef83 Mon Sep 17 00:00:00 2001 From: nahyunkeem Date: Mon, 9 Dec 2024 21:22:47 +0900 Subject: [PATCH 498/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20to=20`docs/ko/docs/advanced/additional-status-codes.md`=20?= =?UTF-8?q?(#12715)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/advanced/additional-status-codes.md | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 docs/ko/docs/advanced/additional-status-codes.md diff --git a/docs/ko/docs/advanced/additional-status-codes.md b/docs/ko/docs/advanced/additional-status-codes.md new file mode 100644 index 000000000..da06cb778 --- /dev/null +++ b/docs/ko/docs/advanced/additional-status-codes.md @@ -0,0 +1,41 @@ +# 추가 상태 코드 + +기본적으로 **FastAPI**는 응답을 `JSONResponse`를 사용하여 반환하며, *경로 작업(path operation)*에서 반환한 내용을 해당 `JSONResponse` 안에 넣어 반환합니다. + +기본 상태 코드 또는 *경로 작업*에서 설정한 상태 코드를 사용합니다. + +## 추가 상태 코드 + +기본 상태 코드와 별도로 추가 상태 코드를 반환하려면 `JSONResponse`와 같이 `Response`를 직접 반환하고 추가 상태 코드를 직접 설정할 수 있습니다. + +예를 들어 항목을 업데이트할 수 있는 *경로 작업*이 있고 성공 시 200 “OK”의 HTTP 상태 코드를 반환한다고 가정해 보겠습니다. + +하지만 새로운 항목을 허용하기를 원할 것입니다. 항목이 이전에 존재하지 않았다면 이를 생성하고 HTTP 상태 코드 201 "Created"를 반환합니다. + +이를 위해서는 `JSONResponse`를 가져와서 원하는 `status_code`를 설정하여 콘텐츠를 직접 반환합니다: + +{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *} + +/// warning | 경고 + +위의 예제처럼 `Response`를 직접 반환하면 바로 반환됩니다. + +모델 등과 함께 직렬화되지 않습니다. + +원하는 데이터가 있는지, 값이 유효한 JSON인지 확인합니다(`JSONResponse`를 사용하는 경우). + +/// + +/// note | 기술적 세부 정보 + +`from starlette.responses import JSONResponse`를 사용할 수도 있습니다. + +**FastAPI**는 개발자 여러분을 위한 편의성으로 `fastapi.responses`와 동일한 `starlette.responses`를 제공합니다. 그러나 사용 가능한 응답의 대부분은 Starlette에서 직접 제공됩니다. `status` 또한 마찬가지입니다. + +/// + +## OpenAPI 및 API 문서 + +추가 상태 코드와 응답을 직접 반환하는 경우, FastAPI는 반환할 내용을 미리 알 수 있는 방법이 없기 때문에 OpenAPI 스키마(API 문서)에 포함되지 않습니다. + +하지만 다음을 사용하여 코드에 이를 문서화할 수 있습니다: [추가 응답](additional-responses.md){.internal-link target=_blank}. From d43fe2d2e11feb564d6e007fe722851872a4cb3d Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 12:23:36 +0000 Subject: [PATCH 499/932] =?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 [skip ci] --- 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 462440826..09f630cf6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Korean translation to `docs/ko/docs/advanced/additional-status-codes.md`. PR [#12715](https://github.com/fastapi/fastapi/pull/12715) by [@nahyunkeem](https://github.com/nahyunkeem). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/tutorial/first-steps.md`. PR [#12467](https://github.com/fastapi/fastapi/pull/12467) by [@codingjenny](https://github.com/codingjenny). ### Internal From 49efaa5b7eba94313ddc67b0d0c0aea787622647 Mon Sep 17 00:00:00 2001 From: nahyunkeem Date: Mon, 9 Dec 2024 21:25:19 +0900 Subject: [PATCH 500/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/how-to/configure-swagger-ui.md`=20(#12?= =?UTF-8?q?898)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/how-to/configure-swagger-ui.md | 70 +++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 docs/ko/docs/how-to/configure-swagger-ui.md diff --git a/docs/ko/docs/how-to/configure-swagger-ui.md b/docs/ko/docs/how-to/configure-swagger-ui.md new file mode 100644 index 000000000..5a57342cf --- /dev/null +++ b/docs/ko/docs/how-to/configure-swagger-ui.md @@ -0,0 +1,70 @@ +# Swagger UI 구성 + +추가적인 Swagger UI 매개변수를 구성할 수 있습니다. + +구성을 하려면, `FastAPI()` 앱 객체를 생성할 때 또는 `get_swagger_ui_html()` 함수에 `swagger_ui_parameters` 인수를 전달하십시오. + +`swagger_ui_parameters`는 Swagger UI에 직접 전달된 구성을 포함하는 딕셔너리를 받습니다. + +FastAPI는 이 구성을 **JSON** 형식으로 변환하여 JavaScript와 호환되도록 합니다. 이는 Swagger UI에서 필요로 하는 형식입니다. + +## 구문 강조 비활성화 + +예를 들어, Swagger UI에서 구문 강조 기능을 비활성화할 수 있습니다. + +설정을 변경하지 않으면, 기본적으로 구문 강조 기능이 활성화되어 있습니다: + + + +그러나 `syntaxHighlight`를 `False`로 설정하여 구문 강조 기능을 비활성화할 수 있습니다: + +{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *} + +...그럼 Swagger UI에서 더 이상 구문 강조 기능이 표시되지 않습니다: + + + +## 테마 변경 + +동일한 방식으로 `"syntaxHighlight.theme"` 키를 사용하여 구문 강조 테마를 설정할 수 있습니다 (중간에 점이 포함된 것을 참고하십시오). + +{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *} + +이 설정은 구문 강조 색상 테마를 변경합니다: + + + +## 기본 Swagger UI 매개변수 변경 + +FastAPI는 대부분의 사용 사례에 적합한 몇 가지 기본 구성 매개변수를 포함하고 있습니다. + +기본 구성에는 다음이 포함됩니다: + +{* ../../fastapi/openapi/docs.py ln[8:23] hl[17:23] *} + +`swagger_ui_parameters` 인수에 다른 값을 설정하여 이러한 기본값 중 일부를 재정의할 수 있습니다. + +예를 들어, `deepLinking`을 비활성화하려면 `swagger_ui_parameters`에 다음 설정을 전달할 수 있습니다: + +{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *} + +## 기타 Swagger UI 매개변수 + +사용할 수 있는 다른 모든 구성 옵션을 확인하려면, Swagger UI 매개변수에 대한 공식 문서를 참조하십시오. + +## JavaScript 전용 설정 + +Swagger UI는 **JavaScript 전용** 객체(예: JavaScript 함수)로 다른 구성을 허용하기도 합니다. + +FastAPI는 이러한 JavaScript 전용 `presets` 설정을 포함하고 있습니다: + +```JavaScript +presets: [ + SwaggerUIBundle.presets.apis, + SwaggerUIBundle.SwaggerUIStandalonePreset +] +``` + +이들은 문자열이 아닌 **JavaScript** 객체이므로 Python 코드에서 직접 전달할 수 없습니다. + +이와 같은 JavaScript 전용 구성을 사용해야 하는 경우, 위의 방법 중 하나를 사용하여 모든 Swagger UI 경로 작업을 재정의하고 필요한 JavaScript를 수동으로 작성할 수 있습니다. From cb33e0aed22f9e64d6bcc312b99ef79cee44a5e4 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 12:28:42 +0000 Subject: [PATCH 501/932] =?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 [skip ci] --- 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 09f630cf6..f65332297 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/how-to/configure-swagger-ui.md`. PR [#12898](https://github.com/fastapi/fastapi/pull/12898) by [@nahyunkeem](https://github.com/nahyunkeem). * 🌐 Add Korean translation to `docs/ko/docs/advanced/additional-status-codes.md`. PR [#12715](https://github.com/fastapi/fastapi/pull/12715) by [@nahyunkeem](https://github.com/nahyunkeem). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/tutorial/first-steps.md`. PR [#12467](https://github.com/fastapi/fastapi/pull/12467) by [@codingjenny](https://github.com/codingjenny). From 30f00ace9a868f4c0deb2ed36284fe1ff3a8ed9c Mon Sep 17 00:00:00 2001 From: "hy.lee" Date: Mon, 9 Dec 2024 21:41:56 +0900 Subject: [PATCH 502/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/resources/index.md`=20(#13004)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/resources/index.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 docs/ko/docs/resources/index.md diff --git a/docs/ko/docs/resources/index.md b/docs/ko/docs/resources/index.md new file mode 100644 index 000000000..e804dd4d5 --- /dev/null +++ b/docs/ko/docs/resources/index.md @@ -0,0 +1,3 @@ +# 리소스 + +추가 리소스, 외부 링크, 기사 등. ✈️ From 92236cf6a462842fcc01fea8d597fb7c4d4a54fe Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 12:42:19 +0000 Subject: [PATCH 503/932] =?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 [skip ci] --- 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 f65332297..e2571ac20 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/resources/index.md`. PR [#13004](https://github.com/fastapi/fastapi/pull/13004) by [@hard-coders](https://github.com/hard-coders). * 🌐 Add Korean translation for `docs/ko/docs/how-to/configure-swagger-ui.md`. PR [#12898](https://github.com/fastapi/fastapi/pull/12898) by [@nahyunkeem](https://github.com/nahyunkeem). * 🌐 Add Korean translation to `docs/ko/docs/advanced/additional-status-codes.md`. PR [#12715](https://github.com/fastapi/fastapi/pull/12715) by [@nahyunkeem](https://github.com/nahyunkeem). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/tutorial/first-steps.md`. PR [#12467](https://github.com/fastapi/fastapi/pull/12467) by [@codingjenny](https://github.com/codingjenny). From 5480386e396d58abd5cb82fbaddd15096c8f6555 Mon Sep 17 00:00:00 2001 From: "hy.lee" Date: Mon, 9 Dec 2024 21:42:55 +0900 Subject: [PATCH 504/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/tutorial/request-forms.md`=20(#13003)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/tutorial/request-forms.md | 74 ++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 docs/ko/docs/tutorial/request-forms.md diff --git a/docs/ko/docs/tutorial/request-forms.md b/docs/ko/docs/tutorial/request-forms.md new file mode 100644 index 000000000..5ca17b0d6 --- /dev/null +++ b/docs/ko/docs/tutorial/request-forms.md @@ -0,0 +1,74 @@ +# 폼 데이터 + +JSON 대신 폼 필드를 받아야 하는 경우 `Form`을 사용할 수 있습니다. + +/// info | 정보 + +폼을 사용하려면, 먼저 `python-multipart`를 설치하세요. + +[가상 환경](../virtual-environments.md){.internal-link target=_blank}을 생성하고 활성화한 다음, 아래와 같이 설치할 수 있습니다: + +```console +$ pip install python-multipart +``` + +/// + +## `Form` 임포트하기 + +`fastapi`에서 `Form`을 임포트합니다: + +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} + +## `Form` 매개변수 정의하기 + +`Body` 또는 `Query`와 동일한 방식으로 폼 매개변수를 만듭니다: + +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} + +예를 들어, OAuth2 사양을 사용할 수 있는 방법 중 하나("패스워드 플로우"라고 함)로 `username`과 `password`를 폼 필드로 보내야 합니다. + +사양에서는 필드 이름이 `username` 및 `password`로 정확하게 명명되어야 하고, JSON이 아닌 폼 필드로 전송해야 합니다. + +`Form`을 사용하면 유효성 검사, 예제, 별칭(예: `username` 대신 `user-name`) 등을 포함하여 `Body`(및 `Query`, `Path`, `Cookie`)와 동일한 구성을 선언할 수 있습니다. + +/// info | 정보 + +`Form`은 `Body`에서 직접 상속되는 클래스입니다. + +/// + +/// tip | 팁 + +폼 본문을 선언할 때, 폼이 없으면 매개변수가 쿼리 매개변수나 본문(JSON) 매개변수로 해석(interpret)되기 때문에 `Form`을 명시적으로 사용해야 합니다. + +/// + +## "폼 필드"에 대해 + +HTML 폼(`
`)이 데이터를 서버로 보내는 방식은 일반적으로 해당 데이터에 대해 "특수" 인코딩을 사용하며, 이는 JSON과 다릅니다. + +**FastAPI**는 JSON 대신 올바른 위치에서 해당 데이터를 읽습니다. + +/// note | 기술 세부사항 + +폼의 데이터는 일반적으로 "미디어 유형(media type)" `application/x-www-form-urlencoded`를 사용하여 인코딩합니다. + +그러나 폼에 파일이 포함된 경우, `multipart/form-data`로 인코딩합니다. 다음 장에서 파일 처리에 대해 읽을 겁니다. + + +이러한 인코딩 및 폼 필드에 대해 더 읽고 싶다면, POST에 대한 MDN 웹 문서를 참조하세요. + +/// + +/// warning | 경고 + +*경로 작업*에서 여러 `Form` 매개변수를 선언할 수 있지만, JSON으로 수신할 것으로 예상되는 `Body` 필드와 함께 선언할 수 없습니다. 요청 본문은 `application/json` 대신에 `application/x-www-form-urlencoded`를 사용하여 인코딩되기 때문입니다. + +이는 **FastAPI**의 제한 사항이 아니며 HTTP 프로토콜의 일부입니다. + +/// + +## 요약 + +폼 데이터 입력 매개변수를 선언하려면 `Form`을 사용하세요. From 5e8fa0e84207c936b1a3a375c7eb859451ba546b Mon Sep 17 00:00:00 2001 From: "hy.lee" Date: Mon, 9 Dec 2024 21:44:27 +0900 Subject: [PATCH 505/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/tutorial/request-form-models.md`=20(#1?= =?UTF-8?q?3002)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/tutorial/request-form-models.md | 78 ++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 docs/ko/docs/tutorial/request-form-models.md diff --git a/docs/ko/docs/tutorial/request-form-models.md b/docs/ko/docs/tutorial/request-form-models.md new file mode 100644 index 000000000..3316a93d5 --- /dev/null +++ b/docs/ko/docs/tutorial/request-form-models.md @@ -0,0 +1,78 @@ +# 폼 모델 + +FastAPI에서 **Pydantic 모델**을 이용하여 **폼 필드**를 선언할 수 있습니다. + +/// info | 정보 + +폼(Form)을 사용하려면, 먼저 `python-multipart`를 설치하세요. + +[가상 환경](../virtual-environments.md){.internal-link target=_blank}을 생성하고 활성화한 다음, 아래와 같이 설치할 수 있습니다: + +```console +$ pip install python-multipart +``` + +/// + +/// note | 참고 + +이 기능은 FastAPI 버전 `0.113.0` 이후부터 지원됩니다. 🤓 + +/// + +## Pydantic 모델을 사용한 폼 + +**폼 필드**로 받고 싶은 필드를 **Pydantic 모델**로 선언한 다음, 매개변수를 `Form`으로 선언하면 됩니다: + +{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *} + +**FastAPI**는 요청에서 받은 **폼 데이터**에서 **각 필드**에 대한 데이터를 **추출**하고 정의한 Pydantic 모델을 줍니다. + +## 문서 확인하기 + +문서 UI `/docs`에서 확인할 수 있습니다: + +
+ +
+ +## 추가 폼 필드 금지하기 + +일부 특별한 사용 사례(흔하지는 않겠지만)에서는 Pydantic 모델에서 정의한 폼 필드를 **제한**하길 원할 수도 있습니다. 그리고 **추가** 필드를 **금지**할 수도 있습니다. + +/// note | 참고 + +이 기능은 FastAPI 버전 `0.114.0` 이후부터 지원됩니다. 🤓 + +/// + +Pydantic의 모델 구성을 사용하여 추가(`extra`) 필드를 금지(`forbid`)할 수 있습니다: + +{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *} + +클라이언트가 추가 데이터를 보내려고 하면 **오류** 응답을 받게 됩니다. + +예를 들어, 클라이언트가 폼 필드를 보내려고 하면: + +* `username`: `Rick` +* `password`: `Portal Gun` +* `extra`: `Mr. Poopybutthole` + +`extra` 필드가 허용되지 않는다는 오류 응답을 받게 됩니다: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "Mr. Poopybutthole" + } + ] +} +``` + +## 요약 + +Pydantic 모델을 사용하여 FastAPI에서 폼 필드를 선언할 수 있습니다. 😎 From 199803085fe819b773d60159b47e4f4e0b366a36 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 12:44:32 +0000 Subject: [PATCH 506/932] =?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 [skip ci] --- 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 e2571ac20..716e9f4ca 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/request-forms.md`. PR [#13003](https://github.com/fastapi/fastapi/pull/13003) by [@hard-coders](https://github.com/hard-coders). * 🌐 Add Korean translation for `docs/ko/docs/resources/index.md`. PR [#13004](https://github.com/fastapi/fastapi/pull/13004) by [@hard-coders](https://github.com/hard-coders). * 🌐 Add Korean translation for `docs/ko/docs/how-to/configure-swagger-ui.md`. PR [#12898](https://github.com/fastapi/fastapi/pull/12898) by [@nahyunkeem](https://github.com/nahyunkeem). * 🌐 Add Korean translation to `docs/ko/docs/advanced/additional-status-codes.md`. PR [#12715](https://github.com/fastapi/fastapi/pull/12715) by [@nahyunkeem](https://github.com/nahyunkeem). From 28f820065f11e5126d484dcad7fa1696343db270 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 12:45:10 +0000 Subject: [PATCH 507/932] =?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 [skip ci] --- 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 716e9f4ca..6a5b7cff4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/request-form-models.md`. PR [#13002](https://github.com/fastapi/fastapi/pull/13002) by [@hard-coders](https://github.com/hard-coders). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/request-forms.md`. PR [#13003](https://github.com/fastapi/fastapi/pull/13003) by [@hard-coders](https://github.com/hard-coders). * 🌐 Add Korean translation for `docs/ko/docs/resources/index.md`. PR [#13004](https://github.com/fastapi/fastapi/pull/13004) by [@hard-coders](https://github.com/hard-coders). * 🌐 Add Korean translation for `docs/ko/docs/how-to/configure-swagger-ui.md`. PR [#12898](https://github.com/fastapi/fastapi/pull/12898) by [@nahyunkeem](https://github.com/nahyunkeem). From f4a023451d38eb43eda04d64ee84796e046dd6d8 Mon Sep 17 00:00:00 2001 From: "hy.lee" Date: Mon, 9 Dec 2024 21:45:39 +0900 Subject: [PATCH 508/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/tutorial/header-param-models.md`=20(#1?= =?UTF-8?q?3001)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/tutorial/header-param-models.md | 56 ++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 docs/ko/docs/tutorial/header-param-models.md diff --git a/docs/ko/docs/tutorial/header-param-models.md b/docs/ko/docs/tutorial/header-param-models.md new file mode 100644 index 000000000..bab7291e3 --- /dev/null +++ b/docs/ko/docs/tutorial/header-param-models.md @@ -0,0 +1,56 @@ +# 헤더 매개변수 모델 + +관련 있는 **헤더 매개변수** 그룹이 있는 경우, **Pydantic 모델**을 생성하여 선언할 수 있습니다. + +이를 통해 **여러 위치**에서 **모델을 재사용** 할 수 있고 모든 매개변수에 대한 유효성 검사 및 메타데이터를 한 번에 선언할 수도 있습니다. 😎 + +/// note | 참고 + +이 기능은 FastAPI 버전 `0.115.0` 이후부터 지원됩니다. 🤓 + +/// + +## Pydantic 모델을 사용한 헤더 매개변수 + +**Pydantic 모델**에 필요한 **헤더 매개변수**를 선언한 다음, 해당 매개변수를 `Header`로 선언합니다: + +{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *} + +**FastAPI**는 요청에서 받은 **헤더**에서 **각 필드**에 대한 데이터를 **추출**하고 정의한 Pydantic 모델을 줍니다. + +## 문서 확인하기 + +문서 UI `/docs`에서 필요한 헤더를 볼 수 있습니다: + +
+ +
+ +## 추가 헤더 금지하기 + +일부 특별한 사용 사례(흔하지는 않겠지만)에서는 수신하려는 헤더를 **제한**할 수 있습니다. + +Pydantic의 모델 구성을 사용하여 추가(`extra`) 필드를 금지(`forbid`)할 수 있습니다: + +{* ../../docs_src/header_param_models/tutorial002_an_py310.py hl[10] *} + +클라이언트가 **추가 헤더**를 보내려고 시도하면, **오류** 응답을 받게 됩니다. + +예를 들어, 클라이언트가 `plumbus` 값으로 `tool` 헤더를 보내려고 하면, 클라이언트는 헤더 매개변수 `tool`이 허용 되지 않는다는 **오류** 응답을 받게 됩니다: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["header", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ] +} +``` + +## 요약 + +**Pydantic 모델**을 사용하여 **FastAPI**에서 **헤더**를 선언할 수 있습니다. 😎 From 95267e58de306d39a9dde036a508ef1a4601b500 Mon Sep 17 00:00:00 2001 From: "hy.lee" Date: Mon, 9 Dec 2024 21:47:02 +0900 Subject: [PATCH 509/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/tutorial/cookie-param-models.md`=20(#1?= =?UTF-8?q?3000)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/tutorial/cookie-param-models.md | 76 ++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 docs/ko/docs/tutorial/cookie-param-models.md diff --git a/docs/ko/docs/tutorial/cookie-param-models.md b/docs/ko/docs/tutorial/cookie-param-models.md new file mode 100644 index 000000000..e7eef0b1d --- /dev/null +++ b/docs/ko/docs/tutorial/cookie-param-models.md @@ -0,0 +1,76 @@ +# 쿠키 매개변수 모델 + +관련있는 **쿠키**들의 그룹이 있는 경우, **Pydantic 모델**을 생성하여 선언할 수 있습니다. 🍪 + +이를 통해 **여러 위치**에서 **모델을 재사용** 할 수 있고 모든 매개변수에 대한 유효성 검사 및 메타데이터를 한 번에 선언할 수도 있습니다. 😍 + +/// note | 참고 + +이 기능은 FastAPI 버전 `0.115.0` 이후부터 지원됩니다. 🤓 + +/// + +/// tip | 팁 + +동일한 기술이 `Query`, `Cookie`, 그리고 `Header`에 적용됩니다. 😎 + +/// + +## Pydantic 모델을 사용한 쿠키 + +**Pydantic 모델**에 필요한 **쿠키** 매개변수를 선언한 다음, 해당 매개변수를 `Cookie`로 선언합니다: + +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} + +**FastAPI**는 요청에서 받은 **쿠키**에서 **각 필드**에 대한 데이터를 **추출**하고 정의한 Pydantic 모델을 줍니다. + +## 문서 확인하기 + +문서 UI `/docs`에서 정의한 쿠키를 볼 수 있습니다: + +
+ +
+ +/// info | 정보 + +명심하세요, 내부적으로 **브라우저는 쿠키를 특별한 방식으로 처리**하기 때문에 **자바스크립트**가 쉽게 쿠키를 건드릴 수 **없습니다**. + +`/docs`에서 **API 문서 UI**로 이동하면 *경로 작업*에 대한 쿠키의 **문서**를 볼 수 있습니다. + +하지만 아무리 **데이터를 입력**하고 "실행(Execute)"을 클릭해도, 문서 UI는 **자바스크립트**로 작동하기 때문에 쿠키는 전송되지 않고, 아무 값도 쓰지 않은 것처럼 **오류** 메시지를 보게 됩니다. + +/// + +## 추가 쿠키 금지하기 + +일부 특별한 사용 사례(흔하지는 않겠지만)에서는 수신하려는 쿠키를 **제한**할 수 있습니다. + +이제 API는 자신의 쿠키 동의를 제어할 수 있는 권한을 갖게 되었습니다. 🤪🍪 + +Pydantic의 모델 구성을 사용하여 추가(`extra`) 필드를 금지(`forbid`)할 수 있습니다: + +{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *} + +클라이언트가 **추가 쿠키**를 보내려고 시도하면, **오류** 응답을 받게 됩니다. + +API가 거부하는데도 동의를 얻기 위해 애쓰는 불쌍한 쿠키 배너(팝업)들. 🍪 + +예를 들어, 클라이언트가 `good-list-please` 값으로 `santa_tracker` 쿠키를 보내려고 하면 클라이언트는 `santa_tracker` 쿠키가 허용되지 않는다는 **오류** 응답을 받게 됩니다: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "santa_tracker"], + "msg": "Extra inputs are not permitted", + "input": "good-list-please", + } + ] +} +``` + +## 요약 + +**Pydantic 모델**을 사용하여 **FastAPI**에서 **쿠키**를 선언할 수 있습니다. 😍 From c62fa0bd3bd43091c35879f43d9d29270be01297 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 12:47:45 +0000 Subject: [PATCH 510/932] =?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 [skip ci] --- 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 6a5b7cff4..35c8d570a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/header-param-models.md`. PR [#13001](https://github.com/fastapi/fastapi/pull/13001) by [@hard-coders](https://github.com/hard-coders). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/request-form-models.md`. PR [#13002](https://github.com/fastapi/fastapi/pull/13002) by [@hard-coders](https://github.com/hard-coders). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/request-forms.md`. PR [#13003](https://github.com/fastapi/fastapi/pull/13003) by [@hard-coders](https://github.com/hard-coders). * 🌐 Add Korean translation for `docs/ko/docs/resources/index.md`. PR [#13004](https://github.com/fastapi/fastapi/pull/13004) by [@hard-coders](https://github.com/hard-coders). From b0f0abda0d5bc89ba0adc8c473c8f3c440eba33a Mon Sep 17 00:00:00 2001 From: alv2017 Date: Mon, 9 Dec 2024 14:49:43 +0200 Subject: [PATCH 511/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/fastapi-cli.md`=20(#13041)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/fastapi-cli.md | 75 +++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 docs/ru/docs/fastapi-cli.md diff --git a/docs/ru/docs/fastapi-cli.md b/docs/ru/docs/fastapi-cli.md new file mode 100644 index 000000000..c0be4a5df --- /dev/null +++ b/docs/ru/docs/fastapi-cli.md @@ -0,0 +1,75 @@ +# FastAPI CLI + +**FastAPI CLI** это программа командной строки, которую вы можете использовать для запуска вашего FastAPI приложения, для управления FastAPI-проектом, а также для многих других вещей. + +`fastapi-cli` устанавливается вместе со стандартным пакетом FastAPI (при запуске команды `pip install "fastapi[standard]"`). Данный пакет предоставляет доступ к программе `fastapi` через терминал. + +Чтобы запустить приложение FastAPI в режиме разработки, вы можете использовать команду `fastapi dev`: + +
+ +```console +$ fastapi dev main.py + + FastAPI Starting development server 🚀 + + Searching for package file structure from directories with + __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with the + following code: + + from main import app + + app Using import string: main:app + + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: + + 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 [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. +``` + +
+ +Приложение командной строки `fastapi` это и есть **FastAPI CLI**. + +FastAPI CLI берет путь к вашей Python-программе (напр. `main.py`) и автоматически находит объект `FastAPI` (обычно это `app`), затем определяет правильный процесс импорта и запускает сервер приложения. + +Для работы в production окружении вместо `fastapi dev` нужно использовать `fastapi run`. 🚀 + +Внутри **FastAPI CLI** используется Uvicorn, высокопроизводительный, готовый к работе в production сервер ASGI. 😎 + +## `fastapi dev` + +Вызов `fastapi dev` запускает режим разработки. + +По умолчанию включена автоматическая перезагрузка (**auto-reload**), благодаря этому при изменении кода происходит перезагрузка сервера приложения. Эта установка требует значительных ресурсов и делает систему менее стабильной. Используйте её только при разработке. Приложение слушает входящие подключения на IP `127.0.0.1`. Это IP адрес вашей машины, предназначенный для внутренних коммуникаций (`localhost`). + +## `fastapi run` + +Вызов `fastapi run` по умолчанию запускает FastAPI в режиме production. + +По умолчанию функция перезагрузки **auto-reload** отключена. Приложение слушает входящие подключения на IP `0.0.0.0`, т.е. на всех доступных адресах компьютера. Таким образом, приложение будет находиться в публичном доступе для любого, кто может подсоединиться к вашей машине. Продуктовые приложения запускаются именно так, например, с помощью контейнеров. + +В большинстве случаев вы будете (и должны) использовать прокси-сервер ("termination proxy"), который будет поддерживать HTTPS поверх вашего приложения. Всё будет зависеть от того, как вы развертываете приложение: за вас это либо сделает ваш провайдер, либо вам придется сделать настройки самостоятельно. + +/// tip | Подсказка + +Вы можете больше узнать об этом в документации по развертыванию приложений [deployment documentation](deployment/index.md){.internal-link target=_blank}. + +/// From cbfb27ca917a3b88838e73be9e65cb9b9c37c179 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 12:50:03 +0000 Subject: [PATCH 512/932] =?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 [skip ci] --- 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 35c8d570a..2212d6020 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/cookie-param-models.md`. PR [#13000](https://github.com/fastapi/fastapi/pull/13000) by [@hard-coders](https://github.com/hard-coders). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/header-param-models.md`. PR [#13001](https://github.com/fastapi/fastapi/pull/13001) by [@hard-coders](https://github.com/hard-coders). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/request-form-models.md`. PR [#13002](https://github.com/fastapi/fastapi/pull/13002) by [@hard-coders](https://github.com/hard-coders). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/request-forms.md`. PR [#13003](https://github.com/fastapi/fastapi/pull/13003) by [@hard-coders](https://github.com/hard-coders). From 40f90b3a946df3e9ae4b10ea72e98d9949ce3fac Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 12:51:00 +0000 Subject: [PATCH 513/932] =?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 [skip ci] --- 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 2212d6020..eee0338d7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Russian translation for `docs/ru/docs/fastapi-cli.md`. PR [#13041](https://github.com/fastapi/fastapi/pull/13041) by [@alv2017](https://github.com/alv2017). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/cookie-param-models.md`. PR [#13000](https://github.com/fastapi/fastapi/pull/13000) by [@hard-coders](https://github.com/hard-coders). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/header-param-models.md`. PR [#13001](https://github.com/fastapi/fastapi/pull/13001) by [@hard-coders](https://github.com/hard-coders). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/request-form-models.md`. PR [#13002](https://github.com/fastapi/fastapi/pull/13002) by [@hard-coders](https://github.com/hard-coders). From 9e1961331155c630ed89574f3e6f89b8108236f3 Mon Sep 17 00:00:00 2001 From: Dave Hay <89824813+dave-hay@users.noreply.github.com> Date: Mon, 9 Dec 2024 04:57:05 -0800 Subject: [PATCH 514/932] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?README=20installation=20instructions=20(#13011)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/en/docs/index.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7973f341b..66ffd7355 100644 --- a/README.md +++ b/README.md @@ -458,7 +458,7 @@ FastAPI depends on Pydantic and Starlette. ### `standard` Dependencies -When you install FastAPI with `pip install "fastapi[standard]"` it comes the `standard` group of optional dependencies: +When you install FastAPI with `pip install "fastapi[standard]"` it comes with the `standard` group of optional dependencies: Used by Pydantic: diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index 4d0514241..cbe71c87d 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -456,7 +456,7 @@ FastAPI depends on Pydantic and Starlette. ### `standard` Dependencies -When you install FastAPI with `pip install "fastapi[standard]"` it comes the `standard` group of optional dependencies: +When you install FastAPI with `pip install "fastapi[standard]"` it comes with the `standard` group of optional dependencies: Used by Pydantic: From eed1496b0ee80ef4fbbc237e321cc0c9a17c530e Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 12:57:32 +0000 Subject: [PATCH 515/932] =?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 [skip ci] --- 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 eee0338d7..55e90373d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏️ Fix typo in README installation instructions. PR [#13011](https://github.com/fastapi/fastapi/pull/13011) by [@dave-hay](https://github.com/dave-hay). * 📝 Update docs for `fastapi-cli`. PR [#13031](https://github.com/fastapi/fastapi/pull/13031) by [@tiangolo](https://github.com/tiangolo). ### Translations From d0626aa565c1a177763502d6b94b460abf41fb7d Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Mon, 9 Dec 2024 13:00:54 +0000 Subject: [PATCH 516/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20in?= =?UTF-8?q?=20`docs/ru/docs/tutorial/query-param-models.md`=20(#12994)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/tutorial/query-param-models.md | 132 +------------------- 1 file changed, 2 insertions(+), 130 deletions(-) diff --git a/docs/ru/docs/tutorial/query-param-models.md b/docs/ru/docs/tutorial/query-param-models.md index 45de1cc76..4d76d09e8 100644 --- a/docs/ru/docs/tutorial/query-param-models.md +++ b/docs/ru/docs/tutorial/query-param-models.md @@ -14,71 +14,7 @@ Объявите нужные **query-параметры** в **Pydantic-модели**, а после аннотируйте параметр как `Query`: -//// tab | Python 3.10+ - -```Python hl_lines="9-13 17" -{!> ../../docs_src/query_param_models/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-12 16" -{!> ../../docs_src/query_param_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10-14 18" -{!> ../../docs_src/query_param_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Совет - -При возможности используйте версию с `Annotated`. - -/// - -```Python hl_lines="9-13 17" -{!> ../../docs_src/query_param_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ без Annotated - -/// tip | Совет - -При возможности используйте версию с `Annotated`. - -/// - -```Python hl_lines="8-12 16" -{!> ../../docs_src/query_param_models/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Совет - -При возможности используйте версию с `Annotated`. - -/// - -```Python hl_lines="9-13 17" -{!> ../../docs_src/query_param_models/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} **FastAPI извлечёт** данные соответствующие **каждому полю модели** из **query-параметров** запроса и выдаст вам объявленную Pydantic-модель заполненную ими. @@ -96,71 +32,7 @@ Вы можете сконфигурировать Pydantic-модель так, чтобы запретить (`forbid`) все дополнительные (`extra`) поля. -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_param_models/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_param_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_param_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Совет - -При возможности используйте версию с `Annotated`. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_param_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ без Annotated - -/// tip | Совет - -При возможности используйте версию с `Annotated`. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_param_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Совет - -При возможности используйте версию с `Annotated`. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_param_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} Если клиент попробует отправить **дополнительные** данные в **query-параметрах**, то в ответ он получит **ошибку**. From 87accca03ea706bfe87a9cc01e4b25c2740d3b2a Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 13:01:17 +0000 Subject: [PATCH 517/932] =?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 [skip ci] --- 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 55e90373d..1239a38d1 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/ru/docs/tutorial/query-param-models.md`. PR [#12994](https://github.com/fastapi/fastapi/pull/12994) by [@alejsdev](https://github.com/alejsdev). * ✏️ Fix typo in README installation instructions. PR [#13011](https://github.com/fastapi/fastapi/pull/13011) by [@dave-hay](https://github.com/dave-hay). * 📝 Update docs for `fastapi-cli`. PR [#13031](https://github.com/fastapi/fastapi/pull/13031) by [@tiangolo](https://github.com/tiangolo). From d24a3349238dba90854aef17561f2ce5a88d2329 Mon Sep 17 00:00:00 2001 From: heum Date: Mon, 9 Dec 2024 22:07:23 +0900 Subject: [PATCH 518/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/advanced/templates.md`=20(#12726)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/advanced/templates.md | 127 +++++++++++++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 docs/ko/docs/advanced/templates.md diff --git a/docs/ko/docs/advanced/templates.md b/docs/ko/docs/advanced/templates.md new file mode 100644 index 000000000..4cb4cbe0d --- /dev/null +++ b/docs/ko/docs/advanced/templates.md @@ -0,0 +1,127 @@ +# 템플릿 + +**FastAPI**와 함께 원하는 어떤 템플릿 엔진도 사용할 수 있습니다. + +일반적인 선택은 Jinja2로, Flask와 다른 도구에서도 사용됩니다. + +설정을 쉽게 할 수 있는 유틸리티가 있으며, 이를 **FastAPI** 애플리케이션에서 직접 사용할 수 있습니다(Starlette 제공). + +## 의존성 설치 + +가상 환경을 생성하고(virtual environment{.internal-link target=_blank}), 활성화한 후 jinja2를 설치해야 합니다: + + +
+ +```console +$ pip install jinja2 + +---> 100% +``` + +
+ +## 사용하기 `Jinja2Templates` + +* `Jinja2Templates`를 가져옵니다. +* 나중에 재사용할 수 있는 `templates` 객체를 생성합니다. +* 템플릿을 반환할 경로 작업에 `Request` 매개변수를 선언합니다. +* 생성한 `templates`를 사용하여 `TemplateResponse`를 렌더링하고 반환합니다. 템플릿의 이름, 요청 객체 및 Jinja2 템플릿 내에서 사용될 키-값 쌍이 포함된 "컨텍스트" 딕셔너리도 전달합니다. + + +```Python hl_lines="4 11 15-18" +{!../../docs_src/templates/tutorial001.py!} +``` + +/// note | 참고 + +FastAPI 0.108.0 이전과 Starlette 0.29.0에서는 `name`이 첫 번째 매개변수였습니다. + +또한 이전 버전에서는 `request` 객체가 Jinja2의 컨텍스트에서 키-값 쌍의 일부로 전달되었습니다. + +/// + +/// tip | 팁 + +`response_class=HTMLResponse`를 선언하면 문서 UI 응답이 HTML임을 알 수 있습니다. + +/// + +/// note | 기술 세부 사항 +`from starlette.templating import Jinja2Templates`를 사용할 수도 있습니다. + +**FastAPI**는 개발자를 위한 편리함으로 `fastapi.templating` 대신 `starlette.templating`을 제공합니다. 하지만 대부분의 사용 가능한 응답은 Starlette에서 직접 옵니다. `Request` 및 `StaticFiles`도 마찬가지입니다. +/// + +## 템플릿 작성하기 + +그런 다음 `templates/item.html`에 템플릿을 작성할 수 있습니다. 예를 들면: + +```jinja hl_lines="7" +{!../../docs_src/templates/templates/item.html!} +``` + +### 템플릿 컨텍스트 값 + +다음과 같은 HTML에서: + +{% raw %} + +```jinja +Item ID: {{ id }} +``` + +{% endraw %} + +...이는 전달한 "컨텍스트" `dict`에서 가져온 `id`를 표시합니다: + +```Python +{"id": id} +``` + +예를 들어, ID가 `42`일 경우, 이는 다음과 같이 렌더링됩니다: + +```html +Item ID: 42 +``` + +### 템플릿 `url_for` 인수 + +템플릿 내에서 `url_for()`를 사용할 수도 있으며, 이는 *경로 작업 함수*에서 사용될 인수와 동일한 인수를 받습니다. + +따라서 다음과 같은 부분에서: + +{% raw %} + +```jinja + +``` + +{% endraw %} + +...이는 *경로 작업 함수* `read_item(id=id)`가 처리할 동일한 URL로 링크를 생성합니다. + +예를 들어, ID가 `42`일 경우, 이는 다음과 같이 렌더링됩니다: +```html + +``` + +## 템플릿과 정적 파일 + +템플릿 내에서 `url_for()`를 사용할 수 있으며, 예를 들어 `name="static"`으로 마운트한 `StaticFiles`와 함께 사용할 수 있습니다. + +```jinja hl_lines="4" +{!../../docs_src/templates/templates/item.html!} +``` + +이 예제에서는 `static/styles.css`에 있는 CSS 파일에 연결될 것입니다: + +```CSS hl_lines="4" +{!../../docs_src/templates/static/styles.css!} +``` + +그리고 `StaticFiles`를 사용하고 있으므로, 해당 CSS 파일은 **FastAPI** 애플리케이션에서 `/static/styles.css` URL로 자동 제공됩니다. + +## 더 많은 세부 사항 + +템플릿 테스트를 포함한 더 많은 세부 사항은 Starlette의 템플릿 문서를 확인하세요. From bb3cf8b902e8777ce61e31346dcf7d1780d72d04 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 13:07:47 +0000 Subject: [PATCH 519/932] =?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 [skip ci] --- 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 1239a38d1..35feb8984 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/advanced/templates.md`. PR [#12726](https://github.com/fastapi/fastapi/pull/12726) by [@Heumhub](https://github.com/Heumhub). * 🌐 Add Russian translation for `docs/ru/docs/fastapi-cli.md`. PR [#13041](https://github.com/fastapi/fastapi/pull/13041) by [@alv2017](https://github.com/alv2017). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/cookie-param-models.md`. PR [#13000](https://github.com/fastapi/fastapi/pull/13000) by [@hard-coders](https://github.com/hard-coders). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/header-param-models.md`. PR [#13001](https://github.com/fastapi/fastapi/pull/13001) by [@hard-coders](https://github.com/hard-coders). From de1fe4d3880c2e75728fc0a48d311aae822dbc9a Mon Sep 17 00:00:00 2001 From: tinyboxvk <13696594+tinyboxvk@users.noreply.github.com> Date: Mon, 9 Dec 2024 15:50:56 -0400 Subject: [PATCH 520/932] =?UTF-8?q?=F0=9F=94=A7=20Remove=20duplicate=20act?= =?UTF-8?q?ions/checkout=20in=20`notify-translations.yml`=20(#12915)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/notify-translations.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/notify-translations.yml b/.github/workflows/notify-translations.yml index 98aa41e5a..40e92e24d 100644 --- a/.github/workflows/notify-translations.yml +++ b/.github/workflows/notify-translations.yml @@ -30,7 +30,6 @@ jobs: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 - - uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: From 2bbd7ce821bf09dea5117aea02cb4428b32a72d2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 19:51:20 +0000 Subject: [PATCH 521/932] =?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 [skip ci] --- 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 35feb8984..3489df7cb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -28,6 +28,7 @@ hide: ### Internal +* 🔧 Remove duplicate actions/checkout in `notify-translations.yml`. PR [#12915](https://github.com/fastapi/fastapi/pull/12915) by [@tinyboxvk](https://github.com/tinyboxvk). * 🔧 Update team members. PR [#13033](https://github.com/fastapi/fastapi/pull/13033) by [@tiangolo](https://github.com/tiangolo). * 📝 Update sponsors: remove Codacy. PR [#13032](https://github.com/fastapi/fastapi/pull/13032) by [@tiangolo](https://github.com/tiangolo). From 671eba1de6f05f817e4473acf3fb9ca2c7f83e07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E9=9B=B2=E6=98=94=20=28Vincy=20SHI=29?= Date: Tue, 10 Dec 2024 06:39:33 +0800 Subject: [PATCH 522/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Traditional=20Chin?= =?UTF-8?q?ese=20translation=20for=20`docs/zh-hant/docs/virtual-environmen?= =?UTF-8?q?ts.md`=20(#12791)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/virtual-environments.md | 844 ++++++++++++++++++++++ 1 file changed, 844 insertions(+) create mode 100644 docs/zh-hant/docs/virtual-environments.md diff --git a/docs/zh-hant/docs/virtual-environments.md b/docs/zh-hant/docs/virtual-environments.md new file mode 100644 index 000000000..d8e31e08e --- /dev/null +++ b/docs/zh-hant/docs/virtual-environments.md @@ -0,0 +1,844 @@ +# 虛擬環境 + +當你在 Python 專案中工作時,你可能會需要使用一個**虛擬環境**(或類似的機制)來隔離你為每個專案安裝的套件。 + +/// info + +如果你已經了解虛擬環境,知道如何建立和使用它們,你可以考慮跳過這一部分。🤓 + +/// + +/// tip + +**虛擬環境**和**環境變數**是不同的。 + +**環境變數**是系統中的一個變數,可以被程式使用。 + +**虛擬環境**是一個包含一些檔案的目錄。 + +/// + +/// info + +這個頁面將教你如何使用**虛擬環境**以及了解它們的工作原理。 + +如果你計畫使用一個**可以為你管理一切的工具**(包括安裝 Python),試試 uv。 + +/// + +## 建立一個專案 + +首先,為你的專案建立一個目錄。 + +我(指原作者 —— 譯者注)通常會在我的主目錄下建立一個名為 `code` 的目錄。 + +在這個目錄下,我再為每個專案建立一個目錄。 + +
+ +```console +// 進入主目錄 +$ cd +// 建立一個用於存放所有程式碼專案的目錄 +$ mkdir code +// 進入 code 目錄 +$ cd code +// 建立一個用於存放這個專案的目錄 +$ mkdir awesome-project +// 進入這個專案的目錄 +$ cd awesome-project +``` + +
+ +## 建立一個虛擬環境 + +在開始一個 Python 專案的**第一時間**,**在你的專案內部**建立一個虛擬環境。 + +/// tip + +你只需要**在每個專案中操作一次**,而不是每次工作時都操作。 + +/// + +//// tab | `venv` + +你可以使用 Python 自帶的 `venv` 模組來建立一個虛擬環境。 + +
+ +```console +$ python -m venv .venv +``` + +
+ +/// details | 上述命令的含義 + +* `python`: 使用名為 `python` 的程式 +* `-m`: 以腳本的方式呼叫一個模組,我們將告訴它接下來使用哪個模組 +* `venv`: 使用名為 `venv` 的模組,這個模組通常隨 Python 一起安裝 +* `.venv`: 在新目錄 `.venv` 中建立虛擬環境 + +/// + +//// + +//// tab | `uv` + +如果你安裝了 `uv`,你也可以使用它來建立一個虛擬環境。 + +
+ +```console +$ uv venv +``` + +
+ +/// tip + +預設情況下,`uv` 會在一個名為 `.venv` 的目錄中建立一個虛擬環境。 + +但你可以透過傳遞一個額外的引數來自訂它,指定目錄的名稱。 + +/// + +//// + +這個命令會在一個名為 `.venv` 的目錄中建立一個新的虛擬環境。 + +/// details | `.venv`,或是其他名稱 + +你可以在不同的目錄下建立虛擬環境,但通常我們會把它命名為 `.venv`。 + +/// + +## 啟動虛擬環境 + +啟動新的虛擬環境來確保你運行的任何 Python 指令或安裝的套件都能使用到它。 + +/// tip + +**每次**開始一個**新的終端會話**來在這個專案工作時,你都需要執行這個操作。 + +/// + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +或者,如果你在 Windows 上使用 Bash(例如 Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +/// tip + +每次你在這個環境中安裝一個**新的套件**時,都需要**重新啟動**這個環境。 + +這麼做確保了當你使用一個由這個套件安裝的**終端(CLI)程式**時,你使用的是你的虛擬環境中的程式,而不是全域安裝、可能版本不同的程式。 + +/// + +## 檢查虛擬環境是否啟動 + +檢查虛擬環境是否啟動(前面的指令是否生效)。 + +/// tip + +這是**非必需的**,但這是一個很好的方法,可以**檢查**一切是否按預期工作,以及你是否使用了你打算使用的虛擬環境。 + +/// + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +如果它顯示了在你專案(在這個例子中是 `awesome-project`)的 `.venv/bin/python` 中的 `python` 二進位檔案,那麼它就生效了。🎉 + +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +如果它顯示了在你專案(在這個例子中是 `awesome-project`)的 `.venv\Scripts\python` 中的 `python` 二進位檔案,那麼它就生效了。🎉 + +//// + +## 升級 `pip` + +/// tip + +如果你使用 `uv` 來安裝內容,而不是 `pip`,那麼你就不需要升級 `pip`。😎 + +/// + +如果你使用 `pip` 來安裝套件(它是 Python 的預設元件),你應該將它**升級**到最新版本。 + +在安裝套件時出現的許多奇怪的錯誤都可以透過先升級 `pip` 來解決。 + +/// tip + +通常你只需要在建立虛擬環境後**執行一次**這個操作。 + +/// + +確保虛擬環境是啟動的(使用上面的指令),然後運行: + +
+ +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
+ +## 加入 `.gitignore` + +如果你使用 **Git**(這是你應該使用的),加入一個 `.gitignore` 檔案來排除你的 `.venv` 中的所有內容。 + +/// tip + +如果你使用 `uv` 來建立虛擬環境,它會自動為你完成這個操作,你可以跳過這一步。😎 + +/// + +/// tip + +通常你只需要在建立虛擬環境後**執行一次**這個操作。 + +/// + +
+ +```console +$ echo "*" > .venv/.gitignore +``` + +
+ +/// details | 上述指令的含義 + +- `echo "*"`: 將在終端中「顯示」文本 `*`(接下來的部分會對這個操作進行一些修改) +- `>`: 使左邊的指令顯示到終端的任何內容實際上都不會被顯示,而是會被寫入到右邊的檔案中 +- `.gitignore`: 被寫入文本的檔案的名稱 + +而 `*` 對於 Git 來說意味著「所有內容」。所以,它會忽略 `.venv` 目錄中的所有內容。 + +該指令會建立一個名為 .gitignore 的檔案,內容如下: + +```gitignore +* +``` + +/// + +## 安裝套件 + +在啟用虛擬環境後,你可以在其中安裝套件。 + +/// tip + +當你需要安裝或升級套件時,執行本操作**一次**; + +如果你需要再升級版本或新增套件,你可以**再次執行此操作**。 + +/// + +### 直接安裝套件 + +如果你急於安裝,不想使用檔案來聲明專案的套件依賴,你可以直接安裝它們。 + +/// tip + +將程式所需的套件及其版本放在檔案中(例如 `requirements.txt` 或 `pyproject.toml`)是個好(而且非常好)的主意。 + +/// + +//// tab | `pip` + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +如果你有 `uv`: + +
+ +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
+ +//// + +### 從 `requirements.txt` 安裝 + +如果你有一個 `requirements.txt` 檔案,你可以使用它來安裝其中的套件。 + +//// tab | `pip` + +
+ +```console +$ pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +如果你有 `uv`: + +
+ +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +/// details | 關於 `requirements.txt` + +一個包含一些套件的 `requirements.txt` 檔案看起來應該是這樣的: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## 執行程式 + +在啟用虛擬環境後,你可以執行你的程式,它將使用虛擬環境中的 Python 和你在其中安裝的套件。 + +
+ +```console +$ python main.py + +Hello World +``` + +
+ +## 設定編輯器 + +你可能會用到編輯器,請確保設定它使用你建立的相同虛擬環境(它可能會自動偵測到),以便你可以獲得自動完成和内嵌錯誤提示。 + +例如: + +* VS Code +* PyCharm + +/// tip + +通常你只需要在建立虛擬環境時執行此操作**一次**。 + +/// + +## 退出虛擬環境 + +當你完成工作後,你可以**退出**虛擬環境。 + +
+ +```console +$ deactivate +``` + +
+ +這樣,當你執行 `python` 時它不會嘗試從已安裝套件的虛擬環境中執行。 + +## 開始工作 + +現在你已經準備好開始你的工作了。 + + + +/// tip + +你想要理解上面的所有內容嗎? + +繼續閱讀。👇🤓 + +/// + +## 為什麼要使用虛擬環境 + +你需要安裝 Python 才能使用 FastAPI。 + +接下來,你需要**安裝** FastAPI 以及你想使用的其他**套件**。 + +要安裝套件,你通常會使用隨 Python 一起提供的 `pip` 指令(或類似的替代工具)。 + +然而,如果你直接使用 `pip`,套件將會安裝在你的**全域 Python 環境**中(即 Python 的全域安裝)。 + +### 存在的問題 + +那麼,在全域 Python 環境中安裝套件有什麼問題呢? + +有時候,你可能會開發許多不同的程式,而這些程式各自依賴於**不同的套件**;有些專案甚至需要依賴於**相同套件的不同版本**。😱 + +例如,你可能會建立一個名為 `philosophers-stone` 的專案,這個程式依賴於另一個名為 **`harry` 的套件,並使用版本 `1`**。因此,你需要安裝 `harry`。 + +```mermaid +flowchart LR + stone(philosophers-stone) -->|需要| harry-1[harry v1] +``` + +然而,在此之後,你又建立了另一個名為 `prisoner-of-azkaban` 的專案,而這個專案也依賴於 `harry`,但需要的是 **`harry` 版本 `3`**。 + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |需要| harry-3[harry v3] +``` + +現在的問題是,如果你在全域環境中安裝套件而不是在本地**虛擬環境**中,你將面臨選擇安裝哪個版本的 `harry` 的困境。 + +如果你想運行 `philosophers-stone`,你需要先安裝 `harry` 版本 `1`,例如: + +
+ +```console +$ pip install "harry==1" +``` + +
+ +然後你會在全域 Python 環境中安裝 `harry` 版本 `1`。 + +```mermaid +flowchart LR + subgraph global[全域環境] + harry-1[harry v1] + end + subgraph stone-project[專案 philosophers-stone] + stone(philosophers-stone) -->|需要| harry-1 + end +``` + +但如果你想運行 `prisoner-of-azkaban`,你需要解除安裝 `harry` 版本 `1` 並安裝 `harry` 版本 `3`(或者只要你安裝版本 `3`,版本 `1` 就會自動移除)。 + +
+ +```console +$ pip install "harry==3" +``` + +
+ +於是,你在全域 Python 環境中安裝了 `harry` 版本 `3`。 + +如果你再次嘗試運行 `philosophers-stone`,很可能會**無法正常運作**,因為它需要的是 `harry` 版本 `1`。 + +```mermaid +flowchart LR + subgraph global[全域環境] + harry-1[harry v1] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[專案 philosophers-stone] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[專案 prisoner-of-azkaban] + azkaban(prisoner-of-azkaban) --> |需要| harry-3 + end +``` + +/// tip + +Python 套件在推出**新版本**時通常會儘量**避免破壞性更改**,但最好還是要謹慎,在安裝新版本前進行測試,以確保一切能正常運行。 + +/// + +現在,想像一下如果有**許多**其他**套件**,它們都是你的**專案所依賴的**。這樣是非常難以管理的。你可能會發現有些專案使用了一些**不相容的套件版本**,而無法得知為什麼某些程式無法正常運作。 + +此外,取決於你的操作系統(例如 Linux、Windows、macOS),它可能已經預先安裝了 Python。在這種情況下,它可能已經有一些系統所需的套件和特定版本。如果你在全域 Python 環境中安裝套件,可能會**破壞**某些隨作業系統一起安裝的程式。 + +## 套件安裝在哪裡 + +當你安裝 Python 時,它會在你的電腦中建立一些目錄並放置一些檔案。 + +其中一些目錄專門用來存放你所安裝的所有套件。 + +當你運行: + +
+ +```console +// 先別去運行這個指令,這只是個示例 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
+ +這會從 PyPI 下載一個壓縮檔案,其中包含 FastAPI 的程式碼。 + +它還會**下載** FastAPI 所依賴的其他套件的檔案。 + +接著,它會**解壓**所有這些檔案,並將它們放在你的電腦中的某個目錄中。 + +預設情況下,這些下載和解壓的檔案會放置於隨 Python 安裝的目錄中,即**全域環境**。 + +## 什麼是虛擬環境 + +解決套件都安裝在全域環境中的問題方法是為你所做的每個專案使用一個**虛擬環境**。 + +虛擬環境是一個**目錄**,與全域環境非常相似,你可以在其中針對某個專案安裝套件。 + +這樣,每個專案都會有自己的虛擬環境(`.venv` 目錄),其中包含自己的套件。 + +```mermaid +flowchart TB + subgraph stone-project[專案 philosophers-stone] + stone(philosophers-stone) --->|需要| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[專案 prisoner-of-azkaban] + azkaban(prisoner-of-azkaban) --->|需要| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## 啟用虛擬環境意味著什麼 + +當你啟用了虛擬環境,例如: + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +或者如果你在 Windows 上使用 Bash(例如 Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +這個命令會建立或修改一些[環境變數](environment-variables.md){.internal-link target=_blank},這些環境變數將在接下來的指令中可用。 + +其中之一是 `PATH` 變數。 + +/// tip + +你可以在 [環境變數](environment-variables.md#path-environment-variable){.internal-link target=_blank} 部分了解更多關於 `PATH` 環境變數的內容。 + +/// + +啟用虛擬環境會將其路徑 `.venv/bin`(在 Linux 和 macOS 上)或 `.venv\Scripts`(在 Windows 上)加入到 `PATH` 環境變數中。 + +假設在啟用環境之前,`PATH` 變數看起來像這樣: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +這意味著系統會在以下目錄中查找程式: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +這意味著系統會在以下目錄中查找程式: + +* `C:\Windows\System32` + +//// + +啟用虛擬環境後,`PATH` 變數會變成這樣: + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +這意味著系統現在會首先在以下目錄中查找程式: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +然後再在其他目錄中查找。 + +因此,當你在終端機中輸入 `python` 時,系統會在以下目錄中找到 Python 程式: + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +並使用這個。 + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +這意味著系統現在會首先在以下目錄中查找程式: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +然後再在其他目錄中查找。 + +因此,當你在終端機中輸入 `python` 時,系統會在以下目錄中找到 Python 程式: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +並使用這個。 + +//// + +一個重要的細節是,虛擬環境路徑會被放在 `PATH` 變數的**開頭**。系統會在找到任何其他可用的 Python **之前**找到它。這樣,當你運行 `python` 時,它會使用**虛擬環境中的** Python,而不是任何其他 `python`(例如,全域環境中的 `python`)。 + +啟用虛擬環境還會改變其他一些內容,但這是它所做的最重要的事情之一。 + +## 檢查虛擬環境 + +當你檢查虛擬環境是否啟動時,例如: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +//// + +這表示將使用的 `python` 程式是**在虛擬環境中**的那一個。 + +在 Linux 和 macOS 中使用 `which`,在 Windows PowerShell 中使用 `Get-Command`。 + +這個指令的運作方式是,它會在 `PATH` 環境變數中搜尋,依序**逐個路徑**查找名為 `python` 的程式。一旦找到,它會**顯示該程式的路徑**。 + +最重要的是,當你呼叫 `python` 時,將執行的就是這個確切的 "`python`"。 + +因此,你可以確認是否在正確的虛擬環境中。 + +/// tip + +啟動一個虛擬環境,取得一個 Python,然後**切換到另一個專案**是件很容易的事; + +但如果第二個專案**無法正常運作**,那可能是因為你使用了來自其他專案的虛擬環境的、**不正確的 Python**。 + +因此,檢查正在使用的 `python` 是非常實用的。🤓 + +/// + +## 為什麼要停用虛擬環境 + +例如,你可能正在一個專案 `philosophers-stone` 上工作,**啟動了該虛擬環境**,安裝了套件並使用了該環境, + +然後你想要在**另一個專案** `prisoner-of-azkaban` 上工作, + +你進入那個專案: + +
+ +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
+ +如果你不去停用 `philosophers-stone` 的虛擬環境,當你在終端中執行 `python` 時,它會嘗試使用 `philosophers-stone` 中的 Python。 + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// 匯入 sirius 錯誤,未安裝 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
+ +但如果你停用虛擬環境並啟用 `prisoner-of-askaban` 的新虛擬環境,那麼當你執行 `python` 時,它會使用 `prisoner-of-askaban` 中虛擬環境的 Python。 + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +// 你不需要在舊目錄中操作停用,你可以在任何地方操作停用,甚至在切換到另一個專案之後 😎 +$ deactivate + +// 啟用 prisoner-of-azkaban/.venv 中的虛擬環境 🚀 +$ source .venv/bin/activate + +// 現在當你執行 python 時,它會在這個虛擬環境中找到已安裝的 sirius 套件 ✨ +$ python main.py + +I solemnly swear 🐺 +``` + +
+ +## 替代方案 + +這是一個簡單的指南,幫助你入門並教會你如何理解一切**底層**的原理。 + +有許多**替代方案**來管理虛擬環境、套件依賴(requirements)、專案。 + +當你準備好並想要使用一個工具來**管理整個專案**、套件依賴、虛擬環境等,建議你嘗試 uv。 + +`uv` 可以執行許多操作,它可以: + +* 為你**安裝 Python**,包括不同的版本 +* 為你的專案管理**虛擬環境** +* 安裝**套件** +* 為你的專案管理套件的**依賴和版本** +* 確保你有一個**精確**的套件和版本集合來安裝,包括它們的依賴項,這樣你可以確保專案在生產環境中運行的狀態與開發時在你的電腦上運行的狀態完全相同,這被稱為**鎖定** +* 還有很多其他功能 + +## 結論 + +如果你讀過並理解了所有這些,現在**你對虛擬環境的了解已超過許多開發者**。🤓 + +未來當你為看起來複雜的問題除錯時,了解這些細節很可能會有所幫助,你會知道**它是如何在底層運作的**。😎 From 502c928ab1441f1bf7c1e43e6da9d207d722fca6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 22:40:00 +0000 Subject: [PATCH 523/932] =?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 [skip ci] --- 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 3489df7cb..e050991a3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/virtual-environments.md`. PR [#12791](https://github.com/fastapi/fastapi/pull/12791) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Add Korean translation for `docs/ko/docs/advanced/templates.md`. PR [#12726](https://github.com/fastapi/fastapi/pull/12726) by [@Heumhub](https://github.com/Heumhub). * 🌐 Add Russian translation for `docs/ru/docs/fastapi-cli.md`. PR [#13041](https://github.com/fastapi/fastapi/pull/13041) by [@alv2017](https://github.com/alv2017). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/cookie-param-models.md`. PR [#13000](https://github.com/fastapi/fastapi/pull/13000) by [@hard-coders](https://github.com/hard-coders). From 2fe5ee41514328359a3f876f8690707765f8bf19 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Dec 2024 22:43:15 +0000 Subject: [PATCH 524/932] =?UTF-8?q?=E2=AC=86=20Bump=20astral-sh/setup-uv?= =?UTF-8?q?=20from=203=20to=204=20(#12982)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv) from 3 to 4. - [Release notes](https://github.com/astral-sh/setup-uv/releases) - [Commits](https://github.com/astral-sh/setup-uv/compare/v3...v4) --- updated-dependencies: - dependency-name: astral-sh/setup-uv dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/build-docs.yml | 4 ++-- .github/workflows/deploy-docs.yml | 2 +- .github/workflows/label-approved.yml | 2 +- .github/workflows/notify-translations.yml | 2 +- .github/workflows/smokeshow.yml | 2 +- .github/workflows/test.yml | 6 +++--- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index dd11727c7..36d3780ac 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -53,7 +53,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v3 + uses: astral-sh/setup-uv@v4 with: version: "0.4.15" enable-cache: true @@ -95,7 +95,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v3 + uses: astral-sh/setup-uv@v4 with: version: "0.4.15" enable-cache: true diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 387063f12..a8383e5c6 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -29,7 +29,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v3 + uses: astral-sh/setup-uv@v4 with: version: "0.4.15" enable-cache: true diff --git a/.github/workflows/label-approved.yml b/.github/workflows/label-approved.yml index 11176bed8..7ecb65547 100644 --- a/.github/workflows/label-approved.yml +++ b/.github/workflows/label-approved.yml @@ -26,7 +26,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v3 + uses: astral-sh/setup-uv@v4 with: version: "0.4.15" enable-cache: true diff --git a/.github/workflows/notify-translations.yml b/.github/workflows/notify-translations.yml index 40e92e24d..edf3e838f 100644 --- a/.github/workflows/notify-translations.yml +++ b/.github/workflows/notify-translations.yml @@ -35,7 +35,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v3 + uses: astral-sh/setup-uv@v4 with: version: "0.4.15" enable-cache: true diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index daff8e244..51e5f56fd 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -26,7 +26,7 @@ jobs: with: python-version: '3.9' - name: Setup uv - uses: astral-sh/setup-uv@v3 + uses: astral-sh/setup-uv@v4 with: version: "0.4.15" enable-cache: true diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 643037a12..0c87d8ed3 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -29,7 +29,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v3 + uses: astral-sh/setup-uv@v4 with: version: "0.4.15" enable-cache: true @@ -66,7 +66,7 @@ jobs: with: python-version: ${{ matrix.python-version }} - name: Setup uv - uses: astral-sh/setup-uv@v3 + uses: astral-sh/setup-uv@v4 with: version: "0.4.15" enable-cache: true @@ -107,7 +107,7 @@ jobs: with: python-version: '3.8' - name: Setup uv - uses: astral-sh/setup-uv@v3 + uses: astral-sh/setup-uv@v4 with: version: "0.4.15" enable-cache: true From d2891b651d63141e0e70ba33eb3d686447e8e827 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Dec 2024 22:43:24 +0000 Subject: [PATCH 525/932] =?UTF-8?q?=E2=AC=86=20Bump=20cloudflare/wrangler-?= =?UTF-8?q?action=20from=203.12=20to=203.13=20(#12996)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [cloudflare/wrangler-action](https://github.com/cloudflare/wrangler-action) from 3.12 to 3.13. - [Release notes](https://github.com/cloudflare/wrangler-action/releases) - [Changelog](https://github.com/cloudflare/wrangler-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/cloudflare/wrangler-action/compare/v3.12...v3.13) --- updated-dependencies: - dependency-name: cloudflare/wrangler-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/deploy-docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index a8383e5c6..648539d47 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -64,7 +64,7 @@ jobs: BRANCH: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} # TODO: Use v3 when it's fixed, probably in v3.11 # https://github.com/cloudflare/wrangler-action/issues/307 - uses: cloudflare/wrangler-action@v3.12 + uses: cloudflare/wrangler-action@v3.13 # uses: cloudflare/wrangler-action@v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} From f6cf06c8647affbb516a02bd8af421498cae49cd Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 22:43:37 +0000 Subject: [PATCH 526/932] =?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 [skip ci] --- 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 e050991a3..27b40d202 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -29,6 +29,7 @@ hide: ### Internal +* ⬆ Bump astral-sh/setup-uv from 3 to 4. PR [#12982](https://github.com/fastapi/fastapi/pull/12982) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Remove duplicate actions/checkout in `notify-translations.yml`. PR [#12915](https://github.com/fastapi/fastapi/pull/12915) by [@tinyboxvk](https://github.com/tinyboxvk). * 🔧 Update team members. PR [#13033](https://github.com/fastapi/fastapi/pull/13033) by [@tiangolo](https://github.com/tiangolo). * 📝 Update sponsors: remove Codacy. PR [#13032](https://github.com/fastapi/fastapi/pull/13032) by [@tiangolo](https://github.com/tiangolo). From 28f22e326c204505949ec9d68c5df108818b06a8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 22:43:46 +0000 Subject: [PATCH 527/932] =?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 [skip ci] --- 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 27b40d202..72fb9242b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -29,6 +29,7 @@ hide: ### Internal +* ⬆ Bump cloudflare/wrangler-action from 3.12 to 3.13. PR [#12996](https://github.com/fastapi/fastapi/pull/12996) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump astral-sh/setup-uv from 3 to 4. PR [#12982](https://github.com/fastapi/fastapi/pull/12982) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Remove duplicate actions/checkout in `notify-translations.yml`. PR [#12915](https://github.com/fastapi/fastapi/pull/12915) by [@tinyboxvk](https://github.com/tinyboxvk). * 🔧 Update team members. PR [#13033](https://github.com/fastapi/fastapi/pull/13033) by [@tiangolo](https://github.com/tiangolo). From ce843bb8e13ae197dfb86d12e3d61fe64a95d9d1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Dec 2024 22:44:36 +0000 Subject: [PATCH 528/932] =?UTF-8?q?=E2=AC=86=20Bump=20dirty-equals=20from?= =?UTF-8?q?=200.6.0=20to=200.8.0=20(#13015)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [dirty-equals](https://github.com/samuelcolvin/dirty-equals) from 0.6.0 to 0.8.0. - [Release notes](https://github.com/samuelcolvin/dirty-equals/releases) - [Commits](https://github.com/samuelcolvin/dirty-equals/compare/v0.6.0...v0.8.0) --- updated-dependencies: - dependency-name: dirty-equals dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-tests.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-tests.txt b/requirements-tests.txt index 95ec09884..bfbb603f6 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -3,7 +3,7 @@ pytest >=7.1.3,<9.0.0 coverage[toml] >= 6.5.0,< 8.0 mypy ==1.8.0 -dirty-equals ==0.6.0 +dirty-equals ==0.8.0 sqlmodel==0.0.22 flask >=1.1.2,<4.0.0 anyio[trio] >=3.2.1,<4.0.0 From fe604f360f8f8609af40f4da2ec91854ed469f02 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Dec 2024 22:44:46 +0000 Subject: [PATCH 529/932] =?UTF-8?q?=E2=AC=86=20Bump=20inline-snapshot=20fr?= =?UTF-8?q?om=200.13.0=20to=200.14.0=20(#13017)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [inline-snapshot](https://github.com/15r10nk/inline-snapshot) from 0.13.0 to 0.14.0. - [Release notes](https://github.com/15r10nk/inline-snapshot/releases) - [Changelog](https://github.com/15r10nk/inline-snapshot/blob/main/CHANGELOG.md) - [Commits](https://github.com/15r10nk/inline-snapshot/compare/v0.13.0...v0.14.0) --- updated-dependencies: - dependency-name: inline-snapshot dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-tests.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-tests.txt b/requirements-tests.txt index bfbb603f6..204bada8e 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -10,7 +10,7 @@ anyio[trio] >=3.2.1,<4.0.0 PyJWT==2.8.0 pyyaml >=5.3.1,<7.0.0 passlib[bcrypt] >=1.7.2,<2.0.0 -inline-snapshot==0.13.0 +inline-snapshot==0.14.0 # types types-ujson ==5.7.0.1 types-orjson ==3.6.2 From cb6edde2e50c08d1f3f0b355e5a9e87645e33c85 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 22:45:09 +0000 Subject: [PATCH 530/932] =?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 [skip ci] --- 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 72fb9242b..a85e827af 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -29,6 +29,7 @@ hide: ### Internal +* ⬆ Bump dirty-equals from 0.6.0 to 0.8.0. PR [#13015](https://github.com/fastapi/fastapi/pull/13015) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump cloudflare/wrangler-action from 3.12 to 3.13. PR [#12996](https://github.com/fastapi/fastapi/pull/12996) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump astral-sh/setup-uv from 3 to 4. PR [#12982](https://github.com/fastapi/fastapi/pull/12982) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Remove duplicate actions/checkout in `notify-translations.yml`. PR [#12915](https://github.com/fastapi/fastapi/pull/12915) by [@tinyboxvk](https://github.com/tinyboxvk). From 329a81777ba1cfea773888e21c55ee94ee50e3ff Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Dec 2024 22:45:45 +0000 Subject: [PATCH 531/932] =?UTF-8?q?=E2=AC=86=20Bump=20black=20from=2024.3.?= =?UTF-8?q?0=20to=2024.10.0=20(#13014)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [black](https://github.com/psf/black) from 24.3.0 to 24.10.0. - [Release notes](https://github.com/psf/black/releases) - [Changelog](https://github.com/psf/black/blob/main/CHANGES.md) - [Commits](https://github.com/psf/black/compare/24.3.0...24.10.0) --- updated-dependencies: - dependency-name: black dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs.txt b/requirements-docs.txt index 9754eaa4a..bb11f01c6 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -14,6 +14,6 @@ cairosvg==2.7.1 mkdocstrings[python]==0.26.1 griffe-typingdoc==0.2.7 # For griffe, it formats with black -black==24.3.0 +black==24.10.0 mkdocs-macros-plugin==1.0.5 markdown-include-variants==0.0.3 From b4155f7a76369e985738899ece5ef6c47380224d Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 22:46:35 +0000 Subject: [PATCH 532/932] =?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 [skip ci] --- 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 a85e827af..d9a14d554 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -29,6 +29,7 @@ hide: ### Internal +* ⬆ Bump inline-snapshot from 0.13.0 to 0.14.0. PR [#13017](https://github.com/fastapi/fastapi/pull/13017) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump dirty-equals from 0.6.0 to 0.8.0. PR [#13015](https://github.com/fastapi/fastapi/pull/13015) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump cloudflare/wrangler-action from 3.12 to 3.13. PR [#12996](https://github.com/fastapi/fastapi/pull/12996) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump astral-sh/setup-uv from 3 to 4. PR [#12982](https://github.com/fastapi/fastapi/pull/12982) by [@dependabot[bot]](https://github.com/apps/dependabot). From dfb6a6b74a00a7cd8273f6cacb00351f71429fbe Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 22:50:51 +0000 Subject: [PATCH 533/932] =?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 [skip ci] --- 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 d9a14d554..45fa50541 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -29,6 +29,7 @@ hide: ### Internal +* ⬆ Bump black from 24.3.0 to 24.10.0. PR [#13014](https://github.com/fastapi/fastapi/pull/13014) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump inline-snapshot from 0.13.0 to 0.14.0. PR [#13017](https://github.com/fastapi/fastapi/pull/13017) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump dirty-equals from 0.6.0 to 0.8.0. PR [#13015](https://github.com/fastapi/fastapi/pull/13015) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump cloudflare/wrangler-action from 3.12 to 3.13. PR [#12996](https://github.com/fastapi/fastapi/pull/12996) by [@dependabot[bot]](https://github.com/apps/dependabot). From 889005d07daec79113fd9c041972ffd3f3ac0be4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Dec 2024 22:53:31 +0000 Subject: [PATCH 534/932] =?UTF-8?q?=E2=AC=86=20Bump=20types-ujson=20from?= =?UTF-8?q?=205.7.0.1=20to=205.10.0.20240515=20(#13018)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [types-ujson](https://github.com/python/typeshed) from 5.7.0.1 to 5.10.0.20240515. - [Commits](https://github.com/python/typeshed/commits) --- updated-dependencies: - dependency-name: types-ujson dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-tests.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-tests.txt b/requirements-tests.txt index 204bada8e..b607998a3 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -12,5 +12,5 @@ pyyaml >=5.3.1,<7.0.0 passlib[bcrypt] >=1.7.2,<2.0.0 inline-snapshot==0.14.0 # types -types-ujson ==5.7.0.1 +types-ujson ==5.10.0.20240515 types-orjson ==3.6.2 From f7bff17f986431f4be6a3c3b084dd7edd198fe69 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 9 Dec 2024 22:53:53 +0000 Subject: [PATCH 535/932] =?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 [skip ci] --- 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 45fa50541..1eccea478 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -29,6 +29,7 @@ hide: ### Internal +* ⬆ Bump types-ujson from 5.7.0.1 to 5.10.0.20240515. PR [#13018](https://github.com/fastapi/fastapi/pull/13018) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump black from 24.3.0 to 24.10.0. PR [#13014](https://github.com/fastapi/fastapi/pull/13014) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump inline-snapshot from 0.13.0 to 0.14.0. PR [#13017](https://github.com/fastapi/fastapi/pull/13017) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump dirty-equals from 0.6.0 to 0.8.0. PR [#13015](https://github.com/fastapi/fastapi/pull/13015) by [@dependabot[bot]](https://github.com/apps/dependabot). From 365d9b93c3750ae537a4a7f5e990f7e98a59a7dc Mon Sep 17 00:00:00 2001 From: YungYueh ChanLee Date: Tue, 10 Dec 2024 18:48:41 +0800 Subject: [PATCH 536/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Traditional=20Chin?= =?UTF-8?q?ese=20translation=20for=20`docs/zh-hant/docs/features.md`=20(#1?= =?UTF-8?q?2441)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/features.md | 207 ++++++++++++++++++++++++++++++++++ 1 file changed, 207 insertions(+) create mode 100644 docs/zh-hant/docs/features.md diff --git a/docs/zh-hant/docs/features.md b/docs/zh-hant/docs/features.md new file mode 100644 index 000000000..3a1392b51 --- /dev/null +++ b/docs/zh-hant/docs/features.md @@ -0,0 +1,207 @@ +# 特性 + +## FastAPI 特性 + +**FastAPI** 提供了以下内容: + +### 建立在開放標準的基礎上 + +* 使用 OpenAPI 來建立 API,包含路徑操作、參數、請求內文、安全性等聲明。 +* 使用 JSON Schema(因為 OpenAPI 本身就是基於 JSON Schema)自動生成資料模型文件。 +* 經過縝密的研究後圍繞這些標準進行設計,而不是事後在已有系統上附加的一層功能。 +* 這也讓我們在多種語言中可以使用自動**用戶端程式碼生成**。 + +### 能夠自動生成文件 + +FastAPI 能生成互動式 API 文件和探索性的 Web 使用者介面。由於該框架基於 OpenAPI,因此有多種選擇,預設提供了兩種。 + +* Swagger UI 提供互動式探索,讓你可以直接從瀏覽器呼叫並測試你的 API 。 + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* ReDoc 提供結構性的文件,讓你可以在瀏覽器中查看。 + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + + +### 現代 Python + +這一切都基於標準的 **Python 型別**宣告(感謝 Pydantic)。無需學習新的語法,只需使用標準的現代 Python。 + +如果你需要 2 分鐘來學習如何使用 Python 型別(即使你不使用 FastAPI),可以看看這個簡短的教學:[Python 型別](python-types.md){.internal-link target=_blank}。 + +如果你寫帶有 Python 型別的程式碼: + +```python +from datetime import date + +from pydantic import BaseModel + +# 宣告一個變數為 string +# 並在函式中獲得 editor support +def main(user_id: str): + return user_id + + +# 宣告一個 Pydantic model +class User(BaseModel): + id: int + name: str + joined: date +``` + + +可以像這樣來使用: + +```python +my_user: User = User(id=3, name="John Doe", joined="2018-07-19") + +second_user_data = { + "id": 4, + "name": "Mary", + "joined": "2018-11-30", +} + +my_second_user: User = User(**second_user_data) +``` + + +/// info + +`**second_user_data` 意思是: + +將 `second_user_data` 字典直接作為 key-value 引數傳遞,等同於:`User(id=4, name="Mary", joined="2018-11-30")` + +/// + +### 多種編輯器支援 + +整個框架的設計是為了讓使用變得簡單且直觀,在開始開發之前,所有決策都在多個編輯器上進行了測試,以確保提供最佳的開發體驗。 + +在最近的 Python 開發者調查中,我們能看到 被使用最多的功能是 autocompletion,此功能可以預測將要輸入文字,並自動補齊。 + +整個 **FastAPI** 框架就是基於這一點,任何地方都可以進行自動補齊。 + +你幾乎不需要經常來回看文件。 + +在這裡,你的編輯器可能會這樣幫助你: + +* Visual Studio Code 中: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +* PyCharm 中: + +![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png) + +你將能進行程式碼補齊,這是在之前你可能曾認為不可能的事。例如,請求 JSON body(可能是巢狀的)中的鍵 `price`。 + +這樣比較不會輸錯鍵名,不用來回翻看文件,也不用來回滾動尋找你最後使用的 `username` 或者 `user_name`。 + + + +### 簡潔 + +FastAPI 為你提供了**預設值**,讓你不必在初期進行繁瑣的配置,一切都可以自動運作。如果你有更具體的需求,則可以進行調整和自定義, + +但在大多數情況下,你只需要直接使用預設值,就能順利完成 API 開發。 + +### 驗證 + +所有的驗證都由完善且強大的 **Pydantic** 處理。 + +* 驗證大部分(甚至所有?)的 Python **資料型別**,包括: + * JSON 物件 (`dict`)。 + * JSON 陣列 (`list`) 定義項目型別。 + * 字串 (`str`) 欄位,定義最小或最大長度。 + * 數字 (`int`, `float`) 與其最大值和最小值等。 + +* 驗證外來的型別,比如: + * URL + * Email + * UUID + + +### 安全性及身份驗證 + +FastAPI 已經整合了安全性和身份驗證的功能,但不會強制與特定的資料庫或資料模型進行綁定。 + +OpenAPI 中定義的安全模式,包括: + +* HTTP 基本認證。 +* **OAuth2**(也使用 **JWT tokens**)。在 [OAuth2 with JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank} 查看教學。 +* API 密鑰,在: + * 標頭(Header) + * 查詢參數 + * Cookies,等等。 + +加上来自 Starlette(包括 **session cookie**)的所有安全特性。 + +所有的這些都是可重複使用的工具和套件,可以輕鬆與你的系統、資料儲存(Data Stores)、關聯式資料庫(RDBMS)以及非關聯式資料庫(NoSQL)等等整合。 + + +### 依賴注入(Dependency Injection) + +FastAPI 有一個使用簡單,但是非常強大的依賴注入系統。 + +* 依賴項甚至可以有自己的依賴,從而形成一個層級或**依賴圖**的結構。 +* 所有**自動化處理**都由框架完成。 +* 依賴項不僅能從請求中提取資料,還能**對 API 的路徑操作進行強化**,並自動生成文檔。 +* 即使是依賴項中定義的*路徑操作參數*,也會**自動進行驗證**。 +* 支持複雜的用戶身份驗證系統、**資料庫連接**等。 +* 不與資料庫、前端等進行強制綁定,但能輕鬆整合它們。 + + +### 無限制「擴充功能」 + +或者說,無需其他額外配置,直接導入並使用你所需要的程式碼。 + +任何整合都被設計得非常簡單易用(通過依賴注入),你只需用與*路徑操作*相同的結構和語法,用兩行程式碼就能為你的應用程式建立一個「擴充功能」。 + + +### 測試 + +* 100% 的測試覆蓋率。 +* 100% 的程式碼有型別註釋。 +* 已能夠在生產環境應用程式中使用。 + +## Starlette 特性 + +**FastAPI** 完全相容且基於 Starlette。所以,你有其他的 Starlette 程式碼也能正常運作。FastAPI 繼承了 Starlette 的所有功能,如果你已經知道或者使用過 Starlette,大部分的功能會以相同的方式運作。 + +通過 **FastAPI** 你可以獲得所有 **Starlette** 的特性(FastAPI 就像加強版的 Starlette): + +* 性能極其出色。它是 Python 可用的最快框架之一,和 **NodeJS** 及 **Go** 相當。 +* **支援 WebSocket**。 +* 能在行程內處理背景任務。 +* 支援啟動和關閉事件。 +* 有基於 HTTPX 的測試用戶端。 +* 支援 **CORS**、GZip、靜態檔案、串流回應。 +* 支援 **Session 和 Cookie** 。 +* 100% 測試覆蓋率。 +* 100% 型別註釋的程式碼庫。 + +## Pydantic 特性 + +**FastAPI** 完全相容且基於 Pydantic。所以,你有其他 Pydantic 程式碼也能正常工作。 + +相容包括基於 Pydantic 的外部函式庫, 例如用於資料庫的 ORMs, ODMs。 + +這也意味著在很多情況下,你可以把從請求中獲得的物件**直接傳到資料庫**,因為所有資料都會自動進行驗證。 + +反之亦然,在很多情況下,你也可以把從資料庫中獲取的物件**直接傳給客戶端**。 + +通過 **FastAPI** 你可以獲得所有 **Pydantic** 的特性(FastAPI 基於 Pydantic 做了所有的資料處理): + +* **更簡單**: + * 不需要學習新的 micro-language 來定義結構。 + * 如果你知道 Python 型別,你就知道如何使用 Pydantic。 +* 和你的 **IDE/linter/brain** 都能好好配合: + * 因為 Pydantic 的資料結構其實就是你自己定義的類別實例,所以自動補齊、linting、mypy 以及你的直覺都能很好地在經過驗證的資料上發揮作用。 +* 驗證**複雜結構**: + * 使用 Pydantic 模型時,你可以把資料結構分層設計,並且用 Python 的 `List` 和 `Dict` 等型別來定義。 + * 驗證器讓我們可以輕鬆地定義和檢查複雜的資料結構,並把它們轉換成 JSON Schema 進行記錄。 + * 你可以擁有深層**巢狀的 JSON** 物件,並對它們進行驗證和註釋。 +* **可擴展**: + * Pydantic 讓我們可以定義客製化的資料型別,或者你可以使用帶有 validator 裝飾器的方法來擴展模型中的驗證功能。 +* 100% 測試覆蓋率。 From d05d970c4d87347d4471604c0a0abce482dded6c Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 10 Dec 2024 10:49:09 +0000 Subject: [PATCH 537/932] =?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 [skip ci] --- 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 1eccea478..c54e6b22f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/features.md`. PR [#12441](https://github.com/fastapi/fastapi/pull/12441) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/virtual-environments.md`. PR [#12791](https://github.com/fastapi/fastapi/pull/12791) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Add Korean translation for `docs/ko/docs/advanced/templates.md`. PR [#12726](https://github.com/fastapi/fastapi/pull/12726) by [@Heumhub](https://github.com/Heumhub). * 🌐 Add Russian translation for `docs/ru/docs/fastapi-cli.md`. PR [#13041](https://github.com/fastapi/fastapi/pull/13041) by [@alv2017](https://github.com/alv2017). From b667e6ff12a226a2ecd4d09aba6c6d7d5a195eb8 Mon Sep 17 00:00:00 2001 From: Aleksandr Andrukhov Date: Tue, 10 Dec 2024 13:52:27 +0300 Subject: [PATCH 538/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/tutorial/security/get-current-user.md?= =?UTF-8?q?`=20(#10594)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tutorial/security/get-current-user.md | 99 +++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 docs/ru/docs/tutorial/security/get-current-user.md diff --git a/docs/ru/docs/tutorial/security/get-current-user.md b/docs/ru/docs/tutorial/security/get-current-user.md new file mode 100644 index 000000000..05eb290d7 --- /dev/null +++ b/docs/ru/docs/tutorial/security/get-current-user.md @@ -0,0 +1,99 @@ +# Данные текущего пользователя + +В предыдущей главе система безопасности (основанная на системе внедрения зависимостей) передавала *функции, обрабатывающей эндпоинт,* `токен` в виде `строки`: + +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} + +Это пока что не слишком нам полезно. Давайте изменим код так, чтобы он возвращал нам данные пользователя, отправившего запрос. + +## Создание модели пользователя + +Сначала создадим Pydantic-модель пользователя. + +Точно так же, как мы использовали Pydantic для объявления тел запросов, мы можем использовать его где угодно: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *} + +## Создание зависимости `get_current_user` + +Давайте создадим зависимость `get_current_user`. + +Помните, что у зависимостей могут быть подзависимости? + +`get_current_user` как раз будет иметь подзависимость `oauth2_scheme`, которую мы создали ранее. + +Аналогично тому, как мы делали это ранее в *обработчике эндпоинта* наша новая зависимость `get_current_user` будет получать `token` в виде `строки` от подзависимости `oauth2_scheme`: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *} + +## Получение данных пользователя + +`get_current_user` будет использовать созданную нами (ненастоящую) служебную функцию, которая принимает токен в виде `строки` и возвращает нашу Pydantic-модель `User`: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *} + +## Внедрение зависимости текущего пользователя + +Теперь мы можем использовать тот же `Depends` с нашей зависимостью `get_current_user` в *функции обрабатывающей эндпоинт*: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *} + +Обратите внимание, что мы объявляем тип переменной `current_user` как Pydantic-модель `User`. + +Это поможет выполнить внутри функции все проверки автозаполнения и типа. + +/// tip | Подсказка +Возможно, вы помните, что тело запроса также объявляется с помощью Pydantic-моделей. + +В этом месте у **FastAPI** не возникнет проблем, потому что вы используете `Depends`. +/// + +/// check | Заметка +То, как устроена эта система зависимостей, позволяет нам иметь различные зависимости, которые возвращают модель `User`. + +Мы не ограничены наличием только одной зависимости, которая может возвращать данные такого типа. +/// + +## Другие модели + +Теперь вы можете получать информацию о текущем пользователе непосредственно в *функции обрабатывающей эндпоинт* и работать с механизмами безопасности на уровне **Внедрения Зависимостей**, используя `Depends`. + +Причем для обеспечения требований безопасности можно использовать любую модель или данные (в данном случае - Pydantic-модель `User`). + +Но вы не ограничены использованием какой-то конкретной моделью данных, классом или типом. + +Вы хотите использовать в модели `id` и `email`, а `username` вам не нужен? Ну разумеется. Воспользуйтесь тем же инструментарием. + +Вам нужны только `строки`? Или только `словари`? Или непосредственно экземпляр модели класса базы данных? Все это работает точно также. + +У вас нет пользователей, которые входят в ваше приложение, а только роботы, боты или другие системы, у которых есть только токен доступа? Опять же, все работает одинаково. + +Просто используйте любую модель, любой класс, любую базу данных, которые нужны для вашего приложения. Система внедрения зависимостей **FastAPI** поможет вам в этом. + +## Размер кода + +Этот пример может показаться многословным. Следует иметь в виду, что в одном файле мы смешиваем безопасность, модели данных, служебные функции и *эндпоинты*. + +Но вот ключевой момент: + +Все, что касается безопасности и внедрения зависимостей, пишется один раз. + +И вы можете сделать его настолько сложным, насколько захотите. И все это будет написано только один раз, в одном месте, со всей своей гибкостью. + +И у вас могут быть тысячи конечных точек (*эндпоинтов*), использующих одну и ту же систему безопасности. + +И все они (или любая их часть по вашему желанию) могут воспользоваться преимуществами повторного использования этих зависимостей или любых других зависимостей, которые вы создадите. + +И все эти тысячи *эндпоинтов* могут составлять всего 3 строки: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *} + +## Резюме + +Теперь вы можете получать данные о текущем пользователе непосредственно в своей *функции обработчике эндпоинта*. + +Мы уже на полпути к этому. + +Осталось лишь добавить *эндпоинт* для отправки пользователем/клиентом своих `имени пользователя` и `пароля`. + +Это будет рассмотрено в следующем разделе. From a54e336b22b2ec15c85e977dfd149f805f281c54 Mon Sep 17 00:00:00 2001 From: Aleksandr Andrukhov Date: Tue, 10 Dec 2024 13:53:40 +0300 Subject: [PATCH 539/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/tutorial/security/simple-oauth2.md`?= =?UTF-8?q?=20(#10599)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/tutorial/security/simple-oauth2.md | 272 ++++++++++++++++++ 1 file changed, 272 insertions(+) create mode 100644 docs/ru/docs/tutorial/security/simple-oauth2.md diff --git a/docs/ru/docs/tutorial/security/simple-oauth2.md b/docs/ru/docs/tutorial/security/simple-oauth2.md new file mode 100644 index 000000000..9732265cc --- /dev/null +++ b/docs/ru/docs/tutorial/security/simple-oauth2.md @@ -0,0 +1,272 @@ +# Простая авторизация по протоколу OAuth2 с токеном типа Bearer + +Теперь, отталкиваясь от предыдущей главы, добавим недостающие части, чтобы получить безопасную систему. + +## Получение `имени пользователя` и `пароля` + +Для получения `имени пользователя` и `пароля` мы будем использовать утилиты безопасности **FastAPI**. + +Протокол OAuth2 определяет, что при использовании "аутентификации по паролю" (которую мы и используем) клиент/пользователь должен передавать поля `username` и `password` в полях формы. + +В спецификации сказано, что поля должны быть названы именно так. Поэтому `user-name` или `email` работать не будут. + +Но не волнуйтесь, вы можете показать его конечным пользователям во фронтенде в том виде, в котором хотите. + +А ваши модели баз данных могут использовать любые другие имена. + +Но при авторизации согласно спецификации, требуется использовать именно эти имена, что даст нам возможность воспользоваться встроенной системой документации API. + +В спецификации также указано, что `username` и `password` должны передаваться в виде данных формы (так что никакого JSON здесь нет). + +### Oбласть видимости (scope) + +В спецификации также говорится, что клиент может передать еще одно поле формы "`scope`". + +Имя поля формы - `scope` (в единственном числе), но на самом деле это длинная строка, состоящая из отдельных областей видимости (scopes), разделенных пробелами. + +Каждая "область видимости" (scope) - это просто строка (без пробелов). + +Обычно они используются для указания уровней доступа, например: + +* `users:read` или `users:write` являются распространенными примерами. +* `instagram_basic` используется Facebook / Instagram. +* `https://www.googleapis.com/auth/drive` используется компанией Google. + +/// info | Дополнительнаяя информация +В OAuth2 "scope" - это просто строка, которая уточняет уровень доступа. + +Не имеет значения, содержит ли он другие символы, например `:`, или является ли он URL. + +Эти детали зависят от конкретной реализации. + +Для OAuth2 это просто строки. +/// + +## Код получения `имени пользователя` и `пароля` + +Для решения задачи давайте воспользуемся утилитами, предоставляемыми **FastAPI**. + +### `OAuth2PasswordRequestForm` + +Сначала импортируйте `OAuth2PasswordRequestForm` и затем используйте ее как зависимость с `Depends` в *эндпоинте* `/token`: + + +{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *} + +`OAuth2PasswordRequestForm` - это класс для использования в качестве зависимости для *функции обрабатывающей эндпоинт*, который определяет тело формы со следующими полями: + +* `username`. +* `password`. +* Необязательное поле `scope` в виде большой строки, состоящей из строк, разделенных пробелами. +* Необязательное поле `grant_type`. + +/// tip | Подсказка +По спецификации OAuth2 поле `grant_type` является обязательным и содержит фиксированное значение `password`, но `OAuth2PasswordRequestForm` не обеспечивает этого. + +Если вам необходимо использовать `grant_type`, воспользуйтесь `OAuth2PasswordRequestFormStrict` вместо `OAuth2PasswordRequestForm`. +/// + +* Необязательное поле `client_id` (в нашем примере он не нужен). +* Необязательное поле `client_secret` (в нашем примере он не нужен). + +/// info | Дополнительная информация +Форма `OAuth2PasswordRequestForm` не является специальным классом для **FastAPI**, как `OAuth2PasswordBearer`. + +`OAuth2PasswordBearer` указывает **FastAPI**, что это схема безопасности. Следовательно, она будет добавлена в OpenAPI. + +Но `OAuth2PasswordRequestForm` - это всего лишь класс зависимости, который вы могли бы написать самостоятельно или вы могли бы объявить параметры `Form` напрямую. + +Но, поскольку это распространённый вариант использования, он предоставляется **FastAPI** напрямую, просто чтобы облегчить задачу. +/// + +### Использование данных формы + +/// tip | Подсказка +В экземпляре зависимого класса `OAuth2PasswordRequestForm` атрибут `scope`, состоящий из одной длинной строки, разделенной пробелами, заменен на атрибут `scopes`, состоящий из списка отдельных строк, каждая из которых соответствует определенному уровню доступа. + +В данном примере мы не используем `scopes`, но если вам это необходимо, то такая функциональность имеется. +/// + +Теперь получим данные о пользователе из (ненастоящей) базы данных, используя `username` из поля формы. + +Если такого пользователя нет, то мы возвращаем ошибку "неверное имя пользователя или пароль". + +Для ошибки мы используем исключение `HTTPException`: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *} + +### Проверка пароля + +На данный момент у нас есть данные о пользователе из нашей базы данных, но мы еще не проверили пароль. + +Давайте сначала поместим эти данные в модель Pydantic `UserInDB`. + +Ни в коем случае нельзя сохранять пароли в открытом виде, поэтому мы будем использовать (пока что ненастоящую) систему хеширования паролей. + +Если пароли не совпадают, мы возвращаем ту же ошибку. + +#### Хеширование паролей + +"Хеширование" означает: преобразование некоторого содержимого (в данном случае пароля) в последовательность байтов (просто строку), которая выглядит как тарабарщина. + +Каждый раз, когда вы передаете точно такое же содержимое (точно такой же пароль), вы получаете точно такую же тарабарщину. + +Но преобразовать тарабарщину обратно в пароль невозможно. + +##### Зачем использовать хеширование паролей + +Если ваша база данных будет украдена, то у вора не будет паролей пользователей в открытом виде, только хэши. + +Таким образом, вор не сможет использовать эти же пароли в другой системе (поскольку многие пользователи используют одни и те же пароли повсеместно, это было бы опасно). + +{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *} + +#### Про `**user_dict` + +`UserInDB(**user_dict)` означает: + +*Передавать ключи и значения `user_dict` непосредственно в качестве аргументов ключ-значение, что эквивалентно:* + +```Python +UserInDB( + username = user_dict["username"], + email = user_dict["email"], + full_name = user_dict["full_name"], + disabled = user_dict["disabled"], + hashed_password = user_dict["hashed_password"], +) +``` + +/// info | Дополнительная информация +Более полное объяснение `**user_dict` можно найти в [документации к **Дополнительным моделям**](../extra-models.md#about-user_indict){.internal-link target=_blank}. +/// + +## Возврат токена + +Ответ эндпоинта `token` должен представлять собой объект в формате JSON. + +Он должен иметь `token_type`. В нашем случае, поскольку мы используем токены типа "Bearer", тип токена должен быть "`bearer`". + +И в нем должна быть строка `access_token`, содержащая наш токен доступа. + +В этом простом примере мы нарушим все правила безопасности, и будем считать, что имя пользователя (username) полностью соответствует токену (token) + +/// tip | Подсказка +В следующей главе мы рассмотрим реальную защищенную реализацию с хешированием паролей и токенами JWT. + +Но пока давайте остановимся на необходимых нам деталях. +/// + +{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *} + +/// tip | Подсказка +Согласно спецификации, вы должны возвращать JSON с `access_token` и `token_type`, как в данном примере. + +Это то, что вы должны сделать сами в своем коде и убедиться, что вы используете эти JSON-ключи. + +Это практически единственное, что нужно не забывать делать самостоятельно, чтобы следовать требованиям спецификации. + +Все остальное за вас сделает **FastAPI**. +/// + +## Обновление зависимостей + +Теперь мы обновим наши зависимости. + +Мы хотим получить значение `current_user` *только* если этот пользователь активен. + +Поэтому мы создаем дополнительную зависимость `get_current_active_user`, которая, в свою очередь, использует в качестве зависимости `get_current_user`. + +Обе эти зависимости просто вернут HTTP-ошибку, если пользователь не существует или неактивен. + +Таким образом, в нашем эндпоинте мы получим пользователя только в том случае, если он существует, правильно аутентифицирован и активен: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *} + +/// info | Дополнительная информация +Дополнительный заголовок `WWW-Authenticate` со значением `Bearer`, который мы здесь возвращаем, также является частью спецификации. + +Ответ сервера с HTTP-кодом 401 "UNAUTHORIZED" должен также возвращать заголовок `WWW-Authenticate`. + +В случае с bearer-токенами (наш случай) значение этого заголовка должно быть `Bearer`. + +На самом деле этот дополнительный заголовок можно пропустить и все будет работать. + +Но он приведён здесь для соответствия спецификации. + +Кроме того, могут существовать инструменты, которые ожидают его и могут использовать, и это может быть полезно для вас или ваших пользователей сейчас или в будущем. + +В этом и заключается преимущество стандартов... +/// + +## Посмотим как это работает + +Откроем интерактивную документацию: http://127.0.0.1:8000/docs. + +### Аутентификация + +Нажмите кнопку "Авторизация". + +Используйте учётные данные: + +Пользователь: `johndoe` + +Пароль: `secret` + + + +После авторизации в системе вы увидите следующее: + + + +### Получение собственных пользовательских данных + +Теперь, используя операцию `GET` с путем `/users/me`, вы получите данные пользователя, например: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false, + "hashed_password": "fakehashedsecret" +} +``` + + + +Если щелкнуть на значке замка и выйти из системы, а затем попытаться выполнить ту же операцию ещё раз, то будет выдана ошибка HTTP 401: + +```JSON +{ + "detail": "Not authenticated" +} +``` + +### Неактивный пользователь + +Теперь попробуйте пройти аутентификацию с неактивным пользователем: + +Пользователь: `alice` + +Пароль: `secret2` + +И попробуйте использовать операцию `GET` с путем `/users/me`. + +Вы получите ошибку "Inactive user", как тут: + +```JSON +{ + "detail": "Inactive user" +} +``` + +## Резюме + +Теперь у вас есть инструменты для реализации полноценной системы безопасности на основе `имени пользователя` и `пароля` для вашего API. + +Используя эти средства, можно сделать систему безопасности совместимой с любой базой данных, с любым пользователем или моделью данных. + + Единственным недостатком нашей системы является то, что она всё ещё не защищена. + +В следующей главе вы увидите, как использовать библиотеку безопасного хеширования паролей и токены JWT. From bc958ac3da557d3671d03c4d989c551ac81c8b9f Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 10 Dec 2024 10:53:56 +0000 Subject: [PATCH 540/932] =?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 [skip ci] --- 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 c54e6b22f..eb8413124 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/get-current-user.md`. PR [#10594](https://github.com/fastapi/fastapi/pull/10594) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/features.md`. PR [#12441](https://github.com/fastapi/fastapi/pull/12441) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/virtual-environments.md`. PR [#12791](https://github.com/fastapi/fastapi/pull/12791) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Add Korean translation for `docs/ko/docs/advanced/templates.md`. PR [#12726](https://github.com/fastapi/fastapi/pull/12726) by [@Heumhub](https://github.com/Heumhub). From c355ae14161b1a0233f0b5ee06742be116592703 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 10 Dec 2024 10:54:21 +0000 Subject: [PATCH 541/932] =?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 [skip ci] --- 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 eb8413124..55ecb968b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/simple-oauth2.md`. PR [#10599](https://github.com/fastapi/fastapi/pull/10599) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/get-current-user.md`. PR [#10594](https://github.com/fastapi/fastapi/pull/10594) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/features.md`. PR [#12441](https://github.com/fastapi/fastapi/pull/12441) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/virtual-environments.md`. PR [#12791](https://github.com/fastapi/fastapi/pull/12791) by [@Vincy1230](https://github.com/Vincy1230). From d8e7edba802002d96d11816b72714ae7de5d2925 Mon Sep 17 00:00:00 2001 From: Aleksandr Andrukhov Date: Tue, 10 Dec 2024 13:56:08 +0300 Subject: [PATCH 542/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/tutorial/security/oauth2-jwt.md`=20(#?= =?UTF-8?q?10601)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/tutorial/security/oauth2-jwt.md | 261 +++++++++++++++++++ 1 file changed, 261 insertions(+) create mode 100644 docs/ru/docs/tutorial/security/oauth2-jwt.md diff --git a/docs/ru/docs/tutorial/security/oauth2-jwt.md b/docs/ru/docs/tutorial/security/oauth2-jwt.md new file mode 100644 index 000000000..1195fad21 --- /dev/null +++ b/docs/ru/docs/tutorial/security/oauth2-jwt.md @@ -0,0 +1,261 @@ +# OAuth2 с паролем (и хешированием), Bearer с JWT-токенами + +Теперь, когда у нас определен процесс обеспечения безопасности, давайте сделаем приложение действительно безопасным, используя токены JWT и безопасное хеширование паролей. + +Этот код можно реально использовать в своем приложении, сохранять хэши паролей в базе данных и т.д. + +Мы продолжим разбираться, начиная с того места, на котором остановились в предыдущей главе. + +## Про JWT + +JWT означает "JSON Web Tokens". + +Это стандарт для кодирования JSON-объекта в виде длинной строки без пробелов. Выглядит это следующим образом: + +``` +eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c +``` + +Он не зашифрован, поэтому любой человек может восстановить информацию из его содержимого. + +Но он подписан. Следовательно, когда вы получаете токен, который вы эмитировали (выдавали), вы можете убедиться, что это именно вы его эмитировали. + +Таким образом, можно создать токен со сроком действия, скажем, 1 неделя. А когда пользователь вернется на следующий день с тем же токеном, вы будете знать, что он все еще авторизирован в вашей системе. + +Через неделю срок действия токена истечет, пользователь не будет авторизован и ему придется заново входить в систему, чтобы получить новый токен. А если пользователь (или третье лицо) попытается модифицировать токен, чтобы изменить срок действия, вы сможете это обнаружить, поскольку подписи не будут совпадать. + +Если вы хотите поиграть с JWT-токенами и посмотреть, как они работают, посмотрите https://jwt.io. + +## Установка `PyJWT` + +Нам необходимо установить `pyjwt` для генерации и проверки JWT-токенов на языке Python. + +Убедитесь, что вы создали [виртуальное окружение](../../virtual-environments.md){.internal-link target=_blank}, активируйте его, а затем установите `pyjwt`: + +
+ +```console +$ pip install pyjwt + +---> 100% +``` + +
+ +/// info | Дополнительная информация +Если вы планируете использовать алгоритмы цифровой подписи, такие как RSA или ECDSA, вам следует установить зависимость библиотеки криптографии `pyjwt[crypto]`. + +Подробнее об этом можно прочитать в документации по установке PyJWT. +/// + +## Хеширование паролей + +"Хеширование" означает преобразование некоторого содержимого (в данном случае пароля) в последовательность байтов (просто строку), которая выглядит как тарабарщина. + +Каждый раз, когда вы передаете точно такое же содержимое (точно такой же пароль), вы получаете точно такую же тарабарщину. + +Но преобразовать тарабарщину обратно в пароль невозможно. + +### Для чего нужно хеширование паролей + +Если ваша база данных будет украдена, то вор не получит пароли пользователей в открытом виде, а только их хэши. + +Таким образом, вор не сможет использовать этот пароль в другой системе (поскольку многие пользователи везде используют один и тот же пароль, это было бы опасно). + +## Установка `passlib` + +PassLib - это отличный пакет Python для работы с хэшами паролей. + +Он поддерживает множество безопасных алгоритмов хеширования и утилит для работы с ними. + +Рекомендуемый алгоритм - "Bcrypt". + +Убедитесь, что вы создали и активировали виртуальное окружение, и затем установите PassLib вместе с Bcrypt: + +
+ +```console +$ pip install "passlib[bcrypt]" + +---> 100% +``` + +
+ +/// tip | Подсказка +С помощью `passlib` можно даже настроить его на чтение паролей, созданных **Django**, плагином безопасности **Flask** или многими другими библиотеками. + +Таким образом, вы сможете, например, совместно использовать одни и те же данные из приложения Django в базе данных с приложением FastAPI. Или постепенно мигрировать Django-приложение, используя ту же базу данных. + +При этом пользователи смогут одновременно входить в систему как из приложения Django, так и из приложения **FastAPI**. +/// + +## Хеширование и проверка паролей + +Импортируйте необходимые инструменты из `passlib`. + +Создайте "контекст" PassLib. Именно он будет использоваться для хэширования и проверки паролей. + +/// tip | Подсказка +Контекст PassLib также имеет функциональность для использования различных алгоритмов хеширования, в том числе и устаревших, только для возможности их проверки и т.д. + +Например, вы можете использовать его для чтения и проверки паролей, сгенерированных другой системой (например, Django), но хэшировать все новые пароли другим алгоритмом, например Bcrypt. + +И при этом быть совместимым со всеми этими системами. +/// + +Создайте служебную функцию для хэширования пароля, поступающего от пользователя. + +А затем создайте другую - для проверки соответствия полученного пароля и хранимого хэша. + +И еще одну - для аутентификации и возврата пользователя. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *} + +/// note | Технические детали +Если проверить новую (фальшивую) базу данных `fake_users_db`, то можно увидеть, как теперь выглядит хэшированный пароль: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. +/// + +## Работа с JWT токенами + +Импортируйте установленные модули. + +Создайте случайный секретный ключ, который будет использоваться для подписи JWT-токенов. + +Для генерации безопасного случайного секретного ключа используйте команду: + +
+ +```console +$ openssl rand -hex 32 + +09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7 +``` + +
+ +И скопируйте полученный результат в переменную `SECRET_KEY` (не используйте тот, что в примере). + +Создайте переменную `ALGORITHM` с алгоритмом, используемым для подписи JWT-токена, и установите для нее значение `"HS256"`. + +Создайте переменную для срока действия токена. + +Определите Pydantic Model, которая будет использоваться для формирования ответа на запрос на получение токена. + +Создайте служебную функцию для генерации нового токена доступа. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *} + +## Обновление зависимостей + +Обновите `get_current_user` для получения того же токена, что и раньше, но на этот раз с использованием JWT-токенов. + +Декодируйте полученный токен, проверьте его и верните текущего пользователя. + +Если токен недействителен, то сразу же верните HTTP-ошибку. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[90:107] *} + +## Обновление *операции пути* `/token` + +Создайте `timedelta` со временем истечения срока действия токена. + +Создайте реальный токен доступа JWT и верните его + +{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *} + +### Технические подробности о JWT ключе `sub` + +В спецификации JWT говорится, что существует ключ `sub`, содержащий субъект токена. + +Его использование необязательно, но это именно то место, куда вы должны поместить идентификатор пользователя, и поэтому мы здесь его и используем. + +JWT может использоваться и для других целей, помимо идентификации пользователя и предоставления ему возможности выполнять операции непосредственно в вашем API. + +Например, вы могли бы определить "автомобиль" или "запись в блоге". + +Затем вы могли бы добавить права доступа к этой сущности, например "управлять" (для автомобиля) или "редактировать" (для блога). + +Затем вы могли бы передать этот JWT-токен пользователю (или боту), и они использовали бы его для выполнения определенных действий (управление автомобилем или редактирование запись в блоге), даже не имея учетной записи, просто используя JWT-токен, сгенерированный вашим API. + +Используя эти идеи, JWT можно применять для гораздо более сложных сценариев. + +В отдельных случаях несколько сущностей могут иметь один и тот же идентификатор, скажем, `foo` (пользователь `foo`, автомобиль `foo` и запись в блоге `foo`). + +Поэтому, чтобы избежать коллизий идентификаторов, при создании JWT-токена для пользователя можно добавить префикс `username` к значению ключа `sub`. Таким образом, в данном примере значение `sub` было бы `username:johndoe`. + +Важно помнить, что ключ `sub` должен иметь уникальный идентификатор для всего приложения и представлять собой строку. + +## Проверка в действии + +Запустите сервер и перейдите к документации: http://127.0.0.1:8000/docs. + +Вы увидите пользовательский интерфейс вида: + + + +Пройдите авторизацию так же, как делали раньше. + +Используя учетные данные пользователя: + +Username: `johndoe` +Password: `secret` + +/// check | Заметка +Обратите внимание, что нигде в коде не используется открытый текст пароля "`secret`", мы используем только его хэшированную версию. +/// + + + +Вызвав эндпоинт `/users/me/`, вы получите ответ в виде: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false +} +``` + + + +Если открыть инструменты разработчика, то можно увидеть, что передаваемые данные включают только токен, пароль передается только в первом запросе для аутентификации пользователя и получения токена доступа, но не в последующих: + + + +/// note | Техническая информация +Обратите внимание на заголовок `Authorization`, значение которого начинается с `Bearer`. +/// + +## Продвинутое использование `scopes` + +В OAuth2 существует понятие "диапазоны" ("`scopes`"). + +С их помощью можно добавить определенный набор разрешений к JWT-токену. + +Затем вы можете передать этот токен непосредственно пользователю или третьей стороне для взаимодействия с вашим API с определенным набором ограничений. + +О том, как их использовать и как они интегрированы в **FastAPI**, читайте далее в **Руководстве пользователя**. + +## Резюме + +С учетом того, что вы видели до сих пор, вы можете создать безопасное приложение **FastAPI**, используя такие стандарты, как OAuth2 и JWT. + +Практически в любом фреймворке работа с безопасностью довольно быстро превращается в сложную тему. + +Многие пакеты, сильно упрощающие эту задачу, вынуждены идти на многочисленные компромиссы с моделью данных, с базой данных и с доступным функционалом. Некоторые из этих пакетов, которые пытаются уж слишком все упростить, имеют даже "дыры" в системе безопасности. + +--- + +**FastAPI** не делает уступок ни одной базе данных, модели данных или инструментарию. + +Он предоставляет вам полную свободу действий, позволяя выбирать то, что лучше всего подходит для вашего проекта. + +Вы можете напрямую использовать многие хорошо поддерживаемые и широко распространенные пакеты, такие как `passlib` и `PyJWT`, поскольку **FastAPI** не требует сложных механизмов для интеграции внешних пакетов. + +Напротив, он предоставляет инструменты, позволяющие максимально упростить этот процесс без ущерба для гибкости, надежности и безопасности. + +При этом вы можете использовать и реализовывать безопасные стандартные протоколы, такие как OAuth2, относительно простым способом. + +В **Руководстве пользователя** вы можете узнать больше о том, как использовать "диапазоны" ("`scopes`") OAuth2 для создания более точно настроенной системы разрешений в соответствии с теми же стандартами. OAuth2 с диапазонами - это механизм, используемый многими крупными провайдерами сервиса аутентификации, такими как Facebook, Google, GitHub, Microsoft, Twitter и др., для авторизации сторонних приложений на взаимодействие с их API от имени их пользователей. From 52cdbebbad592caa86d45b7f2580f89465e06639 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 10 Dec 2024 10:58:06 +0000 Subject: [PATCH 543/932] =?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 [skip ci] --- 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 55ecb968b..1c6c575bc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/oauth2-jwt.md`. PR [#10601](https://github.com/fastapi/fastapi/pull/10601) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/simple-oauth2.md`. PR [#10599](https://github.com/fastapi/fastapi/pull/10599) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/get-current-user.md`. PR [#10594](https://github.com/fastapi/fastapi/pull/10594) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/features.md`. PR [#12441](https://github.com/fastapi/fastapi/pull/12441) by [@codingjenny](https://github.com/codingjenny). From f7ba75e3f7509d0b44e0c9ecc3fba7f532a27798 Mon Sep 17 00:00:00 2001 From: viva-douner Date: Tue, 10 Dec 2024 20:03:16 +0900 Subject: [PATCH 544/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/advanced/async-test.md`=20(#12918)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/advanced/async-tests.md | 108 +++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 docs/ko/docs/advanced/async-tests.md diff --git a/docs/ko/docs/advanced/async-tests.md b/docs/ko/docs/advanced/async-tests.md new file mode 100644 index 000000000..37dfe2979 --- /dev/null +++ b/docs/ko/docs/advanced/async-tests.md @@ -0,0 +1,108 @@ +# 비동기 테스트 코드 작성 + +이전 장에서 `TestClient` 를 이용해 **FastAPI** 어플리케이션 테스트를 작성하는 법을 배우셨을텐데요. +지금까지는 `async` 키워드 사용없이 동기 함수의 테스트 코드를 작성하는 법만 익혔습니다. + +하지만 비동기 함수를 사용하여 테스트 코드를 작성하는 것은 매우 유용할 수 있습니다. +예를 들면 데이터베이스에 비동기로 쿼리하는 경우를 생각해봅시다. +FastAPI 애플리케이션에 요청을 보내고, 비동기 데이터베이스 라이브러리를 사용하여 백엔드가 데이터베이스에 올바르게 데이터를 기록했는지 확인하고 싶을 때가 있을 겁니다. + +이런 경우의 테스트 코드를 어떻게 비동기로 작성하는지 알아봅시다. + +## pytest.mark.anyio + +앞에서 작성한 테스트 함수에서 비동기 함수를 호출하고 싶다면, 테스트 코드도 비동기 함수여야합니다. +AnyIO는 특정 테스트 함수를 비동기 함수로 호출 할 수 있는 깔끔한 플러그인을 제공합니다. + + +## HTTPX + +**FastAPI** 애플리케이션이 `async def` 대신 `def` 키워드로 선언된 함수를 사용하더라도, 내부적으로는 여전히 `비동기` 애플리케이션입니다. + +`TestClient`는 pytest 표준을 사용하여 비동기 FastAPI 애플리케이션을 일반적인 `def` 테스트 함수 내에서 호출할 수 있도록 내부에서 마술을 부립니다. 하지만 이 마술은 비동기 함수 내부에서 사용할 때는 더 이상 작동하지 않습니다. 테스트를 비동기로 실행하면, 더 이상 테스트 함수 내부에서 `TestClient`를 사용할 수 없습니다. + +`TestClient`는 HTTPX를 기반으로 하고 있으며, 다행히 이를 직접 사용하여 API를 테스트할 수 있습니다. + +## 예시 + +간단한 예시를 위해 [더 큰 어플리케이션 만들기](../ko/tutorial/bigger-applications.md){.internal-link target=_blank} 와 [테스트](../ko/tutorial/testing.md){.internal-link target=_blank}:에서 다룬 파일 구조와 비슷한 형태를 확인해봅시다: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + + `main.py`는 아래와 같아야 합니다: + +{* ../../docs_src/async_tests/main.py *} + +`test_main.py` 파일은 `main.py`에 대한 테스트가 있을 텐데, 다음과 같을 수 있습니다: + +{* ../../docs_src/async_tests/test_main.py *} + +## 실행하기 + +아래의 명령어로 테스트 코드를 실행합니다: + +
+ +```console +$ pytest + +---> 100% +``` + +
+ +## 자세히 보기 + +`@pytest.mark.anyio` 마커는 pytest에게 이 테스트 함수가 비동기로 호출되어야 함을 알려줍니다: + +{* ../../docs_src/async_tests/test_main.py hl[7] *} + +/// tip | 팁 + +테스트 함수가 이제 `TestClient`를 사용할 때처럼 단순히 `def`가 아니라 `async def`로 작성된 점에 주목해주세요. + +/// + +그 다음에 `AsyncClient` 로 앱을 만들고 비동기 요청을 `await` 키워드로 보낼 수 있습니다: + +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} + +위의 코드는: + +```Python +response = client.get('/') +``` + +`TestClient` 에 요청을 보내던 것과 동일합니다. + +/// tip | 팁 + +새로운 `AsyncClient`를 사용할 때 async/await를 사용하고 있다는 점에 주목하세요. 이 요청은 비동기적으로 처리됩니다. + +/// + +/// warning | 경고 + +만약의 어플리케이션이 Lifespan 이벤트에 의존성을 갖고 있다면 `AsyncClient` 가 이러한 이벤트를 실행시키지 않습니다. +`AsyncClient` 가 테스트를 실행시켰다는 것을 확인하기 위해 +`LifespanManager` from florimondmanca/asgi-lifespan.확인해주세요. + + +/// + +## 그 외의 비동기 함수 호출 + +테스트 함수가 이제 비동기 함수이므로, FastAPI 애플리케이션에 요청을 보내는 것 외에도 다른 `async` 함수를 호출하고 `await` 키워드를 사용 할 수 있습니다. + +/// tip | 팁 + +테스트에 비동기 함수 호출을 통합할 때 (예: MongoDB의 MotorClient를 사용할 때) `RuntimeError: Task attached to a different loop` 오류가 발생한다면, 이벤트 루프가 필요한 객체는 반드시 비동기 함수 내에서만 인스턴스화해야 한다는 점을 주의하세요! +예를 들어 `@app.on_event("startup")` 콜백 내에서 인스턴스화하는 것이 좋습니다. + +/// From c9470e7aec40f74bab3de8691a59cde514dbcc9f Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 10 Dec 2024 11:03:42 +0000 Subject: [PATCH 545/932] =?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 [skip ci] --- 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 1c6c575bc..bef1356d7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/advanced/async-test.md`. PR [#12918](https://github.com/fastapi/fastapi/pull/12918) by [@icehongssii](https://github.com/icehongssii). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/oauth2-jwt.md`. PR [#10601](https://github.com/fastapi/fastapi/pull/10601) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/simple-oauth2.md`. PR [#10599](https://github.com/fastapi/fastapi/pull/10599) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/get-current-user.md`. PR [#10594](https://github.com/fastapi/fastapi/pull/10594) by [@AlertRED](https://github.com/AlertRED). From 230f2077b9d7acbc48c1a7afb600e50461145926 Mon Sep 17 00:00:00 2001 From: timothy <53824764+jts8257@users.noreply.github.com> Date: Tue, 10 Dec 2024 20:24:48 +0900 Subject: [PATCH 546/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/tutorial/testing.md`=20(#12968)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/tutorial/testing.md | 243 +++++++++++++++++++++++++++++++ 1 file changed, 243 insertions(+) create mode 100644 docs/ko/docs/tutorial/testing.md diff --git a/docs/ko/docs/tutorial/testing.md b/docs/ko/docs/tutorial/testing.md new file mode 100644 index 000000000..a483cbf00 --- /dev/null +++ b/docs/ko/docs/tutorial/testing.md @@ -0,0 +1,243 @@ +# 테스팅 + +Starlette 덕분에 **FastAPI** 를 테스트하는 일은 쉽고 즐거운 일이 되었습니다. + +Starlette는 HTTPX를 기반으로 하며, 이는 Requests를 기반으로 설계되었기 때문에 매우 친숙하고 직관적입니다. + +이를 사용하면 FastAPI에서 pytest를 직접 사용할 수 있습니다. + +## `TestClient` 사용하기 + +/// info | 정보 + +`TestClient` 사용하려면, 우선 `httpx` 를 설치해야 합니다. + +[virtual environment](../virtual-environments.md){.internal-link target=_blank} 를 만들고, 활성화 시킨 뒤에 설치하세요. 예시: + +```console +$ pip install httpx +``` + +/// + +`TestClient` 를 임포트하세요. + +**FastAPI** 어플리케이션을 전달하여 `TestClient` 를 만드세요. + +이름이 `test_` 로 시작하는 함수를 만드세요(`pytest` 의 표준적인 관례입니다). + +`httpx` 를 사용하는 것과 같은 방식으로 `TestClient` 객체를 사용하세요. + +표준적인 파이썬 문법을 이용하여 확인이 필요한 곳에 간단한 `assert` 문장을 작성하세요(역시 표준적인 `pytest` 관례입니다). + +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} + +/// tip | 팁 + +테스트를 위한 함수는 `async def` 가 아니라 `def` 로 작성됨에 주의하세요. + +그리고 클라이언트에 대한 호출도 `await` 를 사용하지 않는 일반 호출입니다. + +이렇게 하여 복잡한 과정 없이 `pytest` 를 직접적으로 사용할 수 있습니다. + +/// + +/// note | 기술 세부사항 + +`from starlette.testclient import TestClient` 역시 사용할 수 있습니다. + +**FastAPI** 는 개발자의 편의를 위해 `starlette.testclient` 를 `fastapi.testclient` 로도 제공할 뿐입니다. 이는 단지 `Starlette` 에서 직접 가져오는지의 차이일 뿐입니다. + +/// + +/// tip | 팁 + +FastAPI 애플리케이션에 요청을 보내는 것 외에도 테스트에서 `async` 함수를 호출하고 싶다면 (예: 비동기 데이터베이스 함수), 심화 튜토리얼의 [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} 를 참조하세요. + +/// + +## 테스트 분리하기 + +실제 애플리케이션에서는 테스트를 별도의 파일로 나누는 경우가 많습니다. + + +그리고 **FastAPI** 애플리케이션도 여러 파일이나 모듈 등으로 구성될 수 있습니다. + +### **FastAPI** app 파일 + +[Bigger Applications](bigger-applications.md){.internal-link target=_blank} 에 묘사된 파일 구조를 가지고 있는 것으로 가정해봅시다. + +``` +. +├── app +│   ├── __init__.py +│   └── main.py +``` + +`main.py` 파일 안에 **FastAPI** app 을 만들었습니다: + +{* ../../docs_src/app_testing/main.py *} + +### 테스트 파일 + +테스트를 위해 `test_main.py` 라는 파일을 생성할 수 있습니다. 이 파일은 동일한 Python 패키지(즉, `__init__.py` 파일이 있는 동일한 디렉터리)에 위치할 수 있습니다. + +``` hl_lines="5" +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +파일들이 동일한 패키지에 위치해 있으므로, 상대 참조를 사용하여 `main` 에서 `app` 객체를 임포트 해올 수 있습니다. + +{* ../../docs_src/app_testing/test_main.py hl[3] *} + + +...그리고 이전에 작성했던 것과 같은 테스트 코드를 작성할 수 있습니다. + +## 테스트: 확장된 예시 + +이제 위의 예시를 확장하고 더 많은 세부 사항을 추가하여 다양한 부분을 어떻게 테스트하는지 살펴보겠습니다. + +### 확장된 FastAPI 애플리케이션 파일 + +이전과 같은 파일 구조를 계속 사용해 보겠습니다. + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +이제 **FastAPI** 앱이 있는 `main.py` 파일에 몇 가지 다른 **경로 작업** 이 추가된 경우를 생각해봅시다. + +단일 오류를 반환할 수 있는 `GET` 작업이 있습니다. + +여러 다른 오류를 반환할 수 있는 `POST` 작업이 있습니다. + +두 *경로 작업* 모두 `X-Token` 헤더를 요구합니다. + +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/app_testing/app_b_an/main.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | 팁 + +될 수 있으면 `Annotated` 버전 사용을 권장합나다. + +/// + +```Python +{!> ../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | 팁 + +될 수 있으면 `Annotated` 버전 사용을 권장합나다. + +/// + +```Python +{!> ../../docs_src/app_testing/app_b/main.py!} +``` + +//// + +### 확장된 테스트 파일 + +이제는 `test_main.py` 를 확장된 테스트들로 수정할 수 있습니다: + +{* ../../docs_src/app_testing/app_b/test_main.py *} + + +클라이언트가 요청에 정보를 전달해야 하는데 방법을 모르겠다면, `httpx`에서 해당 작업을 수행하는 방법을 검색(Google)하거나, `requests`에서의 방법을 검색해보세요. HTTPX는 Requests의 디자인을 기반으로 설계되었습니다. + +그 후, 테스트에서도 동일하게 적용하면 됩니다. + +예시: + +* *경로* 혹은 *쿼리* 매개변수를 전달하려면, URL 자체에 추가한다. +* JSON 본문을 전달하려면, 파이썬 객체 (예를들면 `dict`) 를 `json` 파라미터로 전달한다. +* JSON 대신 *폼 데이터* 를 보내야한다면, `data` 파라미터를 대신 전달한다. +* *헤더* 를 전달하려면, `headers` 파라미터에 `dict` 를 전달한다. +* *쿠키* 를 전달하려면, `cookies` 파라미터에 `dict` 를 전달한다. + +백엔드로 데이터를 어떻게 보내는지 정보를 더 얻으려면 (`httpx` 혹은 `TestClient` 를 이용해서) HTTPX documentation 를 확인하세요. + +/// info | 정보 + +`TestClient` 는 Pydantic 모델이 아니라 JSON 으로 변환될 수 있는 데이터를 받습니다. + +만약 테스트중 Pydantic 모델을 어플리케이션으로에 보내고 싶다면, [JSON 호환 가능 인코더](encoder.md){.internal-link target=_blank} 에 설명되어 있는 `jsonable_encoder` 를 사용할 수 있습니다. + +/// + +## 실행하기 + +테스트 코드를 작성하고, `pytest` 를 설치해야합니다. + +[virtual environment](../virtual-environments.md){.internal-link target=_blank} 를 만들고, 활성화 시킨 뒤에 설치하세요. 예시: + +
+ +```console +$ pip install pytest + +---> 100% +``` + +
+ +`pytest` 파일과 테스트를 자동으로 감지하고 실행한 다음, 결과를 보고할 것입니다. + +테스트를 다음 명령어로 실행하세요. + +
+ +```console +$ pytest + +================ test session starts ================ +platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 +rootdir: /home/user/code/superawesome-cli/app +plugins: forked-1.1.3, xdist-1.31.0, cov-2.8.1 +collected 6 items + +---> 100% + +test_main.py ...... [100%] + +================= 1 passed in 0.03s ================= +``` + +
From bacf9e5af6f31bd56d8775a15a7ec375b95836d8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 10 Dec 2024 11:25:14 +0000 Subject: [PATCH 547/932] =?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 [skip ci] --- 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 bef1356d7..219c01f84 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/testing.md`. PR [#12968](https://github.com/fastapi/fastapi/pull/12968) by [@jts8257](https://github.com/jts8257). * 🌐 Add Korean translation for `docs/ko/docs/advanced/async-test.md`. PR [#12918](https://github.com/fastapi/fastapi/pull/12918) by [@icehongssii](https://github.com/icehongssii). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/oauth2-jwt.md`. PR [#10601](https://github.com/fastapi/fastapi/pull/10601) by [@AlertRED](https://github.com/AlertRED). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/simple-oauth2.md`. PR [#10599](https://github.com/fastapi/fastapi/pull/10599) by [@AlertRED](https://github.com/AlertRED). From 5cc1b065ba8acf4869da9e7acfcad7bab5af8dec Mon Sep 17 00:00:00 2001 From: alv2017 Date: Tue, 10 Dec 2024 13:34:19 +0200 Subject: [PATCH 548/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/virtual-environments.md`=20(#13026)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/virtual-environments.md | 839 +++++++++++++++++++++++++++ 1 file changed, 839 insertions(+) create mode 100644 docs/ru/docs/virtual-environments.md diff --git a/docs/ru/docs/virtual-environments.md b/docs/ru/docs/virtual-environments.md new file mode 100644 index 000000000..777adaf22 --- /dev/null +++ b/docs/ru/docs/virtual-environments.md @@ -0,0 +1,839 @@ +# Виртуальная среда + +При работе с проектами в Python рекомендуется использовать **виртуальную среду разработки** (или какой-нибудь другой подобный механизм). Это нужно для того, чтобы изолировать устанавливаемые пакеты для каждого отдельного проекта. + +/// info | Дополнительная информация + +Если вы уже знакомы с виртуальными средами разработки, знаете как их создавать и использовать, то вы можете свободно пропустить данный раздел. 🤓 + +/// + +/// tip | Подсказка + +**Виртуальная среда** и **переменная окружения** это две разные вещи. + +**Переменная окружения** это системная переменная, которую могут использовать программы. + +**Виртуальная среда** это папка, содержащая файлы. + +/// + +/// info | Дополнительная информация + +В этом разделе мы научим вас пользоваться виртуальными средами разработки и расскажем, как они работают. + +Если же вы готовы воспользоваться инструментом, **который умеет управлять всем, что касается Python-проектов**, +(включая установку Python), то попробуйте uv. + +/// + +## Создание проекта + +В первую очередь, создайте директорию для вашего проекта. + +Я обычно создаю папку под названием `code` внутри моего домашнего каталога `/home/user`. + +Затем внутри данной папки я создаю отдельную директорию под каждый свой проект. + +
+ +```console +// Перейдите в домашний каталог +$ cd +// Создайте отдельную папку под все будущие программные проекты (code) +$ mkdir code +// Войдите в директорию code +$ cd code +// Создайте директрорию под данный проект (awesome-project) +$ mkdir awesome-project +// Перейдите в созданную директорию проекта +$ cd awesome-project +``` + +
+ +## Создание виртуальной среды разработки + +Начиная работу с Python-проектом, сразу же создавайте виртуальную среду разработки +**внутри вашего проекта**. + +/// tip | Подсказка + +Виртуальная среда разработки создается один раз, и в дальнейшем, работая с проектом, этого больше делать не придется. + +/// + +//// tab | `venv` + +Для создания виртуальной среды вы можете воспользоваться модулем `venv`, который является частью встроенной библиотеки Python. + +
+ +```console +$ python -m venv .venv +``` + +
+ +/// details | Что делает эта команда? + +* `python`: использовать программу под именем `python` +* `-m`: вызывать модуль как скрипт, в следующей инструкции мы скажем какой именно модуль вызвать +* `venv`: использовать модуль под названием `venv`, который обычно устанавливается вместе с Python +* `.venv`: создать виртуальную среду разработки в новой директории `.venv` + +/// + +//// + +//// tab | `uv` + +Если вы установили `uv`, то вы можете им воспользоваться для создания виртуальной среды разработки. + +
+ +```console +$ uv venv +``` + +
+ +/// tip | Подсказка + +По умолчанию `uv` создаст виртуальную среду разработки в папке под названием `.venv`. + +Но вы можете это изменить, передав дополнительный аргумент с именем директории. + +/// + +//// + +Данная команда создаст новую виртуальную среду разработки в папке `.venv`. + +/// details | `.venv` или другое имя? + +Вы можете поместить виртуальную среду разработки в папку с другим именем, но традиционным (конвенциональным) названием является `.venv` . + +/// + +## Активация виртуальной среды разработки + +Активируйте виртуальную среду разработки, и тогда любая запускаемая Python-команда или устанавливаемый пакет будут ее использовать. + +/// tip | Подсказка + +При работе над проектом делайте это **каждый раз** при запуске **новой сессии в терминале**. + +/// + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +Или при использовании Bash для Windows (напр. Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +## Проверка активации виртуальной среды + +Проверьте, активна ли виртуальная среда (удостоверимся, что предыдущая команда сработала). + +/// tip | Подсказка + +Убедитесь в том, что все работает так, как нужно и вы используете именно ту виртуальную среду разработки, которую нужно. Делать это необязательно, но желательно. + +/// + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +Если данная команда показывает, что исполняемый файл `python` (`.venv\bin\python`), находится внутри виртуальной среды вашего проекта (у нас это `awesome-project`), значит все отработало как нужно. 🎉 + +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +Если данная команда показывает, что исполняемый файл `python` (`.venv\Scripts\python`), находится внутри виртуальной среды вашего проекта (у нас это `awesome-project`), значит все отработало как нужно. 🎉 + +//// + +## Обновление `pip` + +/// tip | Подсказка + +Если вы используете `uv`, то вы должны будете его использовать для установки пакетов вместо `pip`, поэтому обновлять `pip` вам ненужно. 😎 + +/// + +Если для установки пакетов вы используете `pip` (он устанавливается по умолчанию вместе с Python), то обновите `pip` до последней версии. + +Большинство экзотических ошибок, возникающих при установке пакетов, устраняется предварительным обновлением `pip`. + +/// tip | Подсказка + +Обычно это делается только один раз, сразу после создания виртуальной среды разработки. + +/// + +Убедитесь в том, что виртуальная среда активирована (с помощью вышеуказанной команды) и запустите следующую команду: + +
+ +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
+ +## Добавление `.gitignore` + +Если вы используете **Git** (а вы должны его использовать), то добавьте файл `.gitignore` и исключите из Git всё, что находится в папке `.venv`. + +/// tip | Подсказка + +Если для создания виртуальной среды вы используете `uv`, то для вас все уже сделано и вы можете пропустить этот шаг. 😎 + +/// + +/// tip | Подсказка + +Это делается один раз, сразу после создания виртуальной среды разработки. + +/// + +
+ +```console +$ echo "*" > .venv/.gitignore +``` + +
+ +/// details | Что делает эта команда? + +* `echo "*"`: напечатать `*` в консоли (следующий шаг это слегка изменит) +* `>`: все что находится слева от `>` не печатать в консоль, но записать в файл находящийся справа от `>` +* `.gitignore`: имя файла, в который нужно записать текст. + +`*` в Git означает "всё". Т.е. будет проигнорировано всё, что содержится в папке `.venv`. + +Данная команда создаст файл `.gitignore` следующего содержания: + +```gitignore +* +``` + +/// + +## Установка пакетов + +После установки виртуальной среды, вы можете устанавливать в нее пакеты. + +/// tip | Подсказка + +Сделайте это **один раз**, при установке или обновлении пакетов, нужных вашему проекту. + +Если вам понадобится обновить версию пакета или добавить новый пакет, то вы должны будете **сделать это снова**. + +/// + +### Установка пакетов напрямую + +Если вы торопитесь и не хотите объявлять зависимости проекта в отдельном файле, то вы можете установить их напрямую. + +/// tip | Подсказка + +Объявление пакетов, которые использует ваш проект, и их версий в отдельном файле (например, в `requirements.txt` или в `pyproject.toml`) - это отличная идея. + +/// + +//// tab | `pip` + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +Если вы используете `uv`: + +
+ +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
+ +//// + +### Установка из `requirements.txt` + +Если у вас есть `requirements.txt`, то вы можете использовать его для установки пакетов. + +//// tab | `pip` + +
+ +```console +$ pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +Если вы используете `uv`: + +
+ +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +/// details | `requirements.txt` + +`requirements.txt` с парочкой пакетов внутри выглядит приблизительно так: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## Запуск программы + +После активации виртуальной среды разработки вы можете запустить свою программу и она будет использовать версию Python и пакеты, установленные в виртуальной среде. + +
+ +```console +$ python main.py + +Hello World +``` + +
+ +## Настройка редактора + +Вероятно, вы захотите воспользоваться редактором. Убедитесь, что вы настроили его на использование той самой виртуальной среды, которую вы создали. (Скорее всего, она автоматически будет обнаружена). Это позволит вам использовать авто-завершение и выделение ошибок в редакторе. + +Например: + +* VS Code +* PyCharm + +/// tip | Подсказка + +Обычно это делается один раз, при создании виртуальной среды разработки. + +/// + +## Деактивация виртуальной среды разработки + +По окончании работы над проектом вы можете деактивировать виртуальную среду. + +
+ +```console +$ deactivate +``` + +
+ +Таким образом, при запуске `python`, будет использована версия `python` установленная глобально, а не из этой виртуальной среды вместе с установленными в ней пакетами. + +## Все готово к работе + +Теперь вы готовы к тому, чтобы начать работу над своим проектом. + + + +/// tip | Подсказка + +Хотите разобраться со всем, что написано выше? + +Продолжайте читать. 👇🤓 + +/// + +## Зачем использовать виртуальную среду? + +Для работы с FastAPI вам потребуется установить Python. + +После этого вам нужно будет **установить** FastAPI и другие **пакеты**, которые вы собираетесь использовать. + +Для установки пакетов обычно используют `pip`, который устанавливается вместе с Python (или же используют альтернативные решения). + +Тем не менее, если вы просто используете `pip` напрямую, то пакеты будут установлены в **глобальное Python-окружение** (глобально установленный Python). + +### Проблема + +Так в чем же проблема с установкой пакетов в глобальную среду Python? + +В какой-то момент вам, вероятно, придется писать множество разных программ, которые используют различные пакеты. 😱 + +Например, вы создаете проект `philosophers-stone`, который зависит от пакета под названием **`harry`, версии `1`**. Таким образом, вам нужно установить `harry`. + +```mermaid +flowchart LR + stone(philosophers-stone) -->|requires| harry-1[harry v1] +``` + +Затем, в какой-то момент, вы создаете другой проект под названием `prisoner-of-azkaban`, и этот проект тоже зависит от `harry`, но он уже использует **`harry` версии `3`**. + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3] +``` + +Проблема заключается в том, что при установке в глобальное окружение, а не в локальную виртуальную среду разработки, вам нужно будет выбирать, какую версию пакета `harry` устанавливать. + +Если вам нужен `philosophers-stone`, то вам нужно сначала установить `harry` версии `1`: + +
+ +```console +$ pip install "harry==1" +``` + +
+ +И тогда в вашем глобальном окружении Python будет установлен `harry` версии `1`: + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -->|requires| harry-1 + end +``` + +Но если позднее вы захотите запустить `prisoner-of-azkaban`, то вам нужно будет удалить `harry` версии 1, и установить `harry` версии `3` (при установке пакета версии `3` поверх пакета версии `1`, пакет версии `1` удаляется автоматически). + +
+ +```console +$ pip install "harry==3" +``` + +
+ +И тогда, в вашей глобальной среде окружения Python, будет установлен пакет `harry` версии `3`. + +И когда вы снова попытаетесь запустить `philosophers-stone`, то существует вероятность того, что он не будет работать, так как он использует `harry` версии `1`. + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --> |requires| harry-3 + end +``` + +/// tip | Подсказка + +В пакетах Python очень часто стараются изо всех сил избегать внесения критических изменений в новые версии, но лучше перестраховаться и планово устанавливать новые версии, а затем запускать тесты, чтобы проверить, все ли работает правильно. + +/// + +Теперь представьте, что это происходит со многими другими пакетами, которые используются в ваших проектах. С этим очень сложно справиться. И скорее всего, в конечном итоге вы будете запускать некоторые проекты с некоторыми несовместимыми зависимостями и не будете знать, почему что-то не работает. + +Кроме того, в зависимости от вашей операционной системы (напр. Linux, Windows, macOS), она может поставляться с уже установленным Python. Вероятно, что в этом случае в ней уже установлены системные пакеты определенных версий. Если вы устанавливаете пакеты глобально, то вы можете **поломать** программы, являющиеся частью ОС. + +## Куда устанавливаются пакеты? + +Когда вы устанавливаете Python, то на вашей машине создается некоторое количество директорий, содержащих некоторое количество файлов. + +Среди них есть каталоги, отвечающие за хранение всех устанавливаемых вами пакетов. + +Когда вы запустите команду: + +
+ +```console +// Не запускайте эту команду, это просто пример 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
+ +То будет скачан сжатый файл, содержащий код FastAPI, обычно скачивание происходит с PyPI. + +Также будут скачаны файлы, содержащие пакеты, которые использует FastAPI. + +Затем все файлы будут извлечены и помещены в директорию на вашем компьютере. + +По умолчанию эти файлы будут загружены и извлечены в один из каталогов установки Python, т.е. в глобальную среду. + +## Что такое виртуальная среда разработки? + +Решением проблемы размещения всех пакетов в глобальной среде будет использование отдельной виртуальной среды под каждый проект, над которым вы работаете. + +Виртуальная среда это обычная папка, очень похожая на глобальную, куда вы можете устанавливать пакеты для вашего проекта. + +Таким образом, каждый проект будет иметь свою отдельную виртуальную среду разработки (в директории `.venv`) вместе со своими пакетами. + +```mermaid +flowchart TB + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) --->|requires| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --->|requires| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## Что означает активация виртуальной среды? + +Когда вы активируете виртуальную среду разработки, например, так: + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +Или если вы воспользуетесь Bash под Windows (напр. Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + + +Эта команда создаст или изменит некоторые [переменные окружения](environment-variables.md){.internal-link target=_blank}, которые будут доступны для последующих команд. + +Одной из таких переменных является `PATH`. + +/// tip | Подсказка + +Вы можете узнать больше о переменной окружения `PATH` в разделе [Переменные окружения](environment-variables.md#path-environment-variable){.internal-link target=_blank}. + +/// + +При активации виртуальной среды путь `.venv/bin` (для Linux и macOS) или `.venv\Scripts` (для Windows) добавляется в переменную окружения `PATH`. + +Предположим, что до активации виртуальной среды переменная `PATH` выглядела так: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +Это означает, что система ищет программы в следующих каталогах: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +Это означает, что система ищет программы в: + +* `C:\Windows\System32` + +//// + +После активации виртуальной среды переменная окружение `PATH` будет выглядеть примерно так: + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Это означает, что система теперь будет искать программы в: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +прежде чем начать искать в других каталогах. + +Таким образом, когда вы введете в консоль `python`, система будет искать Python в + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +и будет использовать именно его. + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +Это означает, что система в первую очередь начнет искать программы в: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +прежде чем начать искать в других директориях. + +Таким образом, если вы введете в консоль команду `python`, то система найдет Python в: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +и использует его. + +//// + +Очень важной деталью является то, что путь к виртуальной среде будет помещен в самое начало переменной `PATH`. Система обнаружит данный путь к Python раньше, чем какой-либо другой. Таким образом, при запуске команды `python`, будет использован именно Python из виртуальной среды разработки, а не какой-нибудь другой (например, Python из глобальной среды) + +Активация виртуальной среды разработки также меняет и несколько других вещей, но данная функция является основной. + +## Проверка виртуальной среды + +Когда вы проверяете активна ли виртуальная среда разработки, например, так: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +//// + +Это означает, что будет использоваться `python` **из виртуальной среды разработки**. + +Вы используете `which` для Linux и macOS и `Get-Command` для Windows PowerShell. + +Эта команда работает следующим образом: она проверяет переменную окружения `PATH`, проходя по очереди каждый указанный путь в поисках программы под названием `python`. И когда она её находит, то возвращает путь к данной программе. + +Основной момент при вызове команды `python` состоит в том, какой именно "`python`" будет запущен. + +Таким образом, вы можете убедиться, что используете правильную виртуальную среду разработки. + +/// tip | Подсказка + +Легко активировать одну виртуальную среду, вызвать один Python и **перейти к следующему проекту**. + +И следующий проект не будет работать потому, что вы используете **неправильный Python** из виртуальной среды другого проекта. + +Так что, будет нелишним проверить, какой `python` вы используете. 🤓 + +/// + +## Зачем деактивируют виртуальную среду? + +Предположим, что вы работаете над проектом `philosophers-stone`, **активируете виртуальную среду разработки**, устанавливаете пакеты и работаете с данной средой. + +И позже вам понадобилось поработать с **другим проектом** `prisoner-of-azkaban`. + +Вы переходите к этому проекту: + +
+ +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
+ +Если вы не деактивировали виртуальное окружение проекта `philosophers-stone`, то при запуске `python` через консоль будет вызван Python из `philosophers-stone` + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// Error importing sirius, it's not installed 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
+ +Но если вы деактивируете виртуальную среду разработки и активируете новую среду для `prisoner-of-askaban`, то вы тогда запустите Python из виртуального окружения `prisoner-of-azkaban`. + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +// Вам не требуется находится в старой директории для деактивации среды разработки, вы можете это сделать откуда угодно, даже из каталога другого проекта, в который вы перешли. 😎 +$ deactivate + +// Активируйте виртуальную среду разработки в prisoner-of-azkaban/.venv 🚀 +$ source .venv/bin/activate + +// Тепреь, когда вы запустите python, он найдет пакет sirius, установленный в виртуальной среде ✨ +$ python main.py + +Я торжественно клянусь в этом! 🐺 +``` + +
+ +## Альтернативы + +Это простое руководство поможет вам начать работу и научит тому, как всё работает **изнутри**. + +Существует много альтернативных решений для работы с виртуальными средами разработки, с программными зависимостями, а также с проектами. + +Когда вы будете готовы использовать единый инструмент для управления проектом, программными зависимостями, виртуальными средами разработки и т.д., то я рекомендую вам попробовать uv. + +`uv` может очень многое. Он умеет: + +* **Устанавливать Python**, включая установку различных версий +* Управлять средой виртуального окружения вашего проекта +* Устанавливать **пакеты** +* Управлять пакетами и их версиями внутри вашего проекта +* Удостовериться, что вы используете **точный** набор пакетов и версий при установке, включая зависимости. Таким образом, вы можете быть уверенны, что проект, запускается в production, точно также, как и при разработке, этот механизм называется *locking* +* Многие другие вещи + +## Заключение + +Если вы прочитали и поняли всё это, то теперь вы знаете **гораздо больше** о виртуальных средах разработки, чем многие другие разработчики. 🤓 + +Скорее всего, знание этих деталей будет полезно вам в будущем. Когда вы будете отлаживать что-то, кажущееся сложным, вы будете знать, **как это работает под капотом**. 😎 From fed6fab8f9f2776b4dc847ac78d3ed6f256c63f6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 10 Dec 2024 11:35:32 +0000 Subject: [PATCH 549/932] =?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 [skip ci] --- 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 219c01f84..f51b9c373 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Russian translation for `docs/ru/docs/virtual-environments.md`. PR [#13026](https://github.com/fastapi/fastapi/pull/13026) by [@alv2017](https://github.com/alv2017). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/testing.md`. PR [#12968](https://github.com/fastapi/fastapi/pull/12968) by [@jts8257](https://github.com/jts8257). * 🌐 Add Korean translation for `docs/ko/docs/advanced/async-test.md`. PR [#12918](https://github.com/fastapi/fastapi/pull/12918) by [@icehongssii](https://github.com/icehongssii). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/security/oauth2-jwt.md`. PR [#10601](https://github.com/fastapi/fastapi/pull/10601) by [@AlertRED](https://github.com/AlertRED). From 6455f4bb0148d3cb45a25403b39959f90c98a2f3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Dec 2024 20:34:48 +0000 Subject: [PATCH 550/932] =?UTF-8?q?=E2=AC=86=20Bump=20pypa/gh-action-pypi-?= =?UTF-8?q?publish=20from=201.12.2=20to=201.12.3=20(#13055)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.12.2 to 1.12.3. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.12.2...v1.12.3) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index fc61c3fca..38df75928 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -35,7 +35,7 @@ jobs: TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.12.2 + uses: pypa/gh-action-pypi-publish@v1.12.3 - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} From 727ce82e9b024a8d1b2f98ecb2911ba5b50cc146 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 10 Dec 2024 20:35:10 +0000 Subject: [PATCH 551/932] =?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 [skip ci] --- 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 f51b9c373..599883d64 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -36,6 +36,7 @@ hide: ### Internal +* ⬆ Bump pypa/gh-action-pypi-publish from 1.12.2 to 1.12.3. PR [#13055](https://github.com/fastapi/fastapi/pull/13055) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump types-ujson from 5.7.0.1 to 5.10.0.20240515. PR [#13018](https://github.com/fastapi/fastapi/pull/13018) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump black from 24.3.0 to 24.10.0. PR [#13014](https://github.com/fastapi/fastapi/pull/13014) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump inline-snapshot from 0.13.0 to 0.14.0. PR [#13017](https://github.com/fastapi/fastapi/pull/13017) by [@dependabot[bot]](https://github.com/apps/dependabot). From 0d496337769bad0c442b3c8ac505418570876a46 Mon Sep 17 00:00:00 2001 From: Zhongheng Cheng Date: Tue, 10 Dec 2024 15:36:08 -0500 Subject: [PATCH 552/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/tutorial/request-form-models.md`=20(#?= =?UTF-8?q?13045)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/request-form-models.md | 78 ++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 docs/zh/docs/tutorial/request-form-models.md diff --git a/docs/zh/docs/tutorial/request-form-models.md b/docs/zh/docs/tutorial/request-form-models.md new file mode 100644 index 000000000..e639e4b9f --- /dev/null +++ b/docs/zh/docs/tutorial/request-form-models.md @@ -0,0 +1,78 @@ +# 表单模型 + +您可以使用 **Pydantic 模型**在 FastAPI 中声明**表单字段**。 + +/// info + +要使用表单,需预先安装 `python-multipart` 。 + +确保您创建、激活一个[虚拟环境](../virtual-environments.md){.internal-link target=_blank}后再安装。 + +```console +$ pip install python-multipart +``` + +/// + +/// note + +自 FastAPI 版本 `0.113.0` 起支持此功能。🤓 + +/// + +## 表单的 Pydantic 模型 + +您只需声明一个 **Pydantic 模型**,其中包含您希望接收的**表单字段**,然后将参数声明为 `Form` : + +{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *} + +**FastAPI** 将从请求中的**表单数据**中**提取**出**每个字段**的数据,并提供您定义的 Pydantic 模型。 + +## 检查文档 + +您可以在文档 UI 中验证它,地址为 `/docs` : + +
+ +
+ +## 禁止额外的表单字段 + +在某些特殊使用情况下(可能并不常见),您可能希望将表单字段**限制**为仅在 Pydantic 模型中声明过的字段,并**禁止**任何**额外**的字段。 + +/// note + +自 FastAPI 版本 `0.114.0` 起支持此功能。🤓 + +/// + +您可以使用 Pydantic 的模型配置来禁止( `forbid` )任何额外( `extra` )字段: + +{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *} + +如果客户端尝试发送一些额外的数据,他们将收到**错误**响应。 + +例如,如果客户端尝试发送这样的表单字段: + +* `username`: `Rick` +* `password`: `Portal Gun` +* `extra`: `Mr. Poopybutthole` + +他们将收到一条错误响应,表明字段 `extra` 是不被允许的: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "Mr. Poopybutthole" + } + ] +} +``` + +## 总结 + +您可以使用 Pydantic 模型在 FastAPI 中声明表单字段。😎 From 6c8deb5a4f69faf1611689db7d9fec1478c270c3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 10 Dec 2024 20:36:33 +0000 Subject: [PATCH 553/932] =?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 [skip ci] --- 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 599883d64..06426daf7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/tutorial/request-form-models.md`. PR [#13045](https://github.com/fastapi/fastapi/pull/13045) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Add Russian translation for `docs/ru/docs/virtual-environments.md`. PR [#13026](https://github.com/fastapi/fastapi/pull/13026) by [@alv2017](https://github.com/alv2017). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/testing.md`. PR [#12968](https://github.com/fastapi/fastapi/pull/12968) by [@jts8257](https://github.com/jts8257). * 🌐 Add Korean translation for `docs/ko/docs/advanced/async-test.md`. PR [#12918](https://github.com/fastapi/fastapi/pull/12918) by [@icehongssii](https://github.com/icehongssii). From 9802b90b66b69ac2cca5fef2abada92f3e94a2e0 Mon Sep 17 00:00:00 2001 From: Zhongheng Cheng Date: Tue, 10 Dec 2024 15:38:03 -0500 Subject: [PATCH 554/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/tutorial/cookie-param-models.md`=20(#?= =?UTF-8?q?13038)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/cookie-param-models.md | 76 ++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 docs/zh/docs/tutorial/cookie-param-models.md diff --git a/docs/zh/docs/tutorial/cookie-param-models.md b/docs/zh/docs/tutorial/cookie-param-models.md new file mode 100644 index 000000000..6a7b09e25 --- /dev/null +++ b/docs/zh/docs/tutorial/cookie-param-models.md @@ -0,0 +1,76 @@ +# Cookie 参数模型 + +如果您有一组相关的 **cookie**,您可以创建一个 **Pydantic 模型**来声明它们。🍪 + +这将允许您在**多个地方**能够**重用模型**,并且可以一次性声明所有参数的验证方式和元数据。😎 + +/// note + +自 FastAPI 版本 `0.115.0` 起支持此功能。🤓 + +/// + +/// tip + +此技术同样适用于 `Query` 、 `Cookie` 和 `Header` 。😎 + +/// + +## 带有 Pydantic 模型的 Cookie + +在 **Pydantic** 模型中声明所需的 **cookie** 参数,然后将参数声明为 `Cookie` : + +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} + +**FastAPI** 将从请求中接收到的 **cookie** 中**提取**出**每个字段**的数据,并提供您定义的 Pydantic 模型。 + +## 查看文档 + +您可以在文档 UI 的 `/docs` 中查看定义的 cookie: + +
+ +
+ +/// info + +请记住,由于**浏览器**以特殊方式**处理 cookie**,并在后台进行操作,因此它们**不会**轻易允许 **JavaScript** 访问这些 cookie。 + +如果您访问 `/docs` 的 **API 文档 UI**,您将能够查看您*路径操作*的 cookie **文档**。 + +但是即使您**填写数据**并点击“执行”,由于文档界面使用 **JavaScript**,cookie 将不会被发送。而您会看到一条**错误**消息,就好像您没有输入任何值一样。 + +/// + +## 禁止额外的 Cookie + +在某些特殊使用情况下(可能并不常见),您可能希望**限制**您想要接收的 cookie。 + +您的 API 现在可以控制自己的 cookie 同意。🤪🍪 + +您可以使用 Pydantic 的模型配置来禁止( `forbid` )任何额外( `extra` )字段: + +{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *} + +如果客户尝试发送一些**额外的 cookie**,他们将收到**错误**响应。 + +可怜的 cookie 通知条,费尽心思为了获得您的同意,却被API 拒绝了。🍪 + +例如,如果客户端尝试发送一个值为 `good-list-please` 的 `santa_tracker` cookie,客户端将收到一个**错误**响应,告知他们 `santa_tracker` cookie 是不允许的: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "santa_tracker"], + "msg": "Extra inputs are not permitted", + "input": "good-list-please", + } + ] +} +``` + +## 总结 + +您可以使用 **Pydantic 模型**在 **FastAPI** 中声明 **cookie**。😎 From e90af0c0f91513fd41b9f02c31de0a9a7fa16492 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 10 Dec 2024 20:39:15 +0000 Subject: [PATCH 555/932] =?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 [skip ci] --- 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 06426daf7..d9ef6146b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/tutorial/cookie-param-models.md`. PR [#13038](https://github.com/fastapi/fastapi/pull/13038) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Add Chinese translation for `docs/zh/docs/tutorial/request-form-models.md`. PR [#13045](https://github.com/fastapi/fastapi/pull/13045) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Add Russian translation for `docs/ru/docs/virtual-environments.md`. PR [#13026](https://github.com/fastapi/fastapi/pull/13026) by [@alv2017](https://github.com/alv2017). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/testing.md`. PR [#12968](https://github.com/fastapi/fastapi/pull/12968) by [@jts8257](https://github.com/jts8257). From 974284be907a30ee2e9b1ce9c121c6e32fb2400e Mon Sep 17 00:00:00 2001 From: Gerry Sabar Date: Fri, 13 Dec 2024 04:46:36 +0700 Subject: [PATCH 556/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Indonesian=20trans?= =?UTF-8?q?lation=20for=20`docs/id/docs/tutorial/first-steps.md`=20(#13042?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/id/docs/tutorial/first-steps.md | 332 +++++++++++++++++++++++++++ 1 file changed, 332 insertions(+) create mode 100644 docs/id/docs/tutorial/first-steps.md diff --git a/docs/id/docs/tutorial/first-steps.md b/docs/id/docs/tutorial/first-steps.md new file mode 100644 index 000000000..9b461507d --- /dev/null +++ b/docs/id/docs/tutorial/first-steps.md @@ -0,0 +1,332 @@ +# Langkah Pertama + +File FastAPI yang paling sederhana bisa seperti berikut: + +{* ../../docs_src/first_steps/tutorial001.py *} + +Salin file tersebut ke `main.py`. + +Jalankan di server: + +
+ +```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. +``` + +
+ +Di output, terdapat sebaris pesan: + +```hl_lines="4" +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +Baris tersebut menunjukan URL dimana app aktif di komputer anda. + + +### Mencoba aplikasi + +Buka browser di http://127.0.0.1:8000. + +Anda akan melihat response JSON sebagai berikut: + +```JSON +{"message": "Hello World"} +``` + +### Dokumen API interaktif + +Sekarang kunjungi http://127.0.0.1:8000/docs. + +Anda akan melihat dokumentasi API interaktif otomatis (dibuat oleh Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Dokumen API alternatif + +Dan sekarang, kunjungi http://127.0.0.1:8000/redoc. + +Anda akan melihat dokumentasi alternatif otomatis (dibuat oleh ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +### OpenAPI + +**FastAPI** membuat sebuah "schema" dimana semua API anda menggunakan standar **OpenAPI** untuk mendefinisikan API. + +#### "Schema" + +"schema" adalah suatu definisi atau deskripsi dari sesuatu. Bukan kode yang mengimplementasi definisi tersebut. Ini hanyalah sebuah deskripsi abstrak. + +#### "schema" API + +Dalam hal ini, OpenAPI adalah spesifikasi yang menunjukan bagaimana untuk mendefinisikan sebuah skema di API anda. + +Definisi skema ini termasuk jalur API anda, parameter yang bisa diterima, dll. + +#### "schema" Data + +Istilah "schema" bisa juga merujuk ke struktur data, seperti konten JSON. + +Dalam kondisi ini, ini berarti attribut JSON dan tipe data yang dimiliki, dll. + +#### Schema OpenAPI and JSON + +"schema" OpenAPI mendefinisikan skema API dari API yang anda buat. Skema tersebut termasuk definisi (atau "schema") dari data yang dikirim atau diterima oleh API dari **JSON Schema**, skema data standar JSON. + +#### Lihat `openapi.json` + +Jika anda penasaran bagaimana skema OpenAPI polos seperti apa, FastAPI secara otomatis membuat JSON (schema) dengan deksripsi API anda. + +anda bisa melihatnya di: http://127.0.0.1:8000/openapi.json. + +Anda akan melihat JSON yang dimulai seperti: + +```JSON +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + + + +... +``` + +#### Kegunaan OpenAPI + +Skema OpenAPI adalah tulang punggung dua sistem dokumentasi API interaktif yang ada di FastAPI. + +Ada banyak alternatif sistem dokumentasi lainnya yang semuanya berdasarkan OpenAPI. Anda bisa menambahkannya ke aplikasi **FastAPI** anda. + +Anda juga bisa menggunakan OpenAPI untuk membuat kode secara otomatis, untuk klien yang menggunakan API anda. Sebagai contoh, frontend, aplikasi mobile atau IoT. + +## Ringkasan, secara bertahap + +### Langkah 1: impor `FastAPI` + +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} + +`FastAPI` adalah class Python yang menyediakan semua fungsionalitas API anda. + +/// note | Detail Teknis + +`FastAPI` adalah class turunan langsung dari `Starlette`. + +Anda bisa menggunakan semua fungsionalitas Starlette dengan `FastAPI` juga. + +/// + +### Langkah 2: buat "instance" dari `FastAPI` + +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} + +Di sini variabel `app` akan menjadi sebuah "instance" dari class `FastAPI`. + +Ini akan menjadi gerbang utama untuk membuat semua API anda. + +### Langkah 3: Buat *operasi path* + +#### Path + +"Path" atau jalur di sini merujuk ke bagian URL terakhir dimulai dari `/` pertama. + +Sehingga, URL seperti: + +``` +https://example.com/items/foo +``` + +...path-nya adalah: + +``` +/items/foo +``` + +/// info + +"path" juga biasa disebut "endpoint" atau "route". + +/// + +ketika membuat API, "path" adalah jalan utama untuk memisahkan "concern" dan "resources". + +#### Operasi + +"Operasi" di sini merujuk ke salah satu dari metode HTTP berikut. + +Salah satu dari: + +* `POST` +* `GET` +* `PUT` +* `DELETE` + +...dan operasi lainnya yang unik: + +* `OPTIONS` +* `HEAD` +* `PATCH` +* `TRACE` + +Dalam protokol HTTP, anda bisa berkomunikasi ke setiap path menggunakan satu (atau lebih) metode di atas. + +--- + +Ketika membuat API, anda umumnya menggunakan metode HTTP tertentu untuk proses tertentu. + +Umumnya menggunakan: + +* `POST`: untuk membuat data. +* `GET`: untuk membaca data. +* `PUT`: untuk memperbarui data. +* `DELETE`: untuk menghapus data. + +Sehingga, di OpanAPI, setiap metode HTTP ini disebut sebuah "operasi". + +Kita akan menyebut mereka juga "**operasi**". + +#### Mendefinisikan *dekorator operasi path* + +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} + +`@app.get("/")` memberitahu **FastAPI** bahwa fungsi di bawahnya mengurusi request yang menuju ke: + +* path `/` +* menggunakan operasi get + +/// info | `@decorator` Info + +Sintaksis `@sesuatu` di Python disebut "dekorator". + +Dekorator ditempatkan di atas fungsi. Seperti sebuah topi cantik (Saya pikir istilah ini berasal dari situ). + +"dekorator" memanggil dan bekerja dengan fungsi yang ada di bawahnya + +Pada kondisi ini, dekorator ini memberi tahu **FastAPI** bahwa fungsi di bawah nya berhubungan dengan **path** `/` dengan **operasi** `get`. + +Sehingga disebut **dekorator operasi path**. + +/// + +Operasi lainnya yang bisa digunakan: + +* `@app.post()` +* `@app.put()` +* `@app.delete()` + +Dan operasi unik lainnya: + +* `@app.options()` +* `@app.head()` +* `@app.patch()` +* `@app.trace()` + +/// tip | Tips + +Jika anda bisa menggunakan operasi apa saja (metode HTTP). + +**FastAPI** tidak mengharuskan anda menggunakan operasi tertentu. + +Informasi di sini hanyalah sebagai panduan, bukan keharusan. + +Sebagai contoh, ketika menggunakan GraphQL, semua operasi umumnya hanya menggunakan `POST`. + +/// + +### Langkah 4: mendefinisikan **fungsi operasi path** + +Ini "**fungsi operasi path**" kita: + +* **path**: adalah `/`. +* **operasi**: adalah `get`. +* **fungsi**: adalah fungsi yang ada di bawah dekorator (di bawah `@app.get("/")`). + +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} + +Ini adalah fungsi Python. + +Fungsi ini dipanggil **FastAPI** setiap kali menerima request ke URL "`/`" dengan operasi `GET`. + +Di kondisi ini, ini adalah sebuah fungsi `async`. + +--- + +Anda bisa mendefinisikan fungsi ini sebagai fungsi normal daripada `async def`: + +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} + +/// note | Catatan + +Jika anda tidak tahu perbedaannya, kunjungi [Async: *"Panduan cepat"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +/// + +### Langkah 5: hasilkan konten + +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} + +Anda bisa menghasilkan `dict`, `list`, nilai singular seperti `str`, `int`, dll. + +Anda juga bisa menghasilkan model Pydantic (anda akan belajar mengenai ini nanti). + +Ada banyak objek dan model yang secara otomatis dikonversi ke JSON (termasuk ORM, dll). Anda bisa menggunakan yang anda suka, kemungkinan sudah didukung. + +## Ringkasan + +* Impor `FastAPI`. +* Buat sebuah instance `app`. +* Tulis **dekorator operasi path** menggunakan dekorator seperti `@app.get("/")`. +* Definisikan **fungsi operasi path**; sebagai contoh, `def root(): ...`. +* Jalankan server development dengan perintah `fastapi dev`. From a862acb877f72d157f9fe20e38e5242aa58ecec3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 12 Dec 2024 21:47:03 +0000 Subject: [PATCH 557/932] =?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 [skip ci] --- 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 d9ef6146b..8d4454c10 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Indonesian translation for `docs/id/docs/tutorial/first-steps.md`. PR [#13042](https://github.com/fastapi/fastapi/pull/13042) by [@gerry-sabar](https://github.com/gerry-sabar). * 🌐 Add Chinese translation for `docs/zh/docs/tutorial/cookie-param-models.md`. PR [#13038](https://github.com/fastapi/fastapi/pull/13038) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Add Chinese translation for `docs/zh/docs/tutorial/request-form-models.md`. PR [#13045](https://github.com/fastapi/fastapi/pull/13045) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Add Russian translation for `docs/ru/docs/virtual-environments.md`. PR [#13026](https://github.com/fastapi/fastapi/pull/13026) by [@alv2017](https://github.com/alv2017). From a277942a5297d230b85d8ff50910232c53ff0b6a Mon Sep 17 00:00:00 2001 From: Victor Menezes Date: Thu, 12 Dec 2024 19:47:10 -0300 Subject: [PATCH 558/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/advanced/generate-clients.md`=20(#?= =?UTF-8?q?13030)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/generate-clients.md | 261 ++++++++++++++++++++++ 1 file changed, 261 insertions(+) create mode 100644 docs/pt/docs/advanced/generate-clients.md diff --git a/docs/pt/docs/advanced/generate-clients.md b/docs/pt/docs/advanced/generate-clients.md new file mode 100644 index 000000000..04d7c0071 --- /dev/null +++ b/docs/pt/docs/advanced/generate-clients.md @@ -0,0 +1,261 @@ +# Generate Clients + +Como o **FastAPI** é baseado na especificação **OpenAPI**, você obtém compatibilidade automática com muitas ferramentas, incluindo a documentação automática da API (fornecida pelo Swagger UI). + +Uma vantagem particular que nem sempre é óbvia é que você pode **gerar clientes** (às vezes chamados de **SDKs**) para a sua API, para muitas **linguagens de programação** diferentes. + +## Geradores de Clientes OpenAPI + +Existem muitas ferramentas para gerar clientes a partir do **OpenAPI**. + +Uma ferramenta comum é o OpenAPI Generator. + +Se voce está construindo um **frontend**, uma alternativa muito interessante é o openapi-ts. + +## Geradores de Clientes e SDKs - Patrocinadores + +Existem também alguns geradores de clientes e SDKs baseados na OpenAPI (FastAPI) **patrocinados por empresas**, em alguns casos eles podem oferecer **recursos adicionais** além de SDKs/clientes gerados de alta qualidade. + +Alguns deles também ✨ [**patrocinam o FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, isso garante o **desenvolvimento** contínuo e saudável do FastAPI e seu **ecossistema**. + +E isso mostra o verdadeiro compromisso deles com o FastAPI e sua **comunidade** (você), pois eles não apenas querem fornecer um **bom serviço**, mas também querem garantir que você tenha um **framework bom e saudável**, o FastAPI. 🙇 + +Por exemplo, você pode querer experimentar: + +* Speakeasy +* Stainless +* liblab + +Existem também várias outras empresas que oferecem serviços semelhantes que você pode pesquisar e encontrar online. 🤓 + +## Gerar um Cliente Frontend TypeScript + +Vamos começar com um aplicativo **FastAPI** simples: + +{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *} + +Note que as *operações de rota* definem os modelos que usam para o corpo da requisição e o corpo da resposta, usando os modelos `Item` e `ResponseMessage`. + +### Documentação da API + +Se você acessar a documentação da API, verá que ela tem os **schemas** para os dados a serem enviados nas requisições e recebidos nas respostas: + + + +Você pode ver esses schemas porque eles foram declarados com os modelos no app. + +Essas informações estão disponíveis no **OpenAPI schema** do app e são mostradas na documentação da API (pelo Swagger UI). + +E essas mesmas informações dos modelos que estão incluídas no OpenAPI são o que pode ser usado para **gerar o código do cliente**. + +### Gerar um Cliente TypeScript + +Agora que temos o app com os modelos, podemos gerar o código do cliente para o frontend. + +#### Instalar o `openapi-ts` + +Você pode instalar o `openapi-ts` no seu código frontend com: + +
+ +```console +$ npm install @hey-api/openapi-ts --save-dev + +---> 100% +``` + +
+ +#### Gerar o Código do Cliente + +Para gerar o código do cliente, você pode usar a aplicação de linha de comando `openapi-ts` que agora está instalada. + +Como ela está instalada no projeto local, você provavelmente não conseguiria chamar esse comando diretamente, mas você o colocaria no seu arquivo `package.json`. + +Poderia ser assim: + +```JSON hl_lines="7" +{ + "name": "frontend-app", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "generate-client": "openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios" + }, + "author": "", + "license": "", + "devDependencies": { + "@hey-api/openapi-ts": "^0.27.38", + "typescript": "^4.6.2" + } +} +``` + +Depois de ter esse script NPM `generate-client` lá, você pode executá-lo com: + +
+ +```console +$ npm run generate-client + +frontend-app@1.0.0 generate-client /home/user/code/frontend-app +> openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios +``` + +
+ +Esse comando gerará o código em `./src/client` e usará o `axios` (a biblioteca HTTP frontend) internamente. + +### Experimente o Código do Cliente + +Agora você pode importar e usar o código do cliente, ele poderia ser assim, observe que você obtém preenchimento automático para os métodos: + + + +Você também obterá preenchimento automático para o corpo a ser enviado: + + + +/// tip | Dica + +Observe o preenchimento automático para `name` e `price`, que foi definido no aplicativo FastAPI, no modelo `Item`. + +/// + +Você terá erros em linha para os dados que você envia: + + + +O objeto de resposta também terá preenchimento automático: + + + +## App FastAPI com Tags + +Em muitos casos seu app FastAPI será maior, e você provavelmente usará tags para separar diferentes grupos de *operações de rota*. + +Por exemplo, você poderia ter uma seção para **items** e outra seção para **users**, e elas poderiam ser separadas por tags: + +{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *} + +### Gerar um Cliente TypeScript com Tags + +Se você gerar um cliente para um app FastAPI usando tags, normalmente também separará o código do cliente com base nas tags. + +Dessa forma, você poderá ter as coisas ordenadas e agrupadas corretamente para o código do cliente: + + + +Nesse caso você tem: + +* `ItemsService` +* `UsersService` + +### Nomes dos Métodos do Cliente + +Agora os nomes dos métodos gerados como `createItemItemsPost` não parecem muito "limpos": + +```TypeScript +ItemsService.createItemItemsPost({name: "Plumbus", price: 5}) +``` + +...isto ocorre porque o gerador de clientes usa o **operation ID** interno do OpenAPI para cada *operação de rota*. + +O OpenAPI exige que cada operation ID seja único em todas as *operações de rota*, então o FastAPI usa o **nome da função**, o **caminho** e o **método/operacao HTTP** para gerar esse operation ID, porque dessa forma ele pode garantir que os operation IDs sejam únicos. + +Mas eu vou te mostrar como melhorar isso a seguir. 🤓 + +### IDs de Operação Personalizados e Melhores Nomes de Método + +Você pode **modificar** a maneira como esses IDs de operação são **gerados** para torná-los mais simples e ter **nomes de método mais simples** nos clientes. + +Neste caso, você terá que garantir que cada ID de operação seja **único** de alguma outra maneira. + +Por exemplo, você poderia garantir que cada *operação de rota* tenha uma tag, e então gerar o ID da operação com base na **tag** e no **nome** da *operação de rota* (o nome da função). + +### Função Personalizada para Gerar IDs de Operação Únicos + +O FastAPI usa um **ID único** para cada *operação de rota*, ele é usado para o **ID da operação** e também para os nomes de quaisquer modelos personalizados necessários, para requisições ou respostas. + +Você pode personalizar essa função. Ela recebe uma `APIRoute` e gera uma string. + +Por exemplo, aqui está usando a primeira tag (você provavelmente terá apenas uma tag) e o nome da *operação de rota* (o nome da função). + +Você pode então passar essa função personalizada para o **FastAPI** como o parâmetro `generate_unique_id_function`: + +{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *} + +### Gerar um Cliente TypeScript com IDs de Operação Personalizados + +Agora, se você gerar o cliente novamente, verá que ele tem os nomes dos métodos melhorados: + + + +Como você pode ver, os nomes dos métodos agora têm a tag e, em seguida, o nome da função. Agora eles não incluem informações do caminho da URL e da operação HTTP. + +### Pré-processar a Especificação OpenAPI para o Gerador de Clientes + +O código gerado ainda tem algumas **informações duplicadas**. + +Nós já sabemos que esse método está relacionado aos **items** porque essa palavra está no `ItemsService` (retirada da tag), mas ainda temos o nome da tag prefixado no nome do método também. 😕 + +Provavelmente ainda queremos mantê-lo para o OpenAPI em geral, pois isso garantirá que os IDs de operação sejam **únicos**. + +Mas para o cliente gerado, poderíamos **modificar** os IDs de operação do OpenAPI logo antes de gerar os clientes, apenas para tornar esses nomes de método mais **simples**. + +Poderíamos baixar o JSON do OpenAPI para um arquivo `openapi.json` e então poderíamos **remover essa tag prefixada** com um script como este: + +{* ../../docs_src/generate_clients/tutorial004.py *} + +//// tab | Node.js + +```Javascript +{!> ../../docs_src/generate_clients/tutorial004.js!} +``` + +//// + +Com isso, os IDs de operação seriam renomeados de coisas como `items-get_items` para apenas `get_items`, dessa forma o gerador de clientes pode gerar nomes de métodos mais simples. + +### Gerar um Cliente TypeScript com o OpenAPI Pré-processado + +Agora, como o resultado final está em um arquivo `openapi.json`, você modificaria o `package.json` para usar esse arquivo local, por exemplo: + +```JSON hl_lines="7" +{ + "name": "frontend-app", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios" + }, + "author": "", + "license": "", + "devDependencies": { + "@hey-api/openapi-ts": "^0.27.38", + "typescript": "^4.6.2" + } +} +``` + +Depois de gerar o novo cliente, você teria agora **nomes de métodos "limpos"**, com todo o **preenchimento automático**, **erros em linha**, etc: + + + +## Benefícios + +Ao usar os clientes gerados automaticamente, você teria **preenchimento automático** para: + +* Métodos. +* Corpo de requisições, parâmetros da query, etc. +* Corpo de respostas. + +Você também teria **erros em linha** para tudo. + +E sempre que você atualizar o código do backend, e **regenerar** o frontend, ele teria quaisquer novas *operações de rota* disponíveis como métodos, as antigas removidas, e qualquer outra alteração seria refletida no código gerado. 🤓 + +Isso também significa que se algo mudar, será **refletido** no código do cliente automaticamente. E se você **construir** o cliente, ele dará erro se houver alguma **incompatibilidade** nos dados usados. + +Então, você **detectaria vários erros** muito cedo no ciclo de desenvolvimento, em vez de ter que esperar que os erros apareçam para seus usuários finais em produção e então tentar depurar onde está o problema. ✨ From fbd3ff4a6f3ac1ae5c56c1ba39b722841432c128 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 12 Dec 2024 22:47:34 +0000 Subject: [PATCH 559/932] =?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 [skip ci] --- 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 8d4454c10..a8a185a69 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/generate-clients.md`. PR [#13030](https://github.com/fastapi/fastapi/pull/13030) by [@vitumenezes](https://github.com/vitumenezes). * 🌐 Add Indonesian translation for `docs/id/docs/tutorial/first-steps.md`. PR [#13042](https://github.com/fastapi/fastapi/pull/13042) by [@gerry-sabar](https://github.com/gerry-sabar). * 🌐 Add Chinese translation for `docs/zh/docs/tutorial/cookie-param-models.md`. PR [#13038](https://github.com/fastapi/fastapi/pull/13038) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Add Chinese translation for `docs/zh/docs/tutorial/request-form-models.md`. PR [#13045](https://github.com/fastapi/fastapi/pull/13045) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). From 627242b8ae88a3a9bb04af3ad096c3182bb129d8 Mon Sep 17 00:00:00 2001 From: Aleksandr Lobanov Date: Fri, 13 Dec 2024 05:48:28 +0700 Subject: [PATCH 560/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Russian=20trans?= =?UTF-8?q?lation=20for=20`docs/ru/docs/deployment/docker.md`=20(#13048)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/deployment/docker.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/ru/docs/deployment/docker.md b/docs/ru/docs/deployment/docker.md index 31da01b78..c72f67172 100644 --- a/docs/ru/docs/deployment/docker.md +++ b/docs/ru/docs/deployment/docker.md @@ -58,7 +58,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] ## Образы контейнеров -Docker является одним оз основных инструментов для создания **образов** и **контейнеров** и управления ими. +Docker является одним из основных инструментов для создания **образов** и **контейнеров** и управления ими. Существует общедоступный Docker Hub с подготовленными **официальными образами** многих инструментов, окружений, баз данных и приложений. @@ -87,7 +87,7 @@ Docker является одним оз основных инструменто Когда **контейнер** запущен, он будет выполнять прописанные в нём команды и программы. Но вы можете изменить его так, чтоб он выполнял другие команды и программы. -Контейнер буде работать до тех пор, пока выполняется его **главный процесс** (команда или программа). +Контейнер будет работать до тех пор, пока выполняется его **главный процесс** (команда или программа). В контейнере обычно выполняется **только один процесс**, но от его имени можно запустить другие процессы, тогда в этом же в контейнере будет выполняться **множество процессов**. @@ -215,7 +215,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Опция `--upgrade` указывает `pip` обновить библиотеки, емли они уже установлены. - Ка и в предыдущем шаге с копированием файла, этот шаг также будет использовать **кэш Docker** в случае отсутствия изменений. + Как и в предыдущем шаге с копированием файла, этот шаг также будет использовать **кэш Docker** в случае отсутствия изменений. Использование кэша, особенно на этом шаге, позволит вам **сэкономить** кучу времени при повторной сборке образа, так как зависимости будут сохранены в кеше, а не **загружаться и устанавливаться каждый раз**. From 6ae85b47429c064e2cf1ea704e202da6bbf1ec18 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 12 Dec 2024 22:49:43 +0000 Subject: [PATCH 561/932] =?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 [skip ci] --- 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 a8a185a69..5f1b95d85 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Update Russian translation for `docs/ru/docs/deployment/docker.md`. PR [#13048](https://github.com/fastapi/fastapi/pull/13048) by [@anklav24](https://github.com/anklav24). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/generate-clients.md`. PR [#13030](https://github.com/fastapi/fastapi/pull/13030) by [@vitumenezes](https://github.com/vitumenezes). * 🌐 Add Indonesian translation for `docs/id/docs/tutorial/first-steps.md`. PR [#13042](https://github.com/fastapi/fastapi/pull/13042) by [@gerry-sabar](https://github.com/gerry-sabar). * 🌐 Add Chinese translation for `docs/zh/docs/tutorial/cookie-param-models.md`. PR [#13038](https://github.com/fastapi/fastapi/pull/13038) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). From 0f5146fa5de0eb469a2b4608c235e6f0184b1387 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 15 Dec 2024 14:35:18 +0100 Subject: [PATCH 562/932] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors:=20ren?= =?UTF-8?q?ame=20CryptAPI=20to=20BlockBee=20(#13078)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/en/data/sponsors.yml | 6 +++--- docs/en/data/sponsors_badge.yml | 1 + docs/en/docs/img/sponsors/blockbee-banner.png | Bin 0 -> 11353 bytes docs/en/docs/img/sponsors/blockbee.png | Bin 0 -> 13006 bytes docs/en/overrides/main.html | 4 ++-- 6 files changed, 7 insertions(+), 6 deletions(-) create mode 100644 docs/en/docs/img/sponsors/blockbee-banner.png create mode 100644 docs/en/docs/img/sponsors/blockbee.png diff --git a/README.md b/README.md index 66ffd7355..6492ad745 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ The key features are: - + diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index e66d592f5..4231452e4 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -1,7 +1,7 @@ gold: - - url: https://cryptapi.io/ - title: "CryptAPI: Your easy to use, secure and privacy oriented payment gateway." - img: https://fastapi.tiangolo.com/img/sponsors/cryptapi.svg + - url: https://blockbee.io?ref=fastapi + title: BlockBee Cryptocurrency Payment Gateway + img: https://fastapi.tiangolo.com/img/sponsors/blockbee.png - url: https://platform.sh/try-it-now/?utm_source=fastapi-signup&utm_medium=banner&utm_campaign=FastAPI-signup-June-2023 title: "Build, run and scale your apps on a modern, reliable, and secure PaaS." img: https://fastapi.tiangolo.com/img/sponsors/platform-sh.png diff --git a/docs/en/data/sponsors_badge.yml b/docs/en/data/sponsors_badge.yml index 7470b0238..3e885a2f7 100644 --- a/docs/en/data/sponsors_badge.yml +++ b/docs/en/data/sponsors_badge.yml @@ -32,3 +32,4 @@ logins: - Kong - speakeasy-api - jess-render + - blockbee-io diff --git a/docs/en/docs/img/sponsors/blockbee-banner.png b/docs/en/docs/img/sponsors/blockbee-banner.png new file mode 100644 index 0000000000000000000000000000000000000000..074b36031244e5b690e377d04ffa3ac98eea42d8 GIT binary patch literal 11353 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 literal 0 HcmV?d00001 diff --git a/docs/en/docs/img/sponsors/blockbee.png b/docs/en/docs/img/sponsors/blockbee.png new file mode 100644 index 0000000000000000000000000000000000000000..6d2fcf7019c88d15cd547c870257982d433c67b6 GIT binary patch literal 13006 zcmYjYWn3H0*A4Dc+@)Bd6xZNx1qu|`;!c6!R-m}Mdy%3oUYr6&8=RElR)Pk1dH4B$ zdOsxl%Vx5fow@hibI#1hywgy^!=}Opfk1dF%JSO4@dS8TW1<7^?WNtrzya%{vY{sk zgg@}#3u)M`${ILH2~jYB=(yQJd_H*CfP8#>xEx%aJgq)_wBd5|u**9ZrviZ(Kq~Sw z?|t)+3VZ@-=39n)`8#Xok5y|{>nzn8m#Hnj^;2LVBgM-Rpl%AtA~Q>`GWlV#OH*y9 zpqh;ZFfvQa%Bp-?x5y3er?BFoh^O|*vevC>o4+c!9wu|iTg;hP%^bfCyqJbA&mK?Y z2LyZCL23JU_ftU(C)^KhBrSC}V*Wmmys*S}Z)?)wF)Y>ApKWMp0opVN``g=(B+}ZO zy88`At0MO-E&eRGtO{l_hDoKrPmbVQ#H(DdM#frL&J@%_cD5s`j^Jw^M_Om@R`NAc z3}fI@aMkAGd+M%S(xj(MJTpaJ=R4eJv}2c4}rBB#bjOg5Ia zQiWlNW=FtMZ0uf8o8l=RsEa}stUagNV1VSwF{q#q@t;_(rwJ`AYp`s`XvDv#FUzA(6~3>Xr6b zrK}z=b;8b1{gKVa@ZZy)pfRsra40uxj(b%n{6xN?2!~ehXrmPf{t?3}AiXH8ni9

s+?Voz7%-85A@u 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

From d7f88623e1304667c67da17dfd278b5099522ef9 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 15 Dec 2024 13:35:39 +0000 Subject: [PATCH 563/932] =?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 [skip ci] --- 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 5f1b95d85..623a68303 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -41,6 +41,7 @@ hide: ### Internal +* 🔧 Update sponsors: rename CryptAPI to BlockBee. PR [#13078](https://github.com/fastapi/fastapi/pull/13078) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump pypa/gh-action-pypi-publish from 1.12.2 to 1.12.3. PR [#13055](https://github.com/fastapi/fastapi/pull/13055) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump types-ujson from 5.7.0.1 to 5.10.0.20240515. PR [#13018](https://github.com/fastapi/fastapi/pull/13018) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump black from 24.3.0 to 24.10.0. PR [#13014](https://github.com/fastapi/fastapi/pull/13014) by [@dependabot[bot]](https://github.com/apps/dependabot). From 97206ee28f015806d851c7eff5cd4761d1a62a81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E9=9B=B2=E6=98=94=20=28Vincy=20SHI=29?= Date: Mon, 16 Dec 2024 00:39:22 +0800 Subject: [PATCH 564/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/tutorial/first-steps.md`=20(#12923?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/first-steps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/zh/docs/tutorial/first-steps.md b/docs/zh/docs/tutorial/first-steps.md index 038e17888..c4ff460e0 100644 --- a/docs/zh/docs/tutorial/first-steps.md +++ b/docs/zh/docs/tutorial/first-steps.md @@ -313,7 +313,7 @@ https://example.com/items/foo /// note -如果你不知道两者的区别,请查阅 [Async: *"In a hurry?"*](https://fastapi.tiangolo.com/async/#in-a-hurry){.internal-link target=_blank}。 +如果你不知道两者的区别,请查阅 [并发: *赶时间吗?*](../async.md#_1){.internal-link target=_blank}。 /// From f5f0d20af0aba9fb74dc255a5e469f95a1c332da Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 15 Dec 2024 16:39:45 +0000 Subject: [PATCH 565/932] =?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 [skip ci] --- 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 623a68303..1507c62c0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/first-steps.md`. PR [#12923](https://github.com/fastapi/fastapi/pull/12923) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Update Russian translation for `docs/ru/docs/deployment/docker.md`. PR [#13048](https://github.com/fastapi/fastapi/pull/13048) by [@anklav24](https://github.com/anklav24). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/generate-clients.md`. PR [#13030](https://github.com/fastapi/fastapi/pull/13030) by [@vitumenezes](https://github.com/vitumenezes). * 🌐 Add Indonesian translation for `docs/id/docs/tutorial/first-steps.md`. PR [#13042](https://github.com/fastapi/fastapi/pull/13042) by [@gerry-sabar](https://github.com/gerry-sabar). From 0e5f5d2e93b8d466762fa86a437ec2fae94f4fd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E9=9B=B2=E6=98=94=20=28Vincy=20SHI=29?= Date: Mon, 16 Dec 2024 00:43:19 +0800 Subject: [PATCH 566/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/tutorial/path-params.md`=20(#12926?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/path-params.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/zh/docs/tutorial/path-params.md b/docs/zh/docs/tutorial/path-params.md index 692214a4b..ac9df0831 100644 --- a/docs/zh/docs/tutorial/path-params.md +++ b/docs/zh/docs/tutorial/path-params.md @@ -137,7 +137,7 @@ FastAPI 充分地利用了 枚举(即 enums)。 +Python 3.4 及之后版本支持枚举(即 enums)。 /// From 488763e9f7cd760b035fc20ab0de746a5e3ce8b0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 15 Dec 2024 16:43:41 +0000 Subject: [PATCH 567/932] =?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 [skip ci] --- 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 1507c62c0..5d6d307fe 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/path-params.md`. PR [#12926](https://github.com/fastapi/fastapi/pull/12926) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/first-steps.md`. PR [#12923](https://github.com/fastapi/fastapi/pull/12923) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Update Russian translation for `docs/ru/docs/deployment/docker.md`. PR [#13048](https://github.com/fastapi/fastapi/pull/13048) by [@anklav24](https://github.com/anklav24). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/generate-clients.md`. PR [#13030](https://github.com/fastapi/fastapi/pull/13030) by [@vitumenezes](https://github.com/vitumenezes). From c1220535cc95e27b2ef45c64c0d967227b2038b7 Mon Sep 17 00:00:00 2001 From: Zhongheng Cheng Date: Sun, 15 Dec 2024 11:44:11 -0500 Subject: [PATCH 568/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/tutorial/header-param-models.md`=20(#?= =?UTF-8?q?13040)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/header-param-models.md | 56 ++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 docs/zh/docs/tutorial/header-param-models.md diff --git a/docs/zh/docs/tutorial/header-param-models.md b/docs/zh/docs/tutorial/header-param-models.md new file mode 100644 index 000000000..13366aebc --- /dev/null +++ b/docs/zh/docs/tutorial/header-param-models.md @@ -0,0 +1,56 @@ +# Header 参数模型 + +如果您有一组相关的 **header 参数**,您可以创建一个 **Pydantic 模型**来声明它们。 + +这将允许您在**多个地方**能够**重用模型**,并且可以一次性声明所有参数的验证和元数据。😎 + +/// note + +自 FastAPI 版本 `0.115.0` 起支持此功能。🤓 + +/// + +## 使用 Pydantic 模型的 Header 参数 + +在 **Pydantic 模型**中声明所需的 **header 参数**,然后将参数声明为 `Header` : + +{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *} + +**FastAPI** 将从请求中接收到的 **headers** 中**提取**出**每个字段**的数据,并提供您定义的 Pydantic 模型。 + +## 查看文档 + +您可以在文档 UI 的 `/docs` 中查看所需的 headers: + +
+ +
+ +## 禁止额外的 Headers + +在某些特殊使用情况下(可能并不常见),您可能希望**限制**您想要接收的 headers。 + +您可以使用 Pydantic 的模型配置来禁止( `forbid` )任何额外( `extra` )字段: + +{* ../../docs_src/header_param_models/tutorial002_an_py310.py hl[10] *} + +如果客户尝试发送一些**额外的 headers**,他们将收到**错误**响应。 + +例如,如果客户端尝试发送一个值为 `plumbus` 的 `tool` header,客户端将收到一个**错误**响应,告知他们 header 参数 `tool` 是不允许的: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["header", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ] +} +``` + +## 总结 + +您可以使用 **Pydantic 模型**在 **FastAPI** 中声明 **headers**。😎 From 940c0fb9fb7db850fa12f13d28cd8dbea0e6b5e8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 15 Dec 2024 16:45:42 +0000 Subject: [PATCH 569/932] =?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 [skip ci] --- 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 5d6d307fe..4b9c9c053 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/tutorial/header-param-models.md`. PR [#13040](https://github.com/fastapi/fastapi/pull/13040) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/path-params.md`. PR [#12926](https://github.com/fastapi/fastapi/pull/12926) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/first-steps.md`. PR [#12923](https://github.com/fastapi/fastapi/pull/12923) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Update Russian translation for `docs/ru/docs/deployment/docker.md`. PR [#13048](https://github.com/fastapi/fastapi/pull/13048) by [@anklav24](https://github.com/anklav24). From d3360406c4287f2814b7ffdca6a84fc83e8f74ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E9=9B=B2=E6=98=94=20=28Vincy=20SHI=29?= Date: Mon, 16 Dec 2024 01:10:14 +0800 Subject: [PATCH 570/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/tutorial/query-params-str-validati?= =?UTF-8?q?ons.md`=20(#12928)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/query-params-str-validations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/zh/docs/tutorial/query-params-str-validations.md b/docs/zh/docs/tutorial/query-params-str-validations.md index 9b9d1f5fd..2fba671f7 100644 --- a/docs/zh/docs/tutorial/query-params-str-validations.md +++ b/docs/zh/docs/tutorial/query-params-str-validations.md @@ -116,7 +116,7 @@ q: Union[str, None] = Query(default=None, min_length=3) /// info -如果你之前没见过 `...` 这种用法:它是一个特殊的单独值,它是 Python 的一部分并且被称为「省略号」。 +如果你之前没见过 `...` 这种用法:它是一个特殊的单独值,它是 Python 的一部分并且被称为“Ellipsis”(意为省略号 —— 译者注)。 Pydantic 和 FastAPI 使用它来显式的声明需要一个值。 /// From cfc17e5510c07b78fd627f6f3b2b962ccd0d31f2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 15 Dec 2024 17:10:40 +0000 Subject: [PATCH 571/932] =?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 [skip ci] --- 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 4b9c9c053..8b3e4bc1b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params-str-validations.md`. PR [#12928](https://github.com/fastapi/fastapi/pull/12928) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Add Chinese translation for `docs/zh/docs/tutorial/header-param-models.md`. PR [#13040](https://github.com/fastapi/fastapi/pull/13040) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/path-params.md`. PR [#12926](https://github.com/fastapi/fastapi/pull/12926) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/first-steps.md`. PR [#12923](https://github.com/fastapi/fastapi/pull/12923) by [@Vincy1230](https://github.com/Vincy1230). From 929e844754aa18f7ed05976cd011c73b3c91a63c Mon Sep 17 00:00:00 2001 From: Zhongheng Cheng Date: Sun, 15 Dec 2024 12:11:14 -0500 Subject: [PATCH 572/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/tutorial/sql-databases.md`=20(#13051)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/sql-databases.md | 360 +++++++++++++++++++++++++ 1 file changed, 360 insertions(+) create mode 100644 docs/zh/docs/tutorial/sql-databases.md diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md new file mode 100644 index 000000000..fbdf3be6c --- /dev/null +++ b/docs/zh/docs/tutorial/sql-databases.md @@ -0,0 +1,360 @@ +# SQL(关系型)数据库 + +**FastAPI** 并不要求您使用 SQL(关系型)数据库。您可以使用**任何**想用的数据库。 + +这里,我们来看一个使用 SQLModel 的示例。 + +**SQLModel** 是基于 SQLAlchemy 和 Pydantic 构建的。它由 **FastAPI** 的同一作者制作,旨在完美匹配需要使用 **SQL 数据库**的 FastAPI 应用程序。 + +/// tip + +您可以使用任何其他您想要的 SQL 或 NoSQL 数据库(在某些情况下称为 “ORM”),FastAPI 不会强迫您使用任何东西。😎 + +/// + +由于 SQLModel 基于 SQLAlchemy,因此您可以轻松使用任何由 SQLAlchemy **支持的数据库**(这也让它们被 SQLModel 支持),例如: + +* PostgreSQL +* MySQL +* SQLite +* Oracle +* Microsoft SQL Server 等. + +在这个例子中,我们将使用 **SQLite**,因为它使用单个文件,并且 Python 对其有集成支持。因此,您可以直接复制这个例子并运行。 + +之后,对于您的生产应用程序,您可能会想要使用像 PostgreSQL 这样的数据库服务器。 + +/// tip + +有一个使用 **FastAPI** 和 **PostgreSQL** 的官方的项目生成器,其中包括了前端和更多工具: https://github.com/fastapi/full-stack-fastapi-template + +/// + +这是一个非常简单和简短的教程。如果您想了解一般的数据库、SQL 或更高级的功能,请查看 SQLModel 文档。 + +## 安装 `SQLModel` + +首先,确保您创建并激活了[虚拟环境](../virtual-environments.md){.internal-link target=_blank},然后安装了 `sqlmodel` : + +
+ +```console +$ pip install sqlmodel +---> 100% +``` + +
+ +## 创建含有单一模型的应用程序 + +我们首先创建应用程序的最简单的第一个版本,只有一个 **SQLModel** 模型。 + +稍后我们将通过下面的**多个模型**提高其安全性和多功能性。🤓 + +### 创建模型 + +导入 `SQLModel` 并创建一个数据库模型: + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[1:11] hl[7:11] *} + +`Hero` 类与 Pydantic 模型非常相似(实际上,从底层来看,它确实*就是一个 Pydantic 模型*)。 + +有一些区别: + +* `table=True` 会告诉 SQLModel 这是一个*表模型*,它应该表示 SQL 数据库中的一个*表*,而不仅仅是一个*数据模型*(就像其他常规的 Pydantic 类一样)。 + +* `Field(primary_key=True)` 会告诉 SQLModel `id` 是 SQL 数据库中的**主键**(您可以在 SQLModel 文档中了解更多关于 SQL 主键的信息)。 + + 把类型设置为 `int | None` ,SQLModel 就能知道该列在 SQL 数据库中应该是 `INTEGER` 类型,并且应该是 `NULLABLE` 。 + +* `Field(index=True)` 会告诉 SQLModel 应该为此列创建一个 **SQL 索引**,这样在读取按此列过滤的数据时,程序能在数据库中进行更快的查找。 + + SQLModel 会知道声明为 `str` 的内容将是类型为 `TEXT` (或 `VARCHAR` ,具体取决于数据库)的 SQL 列。 + +### 创建引擎(Engine) + +SQLModel 的引擎 `engine`(实际上它是一个 SQLAlchemy `engine` )是用来与数据库**保持连接**的。 + +您只需构建**一个 `engine`**,来让您的所有代码连接到同一个数据库。 + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[14:18] hl[14:15,17:18] *} + +使用 `check_same_thread=False` 可以让 FastAPI 在不同线程中使用同一个 SQLite 数据库。这很有必要,因为**单个请求**可能会使用**多个线程**(例如在依赖项中)。 + +不用担心,我们会按照代码结构确保**每个请求使用一个单独的 SQLModel *会话***,这实际上就是 `check_same_thread` 想要实现的。 + +### 创建表 + +然后,我们来添加一个函数,使用 `SQLModel.metadata.create_all(engine)` 为所有*表模型***创建表**。 + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[21:22] hl[21:22] *} + +### 创建会话(Session)依赖项 + +**`Session`** 会存储**内存中的对象**并跟踪数据中所需更改的内容,然后它**使用 `engine`** 与数据库进行通信。 + +我们会使用 `yield` 创建一个 FastAPI **依赖项**,为每个请求提供一个新的 `Session` 。这确保我们每个请求使用一个单独的会话。🤓 + +然后我们创建一个 `Annotated` 的依赖项 `SessionDep` 来简化其他也会用到此依赖的代码。 + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[25:30] hl[25:27,30] *} + +### 在启动时创建数据库表 + +我们会在应用程序启动时创建数据库表。 + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[32:37] hl[35:37] *} + +此处,在应用程序启动事件中,我们创建了表。 + +而对于生产环境,您可能会用一个能够在启动应用程序之前运行的迁移脚本。🤓 + +/// tip + +SQLModel 将会拥有封装 Alembic 的迁移工具,但目前您可以直接使用 Alembic。 + +/// + +### 创建 Hero 类 + +因为每个 SQLModel 模型同时也是一个 Pydantic 模型,所以您可以在与 Pydantic 模型相同的**类型注释**中使用它。 + +例如,如果您声明一个类型为 `Hero` 的参数,它将从 **JSON 主体**中读取数据。 + +同样,您可以将其声明为函数的**返回类型**,然后数据的结构就会显示在自动生成的 API 文档界面中。 + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *} + + + +这里,我们使用 `SessionDep` 依赖项(一个 `Session` )将新的 `Hero` 添加到 `Session` 实例中,提交更改到数据库,刷新 hero 中的数据,并返回它。 + +### 读取 Hero 类 + +我们可以使用 `select()` 从数据库中**读取** `Hero` 类,并利用 `limit` 和 `offset` 来对结果进行分页。 + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[48:55] hl[51:52,54] *} + +### 读取单个 Hero + +我们可以**读取**单个 `Hero` 。 + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[58:63] hl[60] *} + +### 删除单个 Hero + +我们也可以**删除**单个 `Hero` 。 + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[66:73] hl[71] *} + +### 运行应用程序 + +您可以运行这个应用程序: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +然后在 `/docs` UI 中,您能够看到 **FastAPI** 会用这些**模型**来**记录** API,并且还会用它们来**序列化**和**验证**数据。 + +
+ +
+ +## 更新应用程序以支持多个模型 + +现在让我们稍微**重构**一下这个应用,以提高**安全性**和**多功能性**。 + +如果您查看之前的应用程序,您可以在 UI 界面中看到,到目前为止,由客户端决定要创建的 `Hero` 的 `id` 值。😱 + +我们不应该允许这样做,因为他们可能会覆盖我们在数据库中已经分配的 `id` 。决定 `id` 的行为应该由**后端**或**数据库**来完成,**而非客户端**。 + +此外,我们为 hero 创建了一个 `secret_name` ,但到目前为止,我们在各处都返回了它,这就不太**秘密**了……😅 + +我们将通过添加一些**额外的模型**来解决这些问题,而 SQLModel 将在这里大放异彩。✨ + +### 创建多个模型 + +在 **SQLModel** 中,任何含有 `table=True` 属性的模型类都是一个**表模型**。 + +任何不含有 `table=True` 属性的模型类都是**数据模型**,这些实际上只是 Pydantic 模型(附带一些小的额外功能)。🤓 + +有了 SQLModel,我们就可以利用**继承**来在所有情况下**避免重复**所有字段。 + +#### `HeroBase` - 基类 + +我们从一个 `HeroBase` 模型开始,该模型具有所有模型**共享的字段**: + +* `name` +* `age` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:9] hl[7:9] *} + +#### `Hero` - *表模型* + +接下来,我们创建 `Hero` ,实际的*表模型*,并添加那些不总是在其他模型中的**额外字段**: + +* `id` +* `secret_name` + +因为 `Hero` 继承自 HeroBase ,所以它**也**包含了在 `HeroBase` 中声明过的**字段**。因此 `Hero` 的所有字段为: + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:14] hl[12:14] *} + +#### `HeroPublic` - 公共*数据模型* + +接下来,我们创建一个 `HeroPublic` 模型,这是将**返回**给 API 客户端的模型。 + +它包含与 `HeroBase` 相同的字段,因此不会包括 `secret_name` 。 + +终于,我们英雄(hero)的身份得到了保护! 🥷 + +它还重新声明了 `id: int` 。这样我们便与 API 客户端建立了一种**约定**,使他们始终可以期待 `id` 存在并且是一个整数 `int`(永远不会是 `None` )。 + +/// tip + +确保返回模型始终提供一个值并且始终是 `int` (而不是 `None` )对 API 客户端非常有用,他们可以在这种确定性下编写更简单的代码。 + +此外,**自动生成的客户端**将拥有更简洁的接口,这样与您的 API 交互的开发者就能更轻松地使用您的 API。😎 + +/// + +`HeroPublic` 中的所有字段都与 `HeroBase` 中的相同,其中 `id` 声明为 `int` (不是 `None` ): + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *} + +#### `HeroCreate` - 用于创建 hero 的*数据模型* + +现在我们创建一个 `HeroCreate` 模型,这是用于**验证**客户数据的模型。 + +它不仅拥有与 `HeroBase` 相同的字段,还有 `secret_name` 。 + +现在,当客户端**创建一个新的 hero** 时,他们会发送 `secret_name` ,它会被存储到数据库中,但这些 `secret_name` 不会通过 API 返回给客户端。 + +/// tip + +这应当是**密码**被处理的方式:接收密码,但不要通过 API 返回它们。 + +在存储密码之前,您还应该对密码的值进行**哈希**处理,**绝不要以明文形式存储它们**。 + +/// + +`HeroCreate` 的字段包括: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:22] hl[21:22] *} + +#### `HeroUpdate` - 用于更新 hero 的*数据模型* + +在之前的应用程序中,我们没有办法**更新 hero**,但现在有了**多个模型**,我们便能做到这一点了。🎉 + +`HeroUpdate` *数据模型*有些特殊,它包含创建新 hero 所需的**所有相同字段**,但所有字段都是**可选的**(它们都有默认值)。这样,当您更新一个 hero 时,您可以只发送您想要更新的字段。 + +因为所有**字段实际上**都发生了**变化**(类型现在包括 `None` ,并且它们现在有一个默认值 `None` ),我们需要**重新声明**它们。 + +我们会重新声明所有字段,因此我们并不是真的需要从 `HeroBase` 继承。我会让它继承只是为了保持一致,但这并不必要。这更多是个人喜好的问题。🤷 + +`HeroUpdate` 的字段包括: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:28] hl[25:28] *} + +### 使用 `HeroCreate` 创建并返回 `HeroPublic` + +既然我们有了**多个模型**,我们就可以对使用它们的应用程序部分进行更新。 + +我们在请求中接收到一个 `HeroCreate` *数据模型*,然后从中创建一个 `Hero` *表模型*。 + +这个新的*表模型* `Hero` 会包含客户端发送的字段,以及一个由数据库生成的 `id` 。 + +然后我们将与函数中相同的*表模型* `Hero` 原样返回。但是由于我们使用 `HeroPublic` *数据模型*声明了 `response_model` ,**FastAPI** 会使用 `HeroPublic` 来验证和序列化数据。 + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[56:62] hl[56:58] *} + +/// tip + +现在我们使用 `response_model=HeroPublic` 来代替**返回类型注释** `-> HeroPublic` ,因为我们返回的值实际上**并不是** `HeroPublic` 类型。 + +如果我们声明了 `-> HeroPublic` ,您的编辑器和代码检查工具会抱怨(但也确实理所应当)您返回了一个 `Hero` 而不是一个 `HeroPublic` 。 + +通过 `response_model` 的声明,我们让 **FastAPI** 按照它自己的方式处理,而不会干扰类型注解以及编辑器和其他工具提供的帮助。 + +/// + +### 用 `HeroPublic` 读取 Hero + +我们可以像之前一样**读取** `Hero` 。同样,使用 `response_model=list[HeroPublic]` 确保正确地验证和序列化数据。 + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[65:72] hl[65] *} + +### 用 `HeroPublic` 读取单个 Hero + +我们可以**读取**单个 `hero` 。 + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[75:80] hl[77] *} + +### 用 `HeroUpdate` 更新单个 Hero + +我们可以**更新**单个 `hero` 。为此,我们会使用 HTTP 的 `PATCH` 操作。 + +在代码中,我们会得到一个 `dict` ,其中包含客户端发送的所有数据,**只有客户端发送的数据**,并排除了任何一个仅仅作为默认值存在的值。为此,我们使用 `exclude_unset=True` 。这是最主要的技巧。🪄 + +然后我们会使用 `hero_db.sqlmodel_update(hero_data)` ,来利用 `hero_data` 的数据更新 `hero_db` 。 + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[83:93] hl[83:84,88:89] *} + +### (又一次)删除单个 Hero + +**删除**一个 hero 基本保持不变。 + +我们不会满足在这一部分中重构一切的愿望。😅 + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *} + +### (又一次)运行应用程序 + +您可以再运行一次应用程序: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +您会在 `/docs` API UI 看到它现在已经更新,并且在进行创建 hero 等操作时,它不会再期望从客户端接收 `id` 数据。 + +
+ +
+ +## 总结 + +您可以使用 **SQLModel** 与 SQL 数据库进行交互,并通过*数据模型*和*表模型*简化代码。 + +您可以在 SQLModel 的文档中学习到更多内容,其中有一个更详细的关于如何将 SQLModel 与 FastAPI 一起使用的教程。🚀 From 5fc3e9102039290d918465d6409f731d7679cc02 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 15 Dec 2024 17:12:47 +0000 Subject: [PATCH 573/932] =?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 [skip ci] --- 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 8b3e4bc1b..1d0777803 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/tutorial/sql-databases.md`. PR [#13051](https://github.com/fastapi/fastapi/pull/13051) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params-str-validations.md`. PR [#12928](https://github.com/fastapi/fastapi/pull/12928) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Add Chinese translation for `docs/zh/docs/tutorial/header-param-models.md`. PR [#13040](https://github.com/fastapi/fastapi/pull/13040) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/path-params.md`. PR [#12926](https://github.com/fastapi/fastapi/pull/12926) by [@Vincy1230](https://github.com/Vincy1230). From d03ef24c9205dde9f215cb401e3b22e53279b3da Mon Sep 17 00:00:00 2001 From: YungYueh ChanLee Date: Wed, 18 Dec 2024 05:16:46 +0800 Subject: [PATCH 574/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Traditional=20C?= =?UTF-8?q?hinese=20translation=20for=20`docs/zh-hant/docs/tutorial/index.?= =?UTF-8?q?md`=20(#13075)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh-hant/docs/tutorial/index.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/zh-hant/docs/tutorial/index.md b/docs/zh-hant/docs/tutorial/index.md index 2aaa78b22..ae0056f52 100644 --- a/docs/zh-hant/docs/tutorial/index.md +++ b/docs/zh-hant/docs/tutorial/index.md @@ -85,9 +85,9 @@ $ pip install "fastapi[standard]" /// note -當你使用 `pip install "fastapi[standard]"` 安裝時,會包含一些預設的可選標準相依項。 +當你使用 `pip install "fastapi[standard]"` 安裝時,會包含一些預設的可選標準依賴項。 -如果你不想包含那些可選的相依項,你可以使用 `pip install fastapi` 來安裝。 +如果你不想包含那些可選的依賴項,你可以使用 `pip install fastapi` 來安裝。 /// From b19af36826ea9e7e64ba847fc90283c4f5a67dd0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 17 Dec 2024 21:18:25 +0000 Subject: [PATCH 575/932] =?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 [skip ci] --- 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 1d0777803..468e76ab5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/tutorial/index.md`. PR [#13075](https://github.com/fastapi/fastapi/pull/13075) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Chinese translation for `docs/zh/docs/tutorial/sql-databases.md`. PR [#13051](https://github.com/fastapi/fastapi/pull/13051) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params-str-validations.md`. PR [#12928](https://github.com/fastapi/fastapi/pull/12928) by [@Vincy1230](https://github.com/Vincy1230). * 🌐 Add Chinese translation for `docs/zh/docs/tutorial/header-param-models.md`. PR [#13040](https://github.com/fastapi/fastapi/pull/13040) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). From a0f64948034269f76a7f59025f03a4030d172ac7 Mon Sep 17 00:00:00 2001 From: Zhongheng Cheng Date: Tue, 17 Dec 2024 16:18:42 -0500 Subject: [PATCH 576/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/advanced/testing-dependencies.md`?= =?UTF-8?q?=20(#13066)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/advanced/testing-dependencies.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/zh/docs/advanced/testing-dependencies.md b/docs/zh/docs/advanced/testing-dependencies.md index 620539fd1..8d53a6d49 100644 --- a/docs/zh/docs/advanced/testing-dependencies.md +++ b/docs/zh/docs/advanced/testing-dependencies.md @@ -28,7 +28,7 @@ 这样一来,**FastAPI** 就会调用覆盖依赖项,不再调用原依赖项。 -{* ../../docs_src/dependency_testing/tutorial001.py hl[26:27,30] *} +{* ../../docs_src/dependency_testing/tutorial001_an_py310.py hl[26:27,30] *} /// tip | 提示 From dae2b957ba0382f44c206e074e0b2e2dbd3c53f6 Mon Sep 17 00:00:00 2001 From: alv2017 Date: Tue, 17 Dec 2024 23:20:20 +0200 Subject: [PATCH 577/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`/docs/ru/docs/tutorial/sql-databases.md`=20(#13079?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/tutorial/sql-databases.md | 358 +++++++++++++++++++++++++ 1 file changed, 358 insertions(+) create mode 100644 docs/ru/docs/tutorial/sql-databases.md diff --git a/docs/ru/docs/tutorial/sql-databases.md b/docs/ru/docs/tutorial/sql-databases.md new file mode 100644 index 000000000..b127e44d5 --- /dev/null +++ b/docs/ru/docs/tutorial/sql-databases.md @@ -0,0 +1,358 @@ +# SQL (реляционные) базы данных + +**FastAPI** не требует использования реляционной базы данных. Вы можете воспользоваться любой базой данных, которой хотите. + +В этом разделе мы продемонстрируем, как работать с SQLModel. + +Библиотека **SQLModel** построена на основе SQLAlchemy и Pydantic. Она была разработана автором **FastAPI** специально для приложений на основе FastAPI, которые используют **реляционные базы данных**. + +/// tip | Подсказка + +Вы можете воспользоваться любой библиотекой для работы с реляционными (SQL) или нереляционными (NoSQL) базами данных. (Их ещё называют **ORM** библиотеками). FastAPI не принуждает вас к использованию чего-либо конкретного. 😎 + +/// + +В основе SQLModel лежит SQLAlchemy, поэтому вы спокойно можете использовать любую базу данных, поддерживаемую SQLAlchemy (и, соответственно, поддерживаемую SQLModel), например: + +* PostgreSQL +* MySQL +* SQLite +* Oracle +* Microsoft SQL Server, и т.д. + +В данном примере мы будем использовать базу данных **SQLite**, т.к. она состоит из единственного файла и поддерживается встроенными библиотеками Python. Таким образом, вы сможете скопировать данный пример и запустить его как он есть. + +В дальнейшем, для продакшн-версии вашего приложения, возможно, вам стоит использовать серверную базу данных, например, **PostgreSQL**. + +/// tip | Подсказка + +Существует официальный генератор проектов на **FastAPI** и **PostgreSQL**, который также включает frontend и дополнительные инструменты https://github.com/fastapi/full-stack-fastapi-template + +/// + +Это очень простое и короткое руководство, поэтому, если вы хотите узнать о базах данных в целом, об SQL, разобраться с более продвинутым функционалом, то воспользуйтесь документацией SQLModel. + +## Установка `SQLModel` + +Создайте виртуальное окружение [virtual environment](../virtual-environments.md){.internal-link target=_blank}, активируйте его и установите `sqlmodel`: + +
+ +```console +$ pip install sqlmodel +---> 100% +``` + +
+ +## Создание приложения с единственной моделью + +Мы начнем с создания наиболее простой первой версии нашего приложения с одной единственной моделью **SQLModel**. + +В дальнейшем с помощью **дополнительных моделей** мы его улучшим и сделаем более безопасным и универсальным. 🤓 + +### Создание моделей + +Импортируйте `SQLModel` и создайте модель базы данных: + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[1:11] hl[7:11] *} + +Класс `Hero` очень напоминает модель Pydantic (фактически, под капотом, *это и есть модель Pydantic*). + +Но есть и некоторые различия + +* `table=True` для SQLModel означает, что это *модель-таблица*, которая должна представлять **таблицу** в реляционной базе данных. Это не просто *модель данных* (в отличие от обычного класса в Pydantic). + +* `Field(primary_key=True)` для SQLModel означает, что поле `id` является первичным ключом в таблице базы данных (вы можете подробнее узнать о первичных ключах баз данных в документации по SQLModel). + + Тип `int | None` сигнализирует для SQLModel, что столбец таблицы базы данных должен иметь тип `INTEGER`, или иметь пустое значение `NULL`. + +* `Field(index=True)` для SQLModel означает, что нужно создать **SQL индекс** для данного столбца. Это обеспечит более быстрый поиск при чтении данных, отфильтрованных по данному столбцу. + + SQLModel будет знать, что данные типа `str`, будут представлены в базе данных как `TEXT` (или `VARCHAR`, в зависимости от типа базы данных). + +### Создание соединения с базой данных (Engine) + +В SQLModel объект соединения `engine` (по сути это `Engine` из SQLAlchemy) **содержит пул соединений** к базе данных. + +Для обеспечения всех подключений приложения к одной базе данных нужен только один объект соединения `engine`. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[14:18] hl[14:15,17:18] *} + +Использование настройки `check_same_thread=False` позволяет FastAPI использовать одну и ту же SQLite базу данных в различных потоках (threads). Это необходимо, когда **один запрос** использует **более одного потока** (например, в зависимостях). + +Не беспокойтесь, учитывая структуру кода, мы позже позаботимся о том, чтобы использовать **отдельную SQLModel-сессию на каждый отдельный запрос**, это как раз то, что пытается обеспечить `check_same_thread`. + +### Создание таблиц + +Далее мы добавляем функцию, использующую `SQLModel.metadata.create_all(engine)`, для того, чтобы создать **таблицы** для каждой из **моделей таблицы**. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[21:22] hl[21:22] *} + +### Создание зависимости Session + +Сессия базы данных (**`Session`**) хранит **объекты в памяти** и отслеживает любые необходимые изменения в данных, а затем **использует `engine`** для коммуникации с базой данных. + +Мы создадим FastAPI-**зависимость** с помощью `yield`, которая будет создавать новую сессию (Session) для каждого запроса. Это как раз и обеспечит использование отдельной сессии на каждый отдельный запрос. 🤓 + +Затем мы создадим объявленную (`Annotated`) зависимость `SessionDep`. Мы сделаем это для того, чтобы упростить остальной код, который будет использовать эту зависимость. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[25:30] hl[25:27,30] *} + +### Создание таблиц базы данных при запуске приложения + +Мы будем создавать таблицы базы данных при запуске приложения. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[32:37] hl[35:37] *} + +В данном примере мы создаем таблицы при наступлении события запуска приложения. + +В продуктовом приложении вы, скорее всего, будете использовать скрипт для миграции базы данных, который выполняется перед запуском приложения. 🤓 + +/// tip | Подсказка + +В SQLModel будут включены утилиты миграции, входящие в состав Alembic, но на данный момент вы просто можете использовать +Alembic напрямую. + +/// + +### Создание героя (Hero) + +Каждая модель в SQLModel является также моделью Pydantic, поэтому вы можете использовать её при **объявлении типов**, точно также, как и модели Pydantic. + +Например, при объявлении параметра типа `Hero`, она будет считана из **тела JSON**. + +Точно также, вы можете использовать её при объявлении типа значения, возвращаемого функцией, и тогда структурированные данные будут отображены через пользовательский интерфейс автоматически сгенерированной документации FastAPI. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *} + +Мы используем зависимость `SessionDep` (сессию базы данных) для того, чтобы добавить нового героя `Hero` в объект сессии (`Session`), сохранить изменения в базе данных, обновить данные героя и затем вернуть их. + +### Чтение данных о героях + +Мы можем **читать** данные героев из базы данных с помощью `select()`. Мы можем включить `limit` и `offset` для постраничного считывания результатов. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[48:55] hl[51:52,54] *} + +### Чтение данных отдельного героя + +Мы можем прочитать данные отдельного героя (`Hero`). + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[58:63] hl[60] *} + +### Удаление данных героя + +Мы также можем удалить героя `Hero` из базы данных. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[66:73] hl[71] *} + +### Запуск приложения + +Вы можете запустить приложение следующим образом: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Далее перейдите в пользовательский интерфейс API `/docs`. Вы увидите, что **FastAPI** использует модели для создания документации API. Эти же модели используются для сериализации и проверки данных. + +
+ +
+ +## Добавление в приложение дополнительных (вспомогательных) моделей + +Теперь давайте проведём **рефакторинг** нашего приложения, чтобы сделать его более безопасным и более универсальным. + +Обратите внимание, что на данном этапе наше приложение позволяет на уровне клиента определять `id` создаваемого героя (`Hero`). 😱 + +Мы не можем этого допустить, т.к. существует риск переписать уже присвоенные `id` в базе данных. Присвоение `id` должно происходить **на уровне бэкэнда (backend)** или **на уровне базы данных**, но никак **не на уровне клиента**. + +Кроме того, мы создаем секретное имя `secret_name` для героя, но пока что, мы возвращаем его повсеместно, и это слабо напоминает **секретность**... 😅 + +Мы поправим это с помощью нескольких дополнительных (вспомогательных) моделей. Вот где SQLModel по-настоящему покажет себя. ✨ + +### Создание дополнительных моделей + +В **SQLModel**, любая модель с параметром `table=True` является **моделью таблицы**. + +Любая модель, не содержащая `table=True` является **моделью данных**, это по сути обычные модели Pydantic (с несколько расширенным функционалом). 🤓 + +С помощью SQLModel мы можем использовать **наследование**, что поможет нам **избежать дублирования** всех полей. + +#### Базовый класс `HeroBase` + +Давайте начнём с модели `HeroBase`, которая содержит поля, общие для всех моделей: + +* `name` +* `age` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:9] hl[7:9] *} + +#### Модель таблицы `Hero` + +Далее давайте создадим **модель таблицы** `Hero` с дополнительными полями, которых может не быть в других моделях: + +* `id` +* `secret_name` + +Модель `Hero` наследует от `HeroBase`, и поэтому включает также поля из `HeroBase`. Таким образом, все поля, содержащиеся в `Hero`, будут следующими: + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:14] hl[12:14] *} + +#### Публичная модель данных `HeroPublic` + +Далее мы создадим модель `HeroPublic`. Мы будем возвращать её клиентам API. + +Она включает в себя те же поля, что и `HeroBase`, и, соответственно, поле `secret_name` в ней отсутствует. + +Наконец-то личность наших героев защищена! 🥷 + +В модели `HeroPublic` также объявляется поле `id: int`. Мы как бы заключаем договоренность с API клиентом, на то, что передаваемые данные всегда должны содержать поле `id`, и это поле должно содержать целое число (и никогда не содержать `None`). + +/// tip | Подсказка + +Модель ответа, гарантирующая наличие поля со значением типа `int` (не `None`), очень полезна при разработке API клиентов. Определенность в передаваемых данных может обеспечить написание более простого кода. + +Также **автоматически генерируемые клиенты** будут иметь более простой интерфейс. И в результате жизнь разработчиков, использующих ваш API, станет значительно легче. 😎 + +/// + +`HeroPublic` содержит все поля `HeroBase`, а также поле `id`, объявленное как `int` (не `None`): + +* `id` +* `name` +* `age` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *} + +#### Модель для создания героя `HeroCreate` + +Сейчас мы создадим модель `HeroCreate`. Эта модель будет использоваться для проверки данных, переданных клиентом. + +Она содержит те же поля, что и `HeroBase`, а также поле `secret_name`. + +Теперь, при создании нового героя, клиенты будут передавать секретное имя `secret_name`, которое будет сохранено в базе данных, но не будет возвращено в ответе API клиентам. + +/// tip | Подсказка + +Вот как нужно работать с **паролями**: получайте их, но не возвращайте их через API. + +Также хэшируйте значения паролей перед тем, как их сохранить. Ни в коем случае не храните пароли в открытом виде, как обычный текст. + +/// + +Поля модели `HeroCreate`: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:22] hl[21:22] *} + +#### Модель для обновления данных героя `HeroUpdate` + +В предыдущих версиях нашей программы мы не могли обновить данные героя, теперь, воспользовавшись дополнительными моделями, мы сможем это сделать. 🎉 + +Модель данных `HeroUpdate` в некотором смысле особенная. Она содержит все те же поля, что и модель создания героя, но все поля модели являются **необязательными**. (Все они имеют значение по умолчанию.) Таким образом, при обновлении данных героя, вам достаточно передать только те поля, которые требуют изменения. + +Поскольку **все поля по сути меняются** (теперь тип каждого поля допускает значение `None` и значение по умолчанию `None`), мы должны их **объявить заново**. + +Фактически, нам не нужно наследоваться от `HeroBase`, потому что мы будем заново объявлять все поля. Я оставлю наследование просто для поддержания общего стиля, но оно (наследование) здесь необязательно. 🤷 + +Поля `HeroUpdate`: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:28] hl[25:28] *} + +### Создание героя с помощью `HeroCreate` и возвращение результатов с помощью `HeroPublic` + +Теперь, когда у нас есть дополнительные модели, мы можем обновить те части приложения, которые их используют. + +Вместе c запросом на создание героя мы получаем объект данных `HeroCreate`, и создаем на его основе объект модели таблицы `Hero`. + +Созданный объект *модели таблицы* `Hero` будет иметь все поля, переданные клиентом, а также поле `id`, сгенерированное базой данных. + +Далее функция вернёт объект *модели таблицы* `Hero`. Но поскольку, мы объявили `HeroPublic` как модель ответа, то **FastAPI** будет использовать именно её для проверки и сериализации данных. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[56:62] hl[56:58] *} + +/// tip | Подсказка + +Теперь мы используем модель ответа `response_model=HeroPublic`, вместо того, чтобы объявить тип возвращаемого значения как `-> HeroPublic`. Мы это делаем потому, что тип возвращаемого значения не относится к `HeroPublic`. + +Если бы мы объявили тип возвращаемого значения как `-> HeroPublic`, то редактор и линтер начали бы ругаться (и вполне справедливо), что возвращаемое значение принадлежит типу `Hero`, а совсем не `HeroPublic`. + +Объявляя модель ответа в `response_model`, мы как бы говорим **FastAPI**: делай свое дело, не вмешиваясь в аннотацию типов и не полагаясь на помощь редактора или других инструментов. + +/// + +### Чтение данных героев с помощью `HeroPublic` + +Мы можем проделать то же самое **для чтения данных** героев. Мы применим модель ответа `response_model=list[HeroPublic]`, и тем самым обеспечим правильную проверку и сериализацию данных. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[65:72] hl[65] *} + +### Чтение данных отдельного героя с помощью `HeroPublic` + +Мы можем **прочитать** данные отдельного героя: + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[75:80] hl[77] *} + +### Обновление данных героя с помощью `HeroUpdate` + +Мы можем **обновить данные героя**. Для этого мы воспользуемся HTTP методом `PATCH`. + +В коде мы получаем объект словаря `dict` с данными, переданными клиентом (т.е. **только c данными, переданными клиентом**, исключая любые значения, которые могли бы быть там только потому, что они являются значениями по умолчанию). Для того чтобы сделать это, мы воспользуемся опцией `exclude_unset=True`. В этом главная хитрость. 🪄 + +Затем мы применим `hero_db.sqlmodel_update(hero_data)`, и обновим `hero_db`, использовав данные `hero_data`. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[83:93] hl[83:84,88:89] *} + +### Удалим героя ещё раз + +Операция **удаления** героя практически не меняется. + +В данном случае желание *`отрефакторить всё`* остаётся неудовлетворенным. 😅 + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *} + +### Снова запустим приложение + +Вы можете снова запустить приложение: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Если вы перейдете в пользовательский интерфейс API `/docs`, то вы увидите, что он был обновлен, и больше не принимает параметра `id` от клиента при создании нового героя, и т.д. + +
+ +
+ +## Резюме + +Вы можете использовать **SQLModel** для взаимодействия с реляционными базами данных, а также для упрощения работы с **моделями данных** и **моделями таблиц**. + +Вы можете узнать гораздо больше информации в документации по **SQLModel**. Там вы найдете более подробное мини-руководство по использованию SQLModel с **FastAPI**. 🚀 From 52d8ad8bfaf839bb6f0784ec44912d9d49ea842b Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 17 Dec 2024 21:21:10 +0000 Subject: [PATCH 578/932] =?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 [skip ci] --- 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 468e76ab5..3b288f0a2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#13066](https://github.com/fastapi/fastapi/pull/13066) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/tutorial/index.md`. PR [#13075](https://github.com/fastapi/fastapi/pull/13075) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Chinese translation for `docs/zh/docs/tutorial/sql-databases.md`. PR [#13051](https://github.com/fastapi/fastapi/pull/13051) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/query-params-str-validations.md`. PR [#12928](https://github.com/fastapi/fastapi/pull/12928) by [@Vincy1230](https://github.com/Vincy1230). From 0d8e9663d818686c2bcec9d4e2cea0a495d588e6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 17 Dec 2024 21:21:39 +0000 Subject: [PATCH 579/932] =?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 [skip ci] --- 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 3b288f0a2..2ddf8686c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Russian translation for `/docs/ru/docs/tutorial/sql-databases.md`. PR [#13079](https://github.com/fastapi/fastapi/pull/13079) by [@alv2017](https://github.com/alv2017). * 🌐 Update Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#13066](https://github.com/fastapi/fastapi/pull/13066) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/tutorial/index.md`. PR [#13075](https://github.com/fastapi/fastapi/pull/13075) by [@codingjenny](https://github.com/codingjenny). * 🌐 Add Chinese translation for `docs/zh/docs/tutorial/sql-databases.md`. PR [#13051](https://github.com/fastapi/fastapi/pull/13051) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). From a559f8f3971ca27f284dc031f3f4510bbbf5c6e0 Mon Sep 17 00:00:00 2001 From: Zhibang Yue Date: Wed, 18 Dec 2024 05:28:37 +0800 Subject: [PATCH 580/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/advanced/events.md`=20(#12512)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/advanced/events.md | 132 ++++++++++++++++++++++++++++++-- 1 file changed, 125 insertions(+), 7 deletions(-) diff --git a/docs/zh/docs/advanced/events.md b/docs/zh/docs/advanced/events.md index 66f5af2e3..5ade0f0ff 100644 --- a/docs/zh/docs/advanced/events.md +++ b/docs/zh/docs/advanced/events.md @@ -1,16 +1,114 @@ -# 事件:启动 - 关闭 +# 生命周期事件 -**FastAPI** 支持定义在应用启动前,或应用关闭后执行的事件处理器(函数)。 +你可以定义在应用**启动**前执行的逻辑(代码)。这意味着在应用**开始接收请求**之前,这些代码只会被执行**一次**。 -事件函数既可以声明为异步函数(`async def`),也可以声明为普通函数(`def`)。 +同样地,你可以定义在应用**关闭**时应执行的逻辑。在这种情况下,这段代码将在**处理可能的多次请求后**执行**一次**。 + +因为这段代码在应用开始接收请求**之前**执行,也会在处理可能的若干请求**之后**执行,它覆盖了整个应用程序的**生命周期**("生命周期"这个词很重要😉)。 + +这对于设置你需要在整个应用中使用的**资源**非常有用,这些资源在请求之间**共享**,你可能需要在之后进行**释放**。例如,数据库连接池,或加载一个共享的机器学习模型。 + +## 用例 + +让我们从一个示例用例开始,看看如何解决它。 + +假设你有几个**机器学习的模型**,你想要用它们来处理请求。 + +相同的模型在请求之间是共享的,因此并非每个请求或每个用户各自拥有一个模型。 + +假设加载模型可能**需要相当长的时间**,因为它必须从**磁盘**读取大量数据。因此你不希望每个请求都加载它。 + +你可以在模块/文件的顶部加载它,但这也意味着即使你只是在运行一个简单的自动化测试,它也会**加载模型**,这样测试将**变慢**,因为它必须在能够独立运行代码的其他部分之前等待模型加载完成。 + +这就是我们要解决的问题——在处理请求前加载模型,但只是在应用开始接收请求前,而不是代码执行时。 + +## 生命周期 lifespan + +你可以使用`FastAPI()`应用的`lifespan`参数和一个上下文管理器(稍后我将为你展示)来定义**启动**和**关闭**的逻辑。 + +让我们从一个例子开始,然后详细介绍。 + +我们使用`yield`创建了一个异步函数`lifespan()`像这样: + +```Python hl_lines="16 19" +{!../../docs_src/events/tutorial003.py!} +``` + +在这里,我们在 `yield` 之前将(虚拟的)模型函数放入机器学习模型的字典中,以此模拟加载模型的耗时**启动**操作。这段代码将在应用程序**开始处理请求之前**执行,即**启动**期间。 + +然后,在 `yield` 之后,我们卸载模型。这段代码将会在应用程序**完成处理请求后**执行,即在**关闭**之前。这可以释放诸如内存或 GPU 之类的资源。 + +/// tip | 提示 + +**关闭**事件只会在你停止应用时触发。 + +可能你需要启动一个新版本,或者你只是你厌倦了运行它。 🤷 + +/// + +## 生命周期函数 + +首先要注意的是,我们定义了一个带有 `yield` 的异步函数。这与带有 `yield` 的依赖项非常相似。 + +```Python hl_lines="14-19" +{!../../docs_src/events/tutorial003.py!} +``` + +这个函数在 `yield`之前的部分,会在应用启动前执行。 + +剩下的部分在 `yield` 之后,会在应用完成后执行。 + +## 异步上下文管理器 + +如你所见,这个函数有一个装饰器 `@asynccontextmanager` 。 + +它将函数转化为所谓的“**异步上下文管理器**”。 + +```Python hl_lines="1 13" +{!../../docs_src/events/tutorial003.py!} +``` + +在 Python 中, **上下文管理器**是一个你可以在 `with` 语句中使用的东西,例如,`open()` 可以作为上下文管理器使用。 + +```Python +with open("file.txt") as file: + file.read() +``` + +Python 的最近几个版本也有了一个**异步上下文管理器**,你可以通过 `async with` 来使用: + +```Python +async with lifespan(app): + await do_stuff() +``` + +你可以像上面一样创建了一个上下文管理器或者异步上下文管理器,它的作用是在进入 `with` 块时,执行 `yield` 之前的代码,并且在离开 `with` 块时,执行 `yield` 后面的代码。 + +但在我们上面的例子里,我们并不是直接使用,而是传递给 FastAPI 来供其使用。 + +`FastAPI()` 的 `lifespan` 参数接受一个**异步上下文管理器**,所以我们可以把我们新定义的上下文管理器 `lifespan` 传给它。 + +```Python hl_lines="22" +{!../../docs_src/events/tutorial003.py!} +``` + +## 替代事件(弃用) /// warning | 警告 -**FastAPI** 只执行主应用中的事件处理器,不执行[子应用 - 挂载](sub-applications.md){.internal-link target=_blank}中的事件处理器。 +配置**启动**和**关闭**事件的推荐方法是使用 `FastAPI()` 应用的 `lifespan` 参数,如前所示。如果你提供了一个 `lifespan` 参数,启动(`startup`)和关闭(`shutdown`)事件处理器将不再生效。要么使用 `lifespan`,要么配置所有事件,两者不能共用。 + +你可以跳过这一部分。 /// -## `startup` 事件 +有一种替代方法可以定义在**启动**和**关闭**期间执行的逻辑。 + +**FastAPI** 支持定义在应用启动前,或应用关闭时执行的事件处理器(函数)。 + +事件函数既可以声明为异步函数(`async def`),也可以声明为普通函数(`def`)。 + +### `startup` 事件 使用 `startup` 事件声明 `app` 启动前运行的函数: @@ -22,7 +120,7 @@ 只有所有 `startup` 事件处理器运行完毕,**FastAPI** 应用才开始接收请求。 -## `shutdown` 事件 +### `shutdown` 事件 使用 `shutdown` 事件声明 `app` 关闭时运行的函数: @@ -48,8 +146,28 @@ /// +### `startup` 和 `shutdown` 一起使用 + +启动和关闭的逻辑很可能是连接在一起的,你可能希望启动某个东西然后结束它,获取一个资源然后释放它等等。 + +在不共享逻辑或变量的不同函数中处理这些逻辑比较困难,因为你需要在全局变量中存储值或使用类似的方式。 + +因此,推荐使用 `lifespan` 。 + +## 技术细节 + +只是为好奇者提供的技术细节。🤓 + +在底层,这部分是生命周期协议的一部分,参见 ASGI 技术规范,定义了称为启动(`startup`)和关闭(`shutdown`)的事件。 + /// info | 说明 -有关事件处理器的详情,请参阅 Starlette 官档 - 事件。 +有关事件处理器的详情,请参阅 Starlette 官档 - 事件。 + +包括如何处理生命周期状态,这可以用于程序的其他部分。 /// + +## 子应用 + +🚨 **FastAPI** 只会触发主应用中的生命周期事件,不包括[子应用 - 挂载](sub-applications.md){.internal-link target=_blank}中的。 From 334c9bc7ad1a7c15db633352495a2a72f3d73b04 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 17 Dec 2024 21:29:01 +0000 Subject: [PATCH 581/932] =?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 [skip ci] --- 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 2ddf8686c..aab6c6334 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/events.md`. PR [#12512](https://github.com/fastapi/fastapi/pull/12512) by [@ZhibangYue](https://github.com/ZhibangYue). * 🌐 Add Russian translation for `/docs/ru/docs/tutorial/sql-databases.md`. PR [#13079](https://github.com/fastapi/fastapi/pull/13079) by [@alv2017](https://github.com/alv2017). * 🌐 Update Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#13066](https://github.com/fastapi/fastapi/pull/13066) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Update Traditional Chinese translation for `docs/zh-hant/docs/tutorial/index.md`. PR [#13075](https://github.com/fastapi/fastapi/pull/13075) by [@codingjenny](https://github.com/codingjenny). From 2b788666628475b708df990552beeca201f9b9f6 Mon Sep 17 00:00:00 2001 From: Yarema Kertytsky <83857001+ykertytsky@users.noreply.github.com> Date: Tue, 17 Dec 2024 23:33:34 +0200 Subject: [PATCH 582/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/fastapi-cli.md`=20(#13020)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/uk/docs/fastapi-cli.md | 83 +++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 docs/uk/docs/fastapi-cli.md diff --git a/docs/uk/docs/fastapi-cli.md b/docs/uk/docs/fastapi-cli.md new file mode 100644 index 000000000..6bbbbc326 --- /dev/null +++ b/docs/uk/docs/fastapi-cli.md @@ -0,0 +1,83 @@ +# FastAPI CLI + +**FastAPI CLI** це програма командного рядка, яку Ви можете використовувати, щоб обслуговувати Ваш додаток FastAPI, керувати Вашими 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** використовує Uvicorn, високопродуктивний, production-ready, ASGI cервер. 😎 + +## `fastapi dev` + +Використання `fastapi dev` ініціює режим розробки. + +За замовчуванням, **автоматичне перезавантаження** увімкнене, автоматично перезавантажуючи сервер кожного разу, коли Ви змінюєте Ваш код. Це ресурсо-затратно, та може бути менш стабільним, ніж коли воно вимкнене. Ви повинні використовувати його тільки під час розробки. Воно також слухає IP-адресу `127.0.0.1`, що є IP Вашого девайсу для самостійної комунікації з самим собою (`localhost`). + +## `fastapi run` + +Виконання `fastapi run` запустить FastAPI у продакшн-режимі за замовчуванням. + +За замовчуванням, **автоматичне перезавантаження** вимкнене. Воно також прослуховує IP-адресу `0.0.0.0`, що означає всі доступні IP адреси, тим самим даючи змогу будь-кому комунікувати з девайсом. Так Ви зазвичай будете запускати його у продакшн, наприклад у контейнері. + +В більшості випадків Ви можете (і маєте) мати "termination proxy", який обробляє HTTPS для Вас, це залежить від способу розгортання вашого додатку, Ваш провайдер може зробити це для Вас, або Вам потрібно налаштувати його самостійно. + +/// tip + +Ви можете дізнатись більше про це у [документації про розгортування](deployment/index.md){.internal-link target=_blank}. + +/// From 3ca5fe1709cd899f3f0f69b72e62681f075a3969 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 17 Dec 2024 21:34:01 +0000 Subject: [PATCH 583/932] =?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 [skip ci] --- 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 aab6c6334..c3bacaf12 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/fastapi-cli.md`. PR [#13020](https://github.com/fastapi/fastapi/pull/13020) by [@ykertytsky](https://github.com/ykertytsky). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/events.md`. PR [#12512](https://github.com/fastapi/fastapi/pull/12512) by [@ZhibangYue](https://github.com/ZhibangYue). * 🌐 Add Russian translation for `/docs/ru/docs/tutorial/sql-databases.md`. PR [#13079](https://github.com/fastapi/fastapi/pull/13079) by [@alv2017](https://github.com/alv2017). * 🌐 Update Chinese translation for `docs/zh/docs/advanced/testing-dependencies.md`. PR [#13066](https://github.com/fastapi/fastapi/pull/13066) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). From a9f63e5d222795cdd7ab853997916fb662551761 Mon Sep 17 00:00:00 2001 From: Zhongheng Cheng Date: Tue, 17 Dec 2024 16:49:06 -0500 Subject: [PATCH 584/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/advanced/async-tests.md`=20(#13074)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/advanced/async-tests.md | 99 ++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 docs/zh/docs/advanced/async-tests.md diff --git a/docs/zh/docs/advanced/async-tests.md b/docs/zh/docs/advanced/async-tests.md new file mode 100644 index 000000000..b5ac15b5b --- /dev/null +++ b/docs/zh/docs/advanced/async-tests.md @@ -0,0 +1,99 @@ +# 异步测试 + +您已经了解了如何使用 `TestClient` 测试 **FastAPI** 应用程序。但是到目前为止,您只了解了如何编写同步测试,而没有使用 `async` 异步函数。 + +在测试中能够使用异步函数可能会很有用,比如当您需要异步查询数据库的时候。想象一下,您想要测试向 FastAPI 应用程序发送请求,然后验证您的后端是否成功在数据库中写入了正确的数据,与此同时您使用了异步的数据库的库。 + +让我们看看如何才能实现这一点。 + +## pytest.mark.anyio + +如果我们想在测试中调用异步函数,那么我们的测试函数必须是异步的。 AnyIO 为此提供了一个简洁的插件,它允许我们指定一些测试函数要异步调用。 + +## HTTPX + +即使您的 **FastAPI** 应用程序使用普通的 `def` 函数而不是 `async def` ,它本质上仍是一个 `async` 异步应用程序。 + +`TestClient` 在内部通过一些“魔法”操作,使得您可以在普通的 `def` 测试函数中调用异步的 FastAPI 应用程序,并使用标准的 pytest。但当我们在异步函数中使用它时,这种“魔法”就不再生效了。由于测试以异步方式运行,我们无法在测试函数中继续使用 `TestClient`。 + +`TestClient` 是基于 HTTPX 的。幸运的是,我们可以直接使用它来测试API。 + +## 示例 + +举个简单的例子,让我们来看一个[更大的应用](../tutorial/bigger-applications.md){.internal-link target=_blank}和[测试](../tutorial/testing.md){.internal-link target=_blank}中描述的类似文件结构: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +文件 `main.py` 将包含: + +{* ../../docs_src/async_tests/main.py *} + +文件 `test_main.py` 将包含针对 `main.py` 的测试,现在它可能看起来如下: + +{* ../../docs_src/async_tests/test_main.py *} + +## 运行测试 + +您可以通过以下方式照常运行测试: + +
+ +```console +$ pytest + +---> 100% +``` + +
+ +## 详细说明 + +这个标记 `@pytest.mark.anyio` 会告诉 pytest 该测试函数应该被异步调用: + +{* ../../docs_src/async_tests/test_main.py hl[7] *} + +/// tip + +请注意,测试函数现在用的是 `async def`,而不是像以前使用 `TestClient` 时那样只是 `def` 。 + +/// + +我们现在可以使用应用程序创建一个 `AsyncClient` ,并使用 `await` 向其发送异步请求。 + +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} + +这相当于: + +```Python +response = client.get('/') +``` + +我们曾经通过它向 `TestClient` 发出请求。 + +/// tip + +请注意,我们正在将 async/await 与新的 `AsyncClient` 一起使用——请求是异步的。 + +/// + +/// warning + +如果您的应用程序依赖于生命周期事件, `AsyncClient` 将不会触发这些事件。为了确保它们被触发,请使用 florimondmanca/asgi-lifespan 中的 `LifespanManager` 。 + +/// + +## 其他异步函数调用 + +由于测试函数现在是异步的,因此除了在测试中向 FastAPI 应用程序发送请求之外,您现在还可以调用(和使用 `await` 等待)其他 `async` 异步函数,就和您在代码中的其他任何地方调用它们的方法一样。 + +/// tip + +如果您在测试程序中集成异步函数调用的时候遇到一个 `RuntimeError: Task attached to a different loop` 的报错(例如,使用 MongoDB 的 MotorClient 时),请记住,只能在异步函数中实例化需要事件循环的对象,例如通过 `'@app.on_event("startup")` 回调函数进行初始化。 + +/// From 986d363a3810f0b7c19228b58f2389a02eae477c Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 17 Dec 2024 21:49:28 +0000 Subject: [PATCH 585/932] =?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 [skip ci] --- 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 c3bacaf12..e8cb60b40 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/async-tests.md`. PR [#13074](https://github.com/fastapi/fastapi/pull/13074) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Add Ukrainian translation for `docs/uk/docs/fastapi-cli.md`. PR [#13020](https://github.com/fastapi/fastapi/pull/13020) by [@ykertytsky](https://github.com/ykertytsky). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/events.md`. PR [#12512](https://github.com/fastapi/fastapi/pull/12512) by [@ZhibangYue](https://github.com/ZhibangYue). * 🌐 Add Russian translation for `/docs/ru/docs/tutorial/sql-databases.md`. PR [#13079](https://github.com/fastapi/fastapi/pull/13079) by [@alv2017](https://github.com/alv2017). From c015245676b84685922fd2969d670ec472347c60 Mon Sep 17 00:00:00 2001 From: Zhongheng Cheng Date: Thu, 19 Dec 2024 10:30:38 -0500 Subject: [PATCH 586/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/advanced/openapi-webhooks.md`=20(#130?= =?UTF-8?q?91)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/advanced/openapi-webhooks.md | 55 +++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 docs/zh/docs/advanced/openapi-webhooks.md diff --git a/docs/zh/docs/advanced/openapi-webhooks.md b/docs/zh/docs/advanced/openapi-webhooks.md new file mode 100644 index 000000000..92ae8db15 --- /dev/null +++ b/docs/zh/docs/advanced/openapi-webhooks.md @@ -0,0 +1,55 @@ +# OpenAPI 网络钩子 + +有些情况下,您可能想告诉您的 API **用户**,您的应用程序可以携带一些数据调用*他们的*应用程序(给它们发送请求),通常是为了**通知**某种**事件**。 + +这意味着,除了您的用户向您的 API 发送请求的一般情况,**您的 API**(或您的应用)也可以向**他们的系统**(他们的 API、他们的应用)**发送请求**。 + +这通常被称为**网络钩子**(Webhook)。 + +## 使用网络钩子的步骤 + +通常的过程是**您**在代码中**定义**要发送的消息,即**请求的主体**。 + +您还需要以某种方式定义您的应用程序将在**何时**发送这些请求或事件。 + +**用户**会以某种方式(例如在某个网页仪表板上)定义您的应用程序发送这些请求应该使用的 **URL**。 + +所有关于注册网络钩子的 URL 的**逻辑**以及发送这些请求的实际代码都由您决定。您可以在**自己的代码**中以任何想要的方式来编写它。 + +## 使用 `FastAPI` 和 OpenAPI 文档化网络钩子 + +使用 **FastAPI**,您可以利用 OpenAPI 来自定义这些网络钩子的名称、您的应用可以发送的 HTTP 操作类型(例如 `POST`、`PUT` 等)以及您的应用将发送的**请求体**。 + +这能让您的用户更轻松地**实现他们的 API** 来接收您的**网络钩子**请求,他们甚至可能能够自动生成一些自己的 API 代码。 + +/// info + +网络钩子在 OpenAPI 3.1.0 及以上版本中可用,FastAPI `0.99.0` 及以上版本支持。 + +/// + +## 带有网络钩子的应用程序 + +当您创建一个 **FastAPI** 应用程序时,有一个 `webhooks` 属性可以用来定义网络钩子,方式与您定义*路径操作*的时候相同,例如使用 `@app.webhooks.post()` 。 + +{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *} + +您定义的网络钩子将被包含在 `OpenAPI` 的架构中,并出现在自动生成的**文档 UI** 中。 + +/// info + +`app.webhooks` 对象实际上只是一个 `APIRouter` ,与您在使用多个文件来构建应用程序时所使用的类型相同。 + +/// + +请注意,使用网络钩子时,您实际上并没有声明一个*路径*(比如 `/items/` ),您传递的文本只是这个网络钩子的**标识符**(事件的名称)。例如在 `@app.webhooks.post("new-subscription")` 中,网络钩子的名称是 `new-subscription` 。 + +这是因为我们预计**您的用户**会以其他方式(例如通过网页仪表板)来定义他们希望接收网络钩子的请求的实际 **URL 路径**。 + +### 查看文档 + +现在您可以启动您的应用程序并访问 http://127.0.0.1:8000/docs. + +您会看到您的文档不仅有正常的*路径操作*显示,现在还多了一些**网络钩子**: + + From d041f12331081110a2098d7ba9ecac4de55b1661 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 19 Dec 2024 15:31:03 +0000 Subject: [PATCH 587/932] =?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 [skip ci] --- 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 e8cb60b40..d9b43c725 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/openapi-webhooks.md`. PR [#13091](https://github.com/fastapi/fastapi/pull/13091) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/async-tests.md`. PR [#13074](https://github.com/fastapi/fastapi/pull/13074) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Add Ukrainian translation for `docs/uk/docs/fastapi-cli.md`. PR [#13020](https://github.com/fastapi/fastapi/pull/13020) by [@ykertytsky](https://github.com/ykertytsky). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/events.md`. PR [#12512](https://github.com/fastapi/fastapi/pull/12512) by [@ZhibangYue](https://github.com/ZhibangYue). From e779069c92da8b3dafd8d1c9aeef2cc3317e3f57 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 20 Dec 2024 21:15:54 +0000 Subject: [PATCH 588/932] =?UTF-8?q?=E2=AC=86=20Bump=20astral-sh/setup-uv?= =?UTF-8?q?=20from=204=20to=205=20(#13096)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv) from 4 to 5. - [Release notes](https://github.com/astral-sh/setup-uv/releases) - [Commits](https://github.com/astral-sh/setup-uv/compare/v4...v5) --- updated-dependencies: - dependency-name: astral-sh/setup-uv dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/build-docs.yml | 4 ++-- .github/workflows/deploy-docs.yml | 2 +- .github/workflows/label-approved.yml | 2 +- .github/workflows/notify-translations.yml | 2 +- .github/workflows/smokeshow.yml | 2 +- .github/workflows/test.yml | 6 +++--- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index 36d3780ac..6ecdf487c 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -53,7 +53,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v4 + uses: astral-sh/setup-uv@v5 with: version: "0.4.15" enable-cache: true @@ -95,7 +95,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v4 + uses: astral-sh/setup-uv@v5 with: version: "0.4.15" enable-cache: true diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 648539d47..d9ed61910 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -29,7 +29,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v4 + uses: astral-sh/setup-uv@v5 with: version: "0.4.15" enable-cache: true diff --git a/.github/workflows/label-approved.yml b/.github/workflows/label-approved.yml index 7ecb65547..02070146c 100644 --- a/.github/workflows/label-approved.yml +++ b/.github/workflows/label-approved.yml @@ -26,7 +26,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v4 + uses: astral-sh/setup-uv@v5 with: version: "0.4.15" enable-cache: true diff --git a/.github/workflows/notify-translations.yml b/.github/workflows/notify-translations.yml index edf3e838f..187322bca 100644 --- a/.github/workflows/notify-translations.yml +++ b/.github/workflows/notify-translations.yml @@ -35,7 +35,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v4 + uses: astral-sh/setup-uv@v5 with: version: "0.4.15" enable-cache: true diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index 51e5f56fd..ba505985d 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -26,7 +26,7 @@ jobs: with: python-version: '3.9' - name: Setup uv - uses: astral-sh/setup-uv@v4 + uses: astral-sh/setup-uv@v5 with: version: "0.4.15" enable-cache: true diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0c87d8ed3..e0daf7472 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -29,7 +29,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v4 + uses: astral-sh/setup-uv@v5 with: version: "0.4.15" enable-cache: true @@ -66,7 +66,7 @@ jobs: with: python-version: ${{ matrix.python-version }} - name: Setup uv - uses: astral-sh/setup-uv@v4 + uses: astral-sh/setup-uv@v5 with: version: "0.4.15" enable-cache: true @@ -107,7 +107,7 @@ jobs: with: python-version: '3.8' - name: Setup uv - uses: astral-sh/setup-uv@v4 + uses: astral-sh/setup-uv@v5 with: version: "0.4.15" enable-cache: true From dd0b335052619ab5f28749d720aa00a061d6dcce Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 20 Dec 2024 21:16:17 +0000 Subject: [PATCH 589/932] =?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 [skip ci] --- 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 d9b43c725..b28ee5685 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -53,6 +53,7 @@ hide: ### Internal +* ⬆ Bump astral-sh/setup-uv from 4 to 5. PR [#13096](https://github.com/fastapi/fastapi/pull/13096) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Update sponsors: rename CryptAPI to BlockBee. PR [#13078](https://github.com/fastapi/fastapi/pull/13078) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump pypa/gh-action-pypi-publish from 1.12.2 to 1.12.3. PR [#13055](https://github.com/fastapi/fastapi/pull/13055) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump types-ujson from 5.7.0.1 to 5.10.0.20240515. PR [#13018](https://github.com/fastapi/fastapi/pull/13018) by [@dependabot[bot]](https://github.com/apps/dependabot). From f2986a1d53543b4a229f00930cd5f074f2ff33ad Mon Sep 17 00:00:00 2001 From: Zhongheng Cheng Date: Mon, 23 Dec 2024 16:53:06 -0500 Subject: [PATCH 590/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/async.md`=20(#13095)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/async.md | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/docs/zh/docs/async.md b/docs/zh/docs/async.md index 822ceeee4..9e6962eb1 100644 --- a/docs/zh/docs/async.md +++ b/docs/zh/docs/async.md @@ -251,7 +251,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和 这与 **FastAPI** 的性能水平相同。 -您可以同时拥有并行性和异步性,您可以获得比大多数经过测试的 NodeJS 框架更高的性能,并且与 Go 不相上下, Go 是一种更接近于 C 的编译语言(全部归功于 Starlette)。 +你可以同时拥有并行性和异步性,你可以获得比大多数经过测试的 NodeJS 框架更高的性能,并且与 Go 不相上下, Go 是一种更接近于 C 的编译语言(全部归功于 Starlette)。 ### 并发比并行好吗? @@ -275,7 +275,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和 但在这种情况下,如果你能带上 8 名前收银员/厨师,现在是清洁工一起清扫,他们中的每一个人(加上你)都能占据房子的一个区域来清扫,你就可以在额外的帮助下并行的更快地完成所有工作。 -在这个场景中,每个清洁工(包括您)都将是一个处理器,完成这个工作的一部分。 +在这个场景中,每个清洁工(包括你)都将是一个处理器,完成这个工作的一部分。 由于大多数执行时间是由实际工作(而不是等待)占用的,并且计算机中的工作是由 CPU 完成的,所以他们称这些问题为"CPU 密集型"。 @@ -292,9 +292,9 @@ CPU 密集型操作的常见示例是需要复杂的数学处理。 ### 并发 + 并行: Web + 机器学习 -使用 **FastAPI**,您可以利用 Web 开发中常见的并发机制的优势(NodeJS 的主要吸引力)。 +使用 **FastAPI**,你可以利用 Web 开发中常见的并发机制的优势(NodeJS 的主要吸引力)。 -并且,您也可以利用并行和多进程(让多个进程并行运行)的优点来处理与机器学习系统中类似的 **CPU 密集型** 工作。 +并且,你也可以利用并行和多进程(让多个进程并行运行)的优点来处理与机器学习系统中类似的 **CPU 密集型** 工作。 这一点,再加上 Python 是**数据科学**、机器学习(尤其是深度学习)的主要语言这一简单事实,使得 **FastAPI** 与数据科学/机器学习 Web API 和应用程序(以及其他许多应用程序)非常匹配。 @@ -304,7 +304,7 @@ CPU 密集型操作的常见示例是需要复杂的数学处理。 现代版本的 Python 有一种非常直观的方式来定义异步代码。这使它看起来就像正常的"顺序"代码,并在适当的时候"等待"。 -当有一个操作需要等待才能给出结果,且支持这个新的 Python 特性时,您可以编写如下代码: +当有一个操作需要等待才能给出结果,且支持这个新的 Python 特性时,你可以编写如下代码: ```Python burgers = await get_burgers(2) @@ -340,7 +340,7 @@ burgers = get_burgers(2) --- -因此,如果您使用的库告诉您可以使用 `await` 调用它,则需要使用 `async def` 创建路径操作函数 ,如: +因此,如果你使用的库告诉你可以使用 `await` 调用它,则需要使用 `async def` 创建路径操作函数 ,如: ```Python hl_lines="2-3" @app.get('/burgers') @@ -351,15 +351,15 @@ async def read_burgers(): ### 更多技术细节 -您可能已经注意到,`await` 只能在 `async def` 定义的函数内部使用。 +你可能已经注意到,`await` 只能在 `async def` 定义的函数内部使用。 但与此同时,必须"等待"通过 `async def` 定义的函数。因此,带 `async def` 的函数也只能在 `async def` 定义的函数内部调用。 那么,这关于先有鸡还是先有蛋的问题,如何调用第一个 `async` 函数? -如果您使用 **FastAPI**,你不必担心这一点,因为"第一个"函数将是你的路径操作函数,FastAPI 将知道如何做正确的事情。 +如果你使用 **FastAPI**,你不必担心这一点,因为"第一个"函数将是你的路径操作函数,FastAPI 将知道如何做正确的事情。 -但如果您想在没有 FastAPI 的情况下使用 `async` / `await`,则可以这样做。 +但如果你想在没有 FastAPI 的情况下使用 `async` / `await`,则可以这样做。 ### 编写自己的异步代码 @@ -367,7 +367,9 @@ Starlette (和 **FastAPI**) 是基于 AnyIO 来处理高级的并发用例,这些用例需要在自己的代码中使用更高级的模式。 -即使您没有使用 **FastAPI**,您也可以使用 AnyIO 编写自己的异步程序,使其拥有较高的兼容性并获得一些好处(例如, 结构化并发)。 +即使你没有使用 **FastAPI**,你也可以使用 AnyIO 编写自己的异步程序,使其拥有较高的兼容性并获得一些好处(例如, 结构化并发)。 + +我(指原作者 —— 译者注)基于 AnyIO 新建了一个库,作为一个轻量级的封装层,用来优化类型注解,同时提供了更好的**自动补全**、**内联错误提示**等功能。这个库还附带了一个友好的入门指南和教程,能帮助你**理解**并编写**自己的异步代码**:Asyncer。如果你有**结合使用异步代码和常规**(阻塞/同步)代码的需求,这个库会特别有用。 ### 其他形式的异步代码 @@ -407,7 +409,7 @@ Starlette (和 **FastAPI**) 是基于 I/O 的代码。 +如果你使用过另一个不以上述方式工作的异步框架,并且你习惯于用普通的 `def` 定义普通的仅计算路径操作函数,以获得微小的性能增益(大约100纳秒),请注意,在 FastAPI 中,效果将完全相反。在这些情况下,最好使用 `async def`,除非路径操作函数内使用执行阻塞 I/O 的代码。 -在这两种情况下,与您之前的框架相比,**FastAPI** 可能[仍然很快](index.md#_11){.internal-link target=_blank}。 +在这两种情况下,与你之前的框架相比,**FastAPI** 可能[仍然很快](index.md#_11){.internal-link target=_blank}。 ### 依赖 @@ -429,9 +431,9 @@ Starlette (和 **FastAPI**) 是基于 赶时间吗?. +否则,你最好应该遵守的指导原则赶时间吗?. From b9a27be0d44ddcfafd93eae42750ea4d55c4c488 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 23 Dec 2024 21:53:32 +0000 Subject: [PATCH 591/932] =?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 [skip ci] --- 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 b28ee5685..18e270aae 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/async.md`. PR [#13095](https://github.com/fastapi/fastapi/pull/13095) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/openapi-webhooks.md`. PR [#13091](https://github.com/fastapi/fastapi/pull/13091) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/async-tests.md`. PR [#13074](https://github.com/fastapi/fastapi/pull/13074) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Add Ukrainian translation for `docs/uk/docs/fastapi-cli.md`. PR [#13020](https://github.com/fastapi/fastapi/pull/13020) by [@ykertytsky](https://github.com/ykertytsky). From eece6344f5d7e24d19de217ab74804577fdce8eb Mon Sep 17 00:00:00 2001 From: Geumbin <107880480+GeumBinLee@users.noreply.github.com> Date: Wed, 25 Dec 2024 01:14:29 +0900 Subject: [PATCH 592/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/tutorial/sql-databases.md`=20(#13093)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/tutorial/sql-databases.md | 360 +++++++++++++++++++++++++ 1 file changed, 360 insertions(+) create mode 100644 docs/ko/docs/tutorial/sql-databases.md diff --git a/docs/ko/docs/tutorial/sql-databases.md b/docs/ko/docs/tutorial/sql-databases.md new file mode 100644 index 000000000..58c7017d6 --- /dev/null +++ b/docs/ko/docs/tutorial/sql-databases.md @@ -0,0 +1,360 @@ +# SQL (관계형) 데이터베이스 + +**FastAPI**에서 SQL(관계형) 데이터베이스 사용은 필수가 아닙니다. 여러분이 원하는 **어떤 데이터베이스든** 사용할 수 있습니다. + +여기서는 SQLModel을 사용하는 예제를 살펴보겠습니다. + +**SQLModel**은 SQLAlchemy와 Pydantic을 기반으로 구축되었습니다.SQLModel은 **SQL 데이터베이스**를 사용하는 FastAPI 애플리케이션에 완벽히 어울리도록 **FastAPI**의 제작자가 설계한 도구입니다. + +/// tip | 팁 + +다른 SQL 또는 NoSQL 데이터베이스 라이브러리를 사용할 수도 있습니다 (일부는 "ORM"이라고도 불립니다), FastAPI는 특정 라이브러리의 사용을 강요하지 않습니다. 😎 + +/// + +SQLModel은 SQLAlchemy를 기반으로 하므로, SQLAlchemy에서 **지원하는 모든 데이터베이스**를 손쉽게 사용할 수 있습니다(SQLModel에서도 동일하게 지원됩니다). 예를 들면: + +* PostgreSQL +* MySQL +* SQLite +* Oracle +* Microsoft SQL Server 등. + +이 예제에서는 **SQLite**를 사용합니다. SQLite는 단일 파일을 사용하고 파이썬에서 기본적으로 지원하기 때문입니다. 따라서 이 예제를 그대로 복사하여 실행할 수 있습니다. + +나중에 실제 프로덕션 애플리케이션에서는 **PostgreSQL**과 같은 데이터베이스 서버를 사용하는 것이 좋습니다. + +/// tip | 팁 + +**FastAPI**와 **PostgreSQL**를 포함하여 프론트엔드와 다양한 도구를 제공하는 공식 프로젝트 생성기가 있습니다: https://github.com/fastapi/full-stack-fastapi-template + +/// + +이 튜토리얼은 매우 간단하고 짧습니다. 데이터베이스 기본 개념, SQL, 또는 더 복잡한 기능에 대해 배우고 싶다면, SQLModel 문서를 참고하세요. + +## `SQLModel` 설치하기 + +먼저, [가상 환경](../virtual-environments.md){.internal-link target=_blank}을 생성하고 활성화한 다음, `sqlmodel`을 설치하세요: + +
+ +```console +$ pip install sqlmodel +---> 100% +``` + +
+ +## 단일 모델로 애플리케이션 생성하기 + +우선 단일 **SQLModel** 모델을 사용하여 애플리케이션의 가장 간단한 첫 번째 버전을 생성해보겠습니다. + +이후 **다중 모델**을 추가하여 보안과 유연성을 강화할 것입니다. 🤓 + +### 모델 생성하기 + +`SQLModel`을 가져오고 데이터베이스 모델을 생성합니다: + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[1:11] hl[7:11] *} + +`Hero` 클래스는 Pydantic 모델과 매우 유사합니다 (실제로 내부적으로 *Pydantic 모델이기도 합니다*). + +몇 가지 차이점이 있습니다: + +* `table=True`는 SQLModel에 이 모델이 *테이블 모델*이며, 단순한 데이터 모델이 아니라 SQL 데이터베이스의 **테이블**을 나타낸다는 것을 알려줍니다. (다른 일반적인 Pydantic 클래스처럼) 단순한 *데이터 모델*이 아닙니다. + +* `Field(primary_key=True)`는 SQLModel에 `id`가 SQL 데이터베이스의 **기본 키**임을 알려줍니다 (SQL 기본 키에 대한 자세한 내용은 SQLModel 문서를 참고하세요). + + `int | None` 유형으로 설정하면, SQLModel은 해당 열이 SQL 데이터베이스에서 `INTEGER` 유형이며 `NULLABLE` 값이어야 한다는 것을 알 수 있습니다. + +* `Field(index=True)`는 SQLModel에 해당 열에 대해 **SQL 인덱스**를 생성하도록 지시합니다. 이를 통해 데이터베이스에서 이 열으로 필터링된 데이터를 읽을 때 더 빠르게 조회할 수 있습니다. + + SQLModel은 `str`으로 선언된 항목이 SQL 데이터베이스에서 `TEXT` (또는 데이터베이스에 따라 `VARCHAR`) 유형의 열로 저장된다는 것을 인식합니다. + +### 엔진 생성하기 + +SQLModel의 `engine` (내부적으로는 SQLAlchemy `engine`)은 데이터베이스에 대한 **연결을 유지**하는 역할을 합니다. + +**하나의 단일 engine 객체**를 통해 코드 전체에서 동일한 데이터베이스에 연결할 수 있습니다. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[14:18] hl[14:15,17:18] *} + +`check_same_thread=False`를 사용하면 FastAPI에서 여러 스레드에서 동일한 SQLite 데이터베이스를 사용할 수 있습니다. 이는 **하나의 단일 요청**이 **여러 스레드**를 사용할 수 있기 때문에 필요합니다(예: 의존성에서 사용되는 경우). + +걱정하지 마세요. 코드가 구조화된 방식으로 인해, 이후에 **각 요청마다 단일 SQLModel *세션*을 사용**하도록 보장할 것입니다. 실제로 그것이 `check_same_thread`가 하려는 것입니다. + +### 테이블 생성하기 + +그 다음 `SQLModel.metadata.create_all(engine)`을 사용하여 모든 *테이블 모델*의 **테이블을 생성**하는 함수를 추가합니다. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[21:22] hl[21:22] *} + +### 세션 의존성 생성하기 + +**`Session`**은 **메모리에 객체**를 저장하고 데이터에 필요한 모든 변경 사항을 추적한 후, **`engine`을 통해** 데이터베이스와 통신합니다. + +`yield`를 사용해 FastAPI의 **의존성**을 생성하여 각 요청마다 새로운 `Session`을 제공합니다. 이는 요청당 하나의 세션만 사용되도록 보장합니다. 🤓 + +그런 다음 이 의존성을 사용하는 코드를 간소화하기 위해 `Annotated` 의존성 `SessionDep`을 생성합니다. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[25:30] hl[25:27,30] *} + +### 시작 시 데이터베이스 테이블 생성하기 + +애플리케이션 시작 시 데이터베이스 테이블을 생성합니다. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[32:37] hl[35:37] *} + +여기서는 애플리케이션 시작 이벤트 시 테이블을 생성합니다. + +프로덕션 환경에서는 애플리케이션을 시작하기 전에 실행되는 마이그레이션 스크립트를 사용할 가능성이 높습니다. 🤓 + +/// tip | 팁 + +SQLModel은 Alembic을 감싸는 마이그레이션 유틸리티를 제공할 예정입니다. 하지만 현재 Alembic을 직접 사용할 수 있습니다. + +/// + +### Hero 생성하기 + +각 SQLModel 모델은 Pydantic 모델이기도 하므로, Pydantic 모델을 사용할 수 있는 **타입 어노테이**션에서 동일하게 사용할 수 있습니다. + +예를 들어, 파라미터를 `Hero` 타입으로 선언하면 **JSON 본문**에서 값을 읽어옵니다. + +마찬가지로, 함수의 **반환 타입**으로 선언하면 해당 데이터의 구조가 자동으로 생성되는 API 문서의 UI에 나타납니다. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *} + + + +여기서 `SessionDep` 의존성 (즉, `Session`)을 사용하여 새로운 `Hero`를 `Session` 인스턴스에 추가하고, 데이터베이스에 변경 사항을 커밋하고, `hero` 데이터의 최신 상태를 갱신한 다음 이를 반환합니다. + +### Heroes 조회하기 + +`select()`를 사용하여 데이터베이스에서 `Hero`를 **조회**할 수 있습니다. 결과에 페이지네이션을 적용하기 위해 `limit`와 `offset`을 포함할 수 있습니다. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[48:55] hl[51:52,54] *} + +### 단일 Hero 조회하기 + +단일 `Hero`를 **조회**할 수도 있습니다. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[58:63] hl[60] *} + +### Hero 삭제하기 + +`Hero`를 **삭제**하는 것도 가능합니다. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[66:73] hl[71] *} + +### 애플리케이션 실행하기 + +애플리케이션을 실행하려면 다음 명령을 사용합니다: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +그런 다음 `/docs` UI로 이동하면, **FastAPI**가 해당 **model들**을 사용하여 API **문서를 생성**하는 것으르 확인할 수 있습니다. 또한 이 모델들은 데이터를 직렬화하고 검증하는 데에도 사용됩니다. + +
+ +
+ +## 여러 모델로 애플리케이션 업데이트 + +이제 애플리케이션을 약간 **리팩토링**하여 **보안**과 **유연성**을 개선해 보겠습니다. + +이전 애플리케이션의 UI를 보면, 지금까지는 클라이언트가 생성할 `Hero`의 `id`를 직접 지정할 수 있다는 것을 알 수 있습니다. 😱 + +이는 허용되어선 안 됩니다. 클라이언트가 이미 데이터베이스에 저장된 `id`를 덮어쓸 위험이 있기 때문입니다. `id`는 **백엔드** 또는 **데이터베이스**가 결정해야 하며, **클라이언트**가 결정해서는 안 됩니다. + +또한 hero의 `secret_name`을 생성하긴 했지만, 지금까지는 이 값을 어디에서나 반환하고 있습니다. 이는 그다지 **비밀스럽지** 않습니다... 😅 + +이러한 문제를 해결하기 위해 몇 가지 **추가 모델**을 추가할 것입니다. 바로 여기서 SQLModel이 빛을 발하게 됩니다. ✨ + +### 여러 모델 생성하기 + +**SQLModel**에서 `table=True`가 설정된 모델 클래스는 **테이블 모델**입니다. + +`table=True`가 없는 모델 클래스는 **데이터 모델**로, 이는 실제로 몇 가지 추가 기능이 포함된 Pydantic 모델에 불과합니다. 🤓 + +SQLModel을 사용하면 **상속**을 통해 모든 경우에 필드를 **중복 선언하지 않아도** 됩니다. + +#### `HeroBase` - 기본 클래스 + +모든 모델에서 **공유되는 필드**를 가진 `HeroBase` 모델을 시작해 봅시다: + +* `name` +* `age` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:9] hl[7:9] *} + +#### `Hero` - *테이블 모델* + +다음으로 실제 *테이블 모델*인 `Hero`를 생성합니다. 이 모델은 다른 모델에는 항상 포함되는 건 아닌 **추가 필드**를 포함합니다: + +* `id` +* `secret_name` + +`Hero`는 `HeroBase`를 상속하므로 `HeroBase`에 선언된 필드도 포함합니다. 따라서 `Hero`는 다음 **필드들도** 가지게 됩니다: + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:14] hl[12:14] *} + +#### `HeroPublic` - 공개 *데이터 모델* + +다음으로 `HeroPublic` 모델을 생성합니다. 이 모델은 API 클라이언트에 **반환**되는 모델입니다. + +`HeroPublic`은 `HeroBase`와 동일한 필드를 가지며, `secret_name`은 포함하지 않습니다. + +마침내 우리의 heroes의 정체가 보호됩니다! 🥷 + +또한 `id: int`를 다시 선언합니다. 이를 통해, API 클라이언트와 **계약**을 맺어 `id`가 항상 존재하며 항상 `int` 타입이라는 것을 보장합니다(`None`이 될 수 없습니다). + +/// tip | 팁 + +반환 모델이 값이 항상 존재하고 항상 `int`(`None`이 아님)를 보장하는 것은 API 클라이언트에게 매우 유용합니다. 이를 통해 API와 통신하는 개발자가 훨씬 더 간단한 코드를 작성할 수 있습니다. + +또한 **자동으로 생성된 클라이언트**는 더 단순한 인터페이스를 제공하므로, API와 소통하는 개발자들이 훨씬 수월하게 작업할 수 있습니다. 😎 + +/// + +`HeroPublic`의 모든 필드는 `HeroBase`와 동일하며, `id`는 `int`로 선언됩니다(`None`이 아님): + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *} + +#### `HeroCreate` - hero 생성용 *데이터 모델* + +이제 `HeroCreate` 모델을 생성합니다. 이 모델은 클라이언트로부터 받은 데이터를 **검증**하는 역할을 합니다. + +`HeroCreate`는 `HeroBase와` 동일한 필드를 가지며, 추가로 `secret_name을` 포함합니다. + +클라이언트가 **새 hero을 생성**할 때 `secret_name`을 보내고, 이는 데이터베이스에 저장되지만, 해당 비밀 이름은 API를 통해 클라이언트에게 반환되지 않습니다. + +/// tip | 팁 + +이 방식은 **비밀번호**를 처리하는 방법과 동일합니다. 비밀번호를 받지만, 이를 API에서 반환하지는 않습니다. + +비밀번호 값을 저장하기 전에 **해싱**하여 저장하고, **평문으로 저장하지 마십시오**. + +/// + +`HeroCreate`의 필드는 다음과 같습니다: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:22] hl[21:22] *} + +#### `HeroUpdate` - hero 수정용 *데이터 모델* + +이전 애플리케이션에서는 **hero를 수정**할 방법이 없었지만, 이제 **다중 모델**을 통해 수정 기능을 추가할 수 있습니다. 🎉 + +`HeroUpdate` *데이터 모델*은 약간 특별한데, 새 hero을 생성할 때 필요한 **모든 동일한 필드**를 가지지만, 모든 필드가 **선택적**(기본값이 있음)입니다. 이렇게 하면 hero을 수정할 때 수정하려는 필드만 보낼 수 있습니다. + +모든 **필드가 변경되기** 때문에(타입이 `None`을 포함하고, 기본값이 `None`으로 설정됨), 모든 필드를 **다시 선언**해야 합니다. + +엄밀히 말하면 `HeroBase`를 상속할 필요는 없습니다. 모든 필드를 다시 선언하기 때문입니다. 일관성을 위해 상속을 유지하긴 했지만, 필수는 아닙니다. 이는 개인적인 취향의 문제입니다. 🤷 + +`HeroUpdate`의 필드는 다음과 같습니다: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:28] hl[25:28] *} + +### `HeroCreate`로 생성하고 `HeroPublic` 반환하기 + +이제 **다중 모델**을 사용하므로 애플리케이션의 관련 부분을 업데이트할 수 있습니다. + +요청에서 `HeroCreate` *데이터 모델*을 받아 이를 기반으로 `Hero` *테이블 모델*을 생성합니다. + +이 새 *테이블 모델* `Hero`는 클라이언트에서 보낸 필드를 가지며, 데이터베이스에서 생성된 `id`도 포함합니다. + +그런 다음 함수를 통해 동일한 *테이블 모델* `Hero`를 반환합니다. 하지만 `response_model`로 `HeroPublic` *데이터 모델*을 선언했기 때문에, **FastAPI**는 `HeroPublic`을 사용하여 데이터를 검증하고 직렬화합니다. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[56:62] hl[56:58] *} + +/// tip | 팁 + +이제 **반환 타입 주석** `-> HeroPublic` 대신 `response_model=HeroPublic`을 사용합니다. 반환하는 값이 실제로 `HeroPublic`이 *아니기* 때문입니다. + +만약 `-> HeroPublic`으로 선언했다면, 에디터와 린터에서 반환값이 `HeroPublic`이 아니라 `Hero`라고 경고했을 것입니다. 이는 적절한 경고입니다. + +`response_model`에 선언함으로써 **FastAPI**가 이를 처리하도록 하고, 타입 어노테이션과 에디터 및 다른 도구의 도움에는 영향을 미치지 않도록 설정합니다. + +/// + +### `HeroPublic`으로 Heroes 조회하기 + +이전과 동일하게 `Hero`를 **조회**할 수 있습니다. 이번에도 `response_model=list[HeroPublic]`을 사용하여 데이터가 올바르게 검증되고 직렬화되도록 보장합니다. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[65:72] hl[65] *} + +### `HeroPublic`으로 단일 Hero 조회하기 + +단일 hero을 **조회**할 수도 있습니다: + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[75:80] hl[77] *} + +### `HeroUpdate`로 Hero 수정하기 + +**hero를 수정**할 수도 있습니다. 이를 위해 HTTP `PATCH` 작업을 사용합니다. + +코드에서는 클라이언트가 보낸 데이터를 딕셔너리 형태(`dict`)로 가져옵니다. 이는 **클라이언트가 보낸 데이터만 포함**하며, 기본값으로 들어가는 값은 제외합니다. 이를 위해 `exclude_unset=True`를 사용합니다. 이것이 주요 핵심입니다. 🪄 + +그런 다음, `hero_db.sqlmodel_update(hero_data)`를 사용하여 `hero_data`의 데이터를 `hero_db`에 업데이트합니다. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[83:93] hl[83:84,88:89] *} + +### Hero 다시 삭제하기 + +hero **삭제**는 이전과 거의 동일합니다. + +이번에는 모든 것을 리팩토링하고 싶은 욕구를 만족시키지 못할 것 같습니다. 😅 + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *} + +### 애플리케이션 다시 실행하기 + +다음 명령을 사용해 애플리케이션을 다시 실행할 수 있습니다: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +`/docs` API UI로 이동하면 업데이트된 것을 확인할 수 있습니다. 클라이언트가 영웅을 생성할 때 `id`를 제공할 필요가 없게 되는 등의 변화도 보입니다. + +
+ +
+ +## 요약 + +**SQLModel**을 사용하여 SQL 데이터베이스와 상호작용하고, *데이터 모델* 및 *테이블 모델*로 코드를 간소화할 수 있습니다. + +더 많은 내용을 배우고 싶다면, **SQLModel** 문서를 참고하세요. SQLModel을 **FastAPI**와 함께 사용하는 것에 대한 더 긴 미니 튜토리얼도 제공합니다. 🚀 From 59401a7829729a19822a7f0ad03d6bcb2daa6224 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 24 Dec 2024 16:14:57 +0000 Subject: [PATCH 593/932] =?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 [skip ci] --- 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 18e270aae..c1d95a990 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/sql-databases.md`. PR [#13093](https://github.com/fastapi/fastapi/pull/13093) by [@GeumBinLee](https://github.com/GeumBinLee). * 🌐 Update Chinese translation for `docs/zh/docs/async.md`. PR [#13095](https://github.com/fastapi/fastapi/pull/13095) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/openapi-webhooks.md`. PR [#13091](https://github.com/fastapi/fastapi/pull/13091) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/async-tests.md`. PR [#13074](https://github.com/fastapi/fastapi/pull/13074) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). From d529449241d6ca2b1788d1958763b9215e3e34e6 Mon Sep 17 00:00:00 2001 From: Gerry Sabar Date: Tue, 24 Dec 2024 23:16:02 +0700 Subject: [PATCH 594/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Indonesian=20trans?= =?UTF-8?q?lation=20for=20`docs/id/docs/tutorial/path-params.md`=20(#13086?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/id/docs/tutorial/path-params.md | 258 +++++++++++++++++++++++++++ 1 file changed, 258 insertions(+) create mode 100644 docs/id/docs/tutorial/path-params.md diff --git a/docs/id/docs/tutorial/path-params.md b/docs/id/docs/tutorial/path-params.md new file mode 100644 index 000000000..7c24de4d3 --- /dev/null +++ b/docs/id/docs/tutorial/path-params.md @@ -0,0 +1,258 @@ +# Parameter Path + +"parameter" atau "variabel" path didefinisikan dengan sintaksis Python format string: + +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} + +Nilai parameter path `item_id` akan dikirim ke fungsi sebagai argument `item_id`: + +Jika anda menjalankan contoh berikut dan kunjungi http://127.0.0.1:8000/items/foo, anda akan melihat respon: + +```JSON +{"item_id":"foo"} +``` + +## Parameter path dengan tipe data + +Tipe data parameter path bisa didefinisikan di dalam fungsi, menggunakan anotasi tipe data standar Python: + +{* ../../docs_src/path_params/tutorial002.py hl[7] *} + +Dalam hal ini `item_id` didefinisikan sebagai `int`. + +/// check | Periksa + +Penyunting kode anda bisa membantu periksa di dalam fungsi seperti pemeriksaan kesalahan, kelengkapan kode, dll. + +/// + +## Konversi data + +Jika contoh berikut dijalankan dan diakses browser melalui http://127.0.0.1:8000/items/3, anda akan melihat respon: + +```JSON +{"item_id":3} +``` + +/// check | Periksa + +Perhatikan nilai fungsi yang diterima (dan dihasilkan) adalah `3`, sebagai `int` di Python, dan bukan string `"3"`. + +Sehingga dengan deklarasi tipe data **FastAPI** memberikan request otomatis "parsing". + +/// + +## Validasi Data + +Tetapi jika di browser anda akses http://127.0.0.1:8000/items/foo, anda akan melihat pesan kesalahan HTTP: + +```JSON +{ + "detail": [ + { + "type": "int_parsing", + "loc": [ + "path", + "item_id" + ], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": "https://errors.pydantic.dev/2.1/v/int_parsing" + } + ] +} +``` + +Karena parameter path `item_id` bernilai `"foo"` yang bukan tipe data `int`. + +Kesalahan yang sama akan muncul jika menggunakan `float` daripada `int`, seperti di: http://127.0.0.1:8000/items/4.2 + +/// check | Periksa + +Dengan deklarasi tipe data Python, **FastAPI** melakukan validasi data. + +Perhatikan kesalahan tersebut juga menjelaskan validasi apa yang tidak sesuai. + +Validasi ini sangat membantu ketika mengembangkan dan men-*debug* kode yang berhubungan dengan API anda. + +/// + +## Dokumentasi + +Ketika anda membuka browser di http://127.0.0.1:8000/docs, anda melihat dokumentasi API interaktif otomatis berikut: + + + +/// check | Periksa + +Dengan deklarasi tipe data Python yang sama, **FastAPI** membuat dokumentasi interaktif otomatis (terintegrasi Swagger UI). + +Perhatikan parameter path dideklarasikan sebagai integer. + +/// + +## Keuntungan basis-standar, dokumentasi alternatif + +Karena skema yang dibuat berasal dari standar OpenAPI, maka banyak alat lain yang kompatibel. + +Sehingga **FastAPI** menyediakan dokumentasi alternatif (menggunakan ReDoc), yang bisa diakses di http://127.0.0.1:8000/redoc: + + + +Cara yang sama untuk menggunakan tools kompatibel lainnya. Termasuk alat membuat kode otomatis untuk banyak bahasa. + +## Pydantic + +Semua validasi data dikerjakan di belakang layar oleh Pydantic, sehingga anda mendapatkan banyak kemudahan. Anda juga tahu proses ini akan ditangani dengan baik. + +Anda bisa mendeklarasikan tipe data dengan `str`, `float`, `bool` dan banyak tipe data kompleks lainnya. + +Beberapa tipe di atas akan dibahas pada bab berikutnya tutorial ini. + +## Urutan berpengaruh + +Ketika membuat *operasi path*, anda bisa menghadapi kondisi dimana *path* nya sudah tetap. + +Seperti `/users/me`, untuk mendapatkan data user yang sedang aktif. + +Kemudian anda bisa memiliki path `/users/{user_id}` untuk mendapatkan data user tertentu melalui user ID. + +karena *operasi path* dievaluasi melalui urutan, anda harus memastikan path untuk `/users/me` dideklarasikan sebelum `/user/{user_id}`: + +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} + +Sebaliknya, path `/users/{user_id}` juga akan sesuai dengan `/users/me`, "menganggap" menerima parameter `user_id` dengan nilai `"me"`. + +Serupa, anda juga tidak bisa mendefinisikan operasi path: + +{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *} + +Path pertama akan selalu digunakan karena path sesuai dengan yang pertama. + +## Nilai terdefinisi + +Jika ada *operasi path* yang menerima *parameter path*, tetapi anda ingin nilai valid *parameter path* sudah terdefinisi, anda bisa menggunakan standar Python `Enum`. + +### Membuat class `Enum` + +Import `Enum` dan buat *sub-class* warisan dari `str` dan `Enum`. + +Dengan warisan dari `str` dokumen API mengetahui nilai nya harus berjenis `string` supaya bisa digunakan dengan benar. + +Kemudian buat atribut *class* dengan nilai tetap *string* yang benar: + +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} + +/// info + +Enumerasi (atau enum) tersedia di Python sejak versi 3.4. + +/// + +/// tip | Tips + +"AlxexNet", "ResNet", dan "LeNet" adalah nama model *Machine Learning*. + +/// + +### Mendeklarasikan *parameter path* + +Kemudian buat *parameter path* dengan tipe anotasi menggunakan *class* enum dari (`ModelName`) + +{* ../../docs_src/path_params/tutorial005.py hl[16] *} + +### Periksa dokumentasi + +Karena nilai yang tersedia untuk *parameter path* telah terdefinisi, dokumen interatik bisa memunculkan: + + + +### Bekerja dengan *enumarasi* Python + +Nilai *parameter path* akan menjadi *anggota enumerasi*. + +#### Membandingkan *anggota enumerasi* + +Anda bisa membandingkan parameter *path* dengan *anggota enumerasi* di enum `ModelName` yang anda buat: + +{* ../../docs_src/path_params/tutorial005.py hl[17] *} + +#### Mendapatkan *nilai enumerasi* + +Anda bisa mendapatkan nilai (`str` dalam kasus ini) menggunakan `model_name.value`, atau secara umum `anggota_enum_anda.value`: + +{* ../../docs_src/path_params/tutorial005.py hl[20] *} + +/// tip | Tips + +Anda bisa mengakses nilai `"lenet"` dnegan `ModelName.lenet.value`. + +/// + +#### Menghasilkan *anggota enumerasi* + +Anda bisa menghasilkan *anggota enumerasi* dari *operasi path* bahkan di body JSON bersarang (contoh `dict`). + +They will be converted to their corresponding values (strings in this case) before returning them to the client: + +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} + +Klien akan mendapatkan respon JSON seperti berikut: + +```JSON +{ + "model_name": "alexnet", + "message": "Deep Learning FTW!" +} +``` + +## Parameter path berisi path + +Misalkan terdapat *operasi path* dengan path `/files/{file_path}`. + +Tetapi anda memerlukan `file_path` itu berisi *path*, seperti like `home/johndoe/myfile.txt`. + +Sehingga URL untuk file tersebut akan seperti: `/files/home/johndoe/myfile.txt`. + +### Dukungan OpenAPI + +OpenAPI tidak bisa mendeklarasikan *parameter path* berisi *path* di dalamnya, karena menyebabkan kondisi yang sulit di*test* dan didefinisikan. + +Tetapi, di **FastAPI** anda tetap bisa melakukannya dengan menggunakan *tools* internal dari Starlette. + +Dan dokumentasi tetap berfungsi walaupun tidak menambahkan keterangan bahwa parameter harus berisi *path*. + +### Konverter path + +Melalui Starlette anda bisa mendeklarasikan *parameter path* berisi *path* dengan URL seperti: + +``` +/files/{file_path:path} +``` + +Dikondisi ini nama parameter adalah `file_path` dan bagian terakhir `:path` menginformasikan parameter harus sesuai dengan setiap *path*. + +Sehingga anda bisa menggunakan: + +{* ../../docs_src/path_params/tutorial004.py hl[6] *} + +/// tip | Tips + +Anda mungkin perlu parameter berisi `/home/johndoe/myfile.txt` di awali garis belakang (`/`). + +Di kondisi ini, URL nya menjadi: `/files//home/johndoe/myfile.txt`, dengan dua garis belakang (`//`) di antara `files` dan `home`. + +/// + +## Ringkasan + +Di **FastAPI** dengan menggunakan deklarasi tipe Python standar, pendek, intuitif, anda mendapatkan: + +* Dukungan editor: pemeriksaan kesalahan, autocompletion, dll. +* "Parsing" data. +* Validasi data. +* Annotasi API dan dokumentasi otomatis. + +Semua itu anda hanya perlu mendeklarasikan sekali saja. + +Ini adalah salah satu keunggulan **FastAPI** dibandingkan dengan *framework* lainnya (selain dari performa Python *native*c) From 0370958171b0aabac7cdaf79337a29b3811f55af Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 24 Dec 2024 16:17:09 +0000 Subject: [PATCH 595/932] =?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 [skip ci] --- 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 c1d95a990..14e1b3983 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Translations +* 🌐 Add Indonesian translation for `docs/id/docs/tutorial/path-params.md`. PR [#13086](https://github.com/fastapi/fastapi/pull/13086) by [@gerry-sabar](https://github.com/gerry-sabar). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/sql-databases.md`. PR [#13093](https://github.com/fastapi/fastapi/pull/13093) by [@GeumBinLee](https://github.com/GeumBinLee). * 🌐 Update Chinese translation for `docs/zh/docs/async.md`. PR [#13095](https://github.com/fastapi/fastapi/pull/13095) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Add Chinese translation for `docs/zh/docs/advanced/openapi-webhooks.md`. PR [#13091](https://github.com/fastapi/fastapi/pull/13091) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). From b7367f2564b0e7cbee564a00e1a5ec458959ef32 Mon Sep 17 00:00:00 2001 From: alv2017 Date: Wed, 25 Dec 2024 22:10:12 +0200 Subject: [PATCH 596/932] =?UTF-8?q?=F0=9F=93=9D=20Minor=20corrections=20in?= =?UTF-8?q?=20`docs/en/docs/tutorial/sql-databases.md`=20(#13081)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/sql-databases.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 972eb9308..eac86f7fb 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -125,8 +125,6 @@ The same way, you can declare it as the function's **return type**, and then the {* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *} - - Here we use the `SessionDep` dependency (a `Session`) to add the new `Hero` to the `Session` instance, commit the changes to the database, refresh the data in the `hero`, and then return it. ### Read Heroes @@ -235,7 +233,6 @@ All the fields in `HeroPublic` are the same as in `HeroBase`, with `id` declared * `id` * `name` * `age` -* `secret_name` {* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *} From d5a11b6cdc5cfae358bf4449e8a3bc5318078b88 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 25 Dec 2024 20:10:38 +0000 Subject: [PATCH 597/932] =?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 [skip ci] --- 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 14e1b3983..a9b91667e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Minor corrections in `docs/en/docs/tutorial/sql-databases.md`. PR [#13081](https://github.com/fastapi/fastapi/pull/13081) by [@alv2017](https://github.com/alv2017). * 📝 Update includes in `docs/ru/docs/tutorial/query-param-models.md`. PR [#12994](https://github.com/fastapi/fastapi/pull/12994) by [@alejsdev](https://github.com/alejsdev). * ✏️ Fix typo in README installation instructions. PR [#13011](https://github.com/fastapi/fastapi/pull/13011) by [@dave-hay](https://github.com/dave-hay). * 📝 Update docs for `fastapi-cli`. PR [#13031](https://github.com/fastapi/fastapi/pull/13031) by [@tiangolo](https://github.com/tiangolo). From abac4754072fff16de3b2b0f3c52f9b8695a7123 Mon Sep 17 00:00:00 2001 From: Subin Lee Date: Thu, 26 Dec 2024 05:32:56 +0900 Subject: [PATCH 598/932] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20error=20in?= =?UTF-8?q?=20`docs/en/docs/contributing.md`=20(#12899)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/contributing.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index a29bb03e9..1b70a0ea9 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -107,7 +107,7 @@ $ cd docs/en/ Then run `mkdocs` in that directory: ```console -$ mkdocs serve --dev-addr 8008 +$ mkdocs serve --dev-addr 127.0.0.1:8008 ``` /// @@ -245,7 +245,7 @@ $ cd docs/es/ Then run `mkdocs` in that directory: ```console -$ mkdocs serve --dev-addr 8008 +$ mkdocs serve --dev-addr 127.0.0.1:8008 ``` /// From 741b95a45423012b660056506312b781907d91d7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 25 Dec 2024 20:33:17 +0000 Subject: [PATCH 599/932] =?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 [skip ci] --- 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 a9b91667e..474cc3434 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏️ Fix error in `docs/en/docs/contributing.md`. PR [#12899](https://github.com/fastapi/fastapi/pull/12899) by [@kingsubin](https://github.com/kingsubin). * 📝 Minor corrections in `docs/en/docs/tutorial/sql-databases.md`. PR [#13081](https://github.com/fastapi/fastapi/pull/13081) by [@alv2017](https://github.com/alv2017). * 📝 Update includes in `docs/ru/docs/tutorial/query-param-models.md`. PR [#12994](https://github.com/fastapi/fastapi/pull/12994) by [@alejsdev](https://github.com/alejsdev). * ✏️ Fix typo in README installation instructions. PR [#13011](https://github.com/fastapi/fastapi/pull/13011) by [@dave-hay](https://github.com/dave-hay). From 13a5b3f9b952084c48e9ca477872943b864fc816 Mon Sep 17 00:00:00 2001 From: Chen Pu <113831763+ChenPu2002@users.noreply.github.com> Date: Mon, 30 Dec 2024 04:41:04 +0800 Subject: [PATCH 600/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/advanced/security/oauth2-scopes.md?= =?UTF-8?q?`=20(#13110)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/advanced/security/oauth2-scopes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/zh/docs/advanced/security/oauth2-scopes.md b/docs/zh/docs/advanced/security/oauth2-scopes.md index c3f593684..784c38490 100644 --- a/docs/zh/docs/advanced/security/oauth2-scopes.md +++ b/docs/zh/docs/advanced/security/oauth2-scopes.md @@ -146,7 +146,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 该依赖项函数本身不需要作用域,因此,可以使用 `Depends` 和 `oauth2_scheme`。不需要指定安全作用域时,不必使用 `Security`。 -此处还声明了从 `fastapin.security` 导入的 `SecurityScopes` 类型的特殊参数。 +此处还声明了从 `fastapi.security` 导入的 `SecurityScopes` 类型的特殊参数。 `SecuriScopes` 类与 `Request` 类似(`Request` 用于直接提取请求对象)。 From d88473b73986d16a757efab6b4c8bb88e7f855cc Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 29 Dec 2024 20:41:26 +0000 Subject: [PATCH 601/932] =?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 [skip ci] --- 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 474cc3434..dfd16b030 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/advanced/security/oauth2-scopes.md`. PR [#13110](https://github.com/fastapi/fastapi/pull/13110) by [@ChenPu2002](https://github.com/ChenPu2002). * 🌐 Add Indonesian translation for `docs/id/docs/tutorial/path-params.md`. PR [#13086](https://github.com/fastapi/fastapi/pull/13086) by [@gerry-sabar](https://github.com/gerry-sabar). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/sql-databases.md`. PR [#13093](https://github.com/fastapi/fastapi/pull/13093) by [@GeumBinLee](https://github.com/GeumBinLee). * 🌐 Update Chinese translation for `docs/zh/docs/async.md`. PR [#13095](https://github.com/fastapi/fastapi/pull/13095) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). From 495460d3edfe195602f9bd179642c1bf6046f071 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 30 Dec 2024 17:46:44 +0000 Subject: [PATCH 602/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20existing=20Span?= =?UTF-8?q?ish=20translations=20using=20the=20new=20LLM-assisted=20system?= =?UTF-8?q?=20using=20PydanticAI=20(#13118)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- .../docs/advanced/additional-status-codes.md | 30 +- docs/es/docs/advanced/index.md | 31 +- .../path-operation-advanced-configuration.md | 185 ++++++- .../advanced/response-change-status-code.md | 28 +- docs/es/docs/advanced/response-directly.md | 50 +- docs/es/docs/advanced/response-headers.md | 36 +- docs/es/docs/advanced/security/index.md | 14 +- docs/es/docs/async.md | 315 +++++------ docs/es/docs/benchmarks.md | 35 +- docs/es/docs/deployment/index.md | 22 +- docs/es/docs/deployment/versions.md | 68 +-- docs/es/docs/features.md | 166 +++--- docs/es/docs/how-to/graphql.md | 38 +- docs/es/docs/index.md | 323 ++++++----- docs/es/docs/learn/index.md | 4 +- docs/es/docs/project-generation.md | 28 +- docs/es/docs/python-types.md | 500 ++++++++++++++---- docs/es/docs/tutorial/cookie-params.md | 12 +- docs/es/docs/tutorial/first-steps.md | 248 +++++---- docs/es/docs/tutorial/index.md | 99 ++-- docs/es/docs/tutorial/path-params.md | 170 +++--- docs/es/docs/tutorial/query-params.md | 106 ++-- 22 files changed, 1513 insertions(+), 995 deletions(-) diff --git a/docs/es/docs/advanced/additional-status-codes.md b/docs/es/docs/advanced/additional-status-codes.md index b72798c2b..df7737aac 100644 --- a/docs/es/docs/advanced/additional-status-codes.md +++ b/docs/es/docs/advanced/additional-status-codes.md @@ -1,41 +1,41 @@ -# Códigos de estado adicionales +# Códigos de Estado Adicionales -Por defecto, **FastAPI** devolverá las respuestas utilizando una `JSONResponse`, poniendo el contenido que devuelves en tu *operación de path* dentro de esa `JSONResponse`. +Por defecto, **FastAPI** devolverá los responses usando un `JSONResponse`, colocando el contenido que devuelves desde tu *path operation* dentro de ese `JSONResponse`. -Utilizará el código de estado por defecto, o el que hayas asignado en tu *operación de path*. +Usará el código de estado por defecto o el que configures en tu *path operation*. ## Códigos de estado adicionales -Si quieres devolver códigos de estado adicionales además del principal, puedes hacerlo devolviendo directamente una `Response`, como una `JSONResponse`, y asignar directamente el código de estado adicional. +Si quieres devolver códigos de estado adicionales aparte del principal, puedes hacerlo devolviendo un `Response` directamente, como un `JSONResponse`, y configurando el código de estado adicional directamente. -Por ejemplo, digamos que quieres tener una *operación de path* que permita actualizar ítems y devolver códigos de estado HTTP 200 "OK" cuando sea exitosa. +Por ejemplo, supongamos que quieres tener una *path operation* que permita actualizar elementos, y devuelva códigos de estado HTTP de 200 "OK" cuando sea exitoso. -Pero también quieres que acepte nuevos ítems. Cuando los ítems no existan anteriormente, serán creados y devolverá un código de estado HTTP 201 "Created". +Pero también quieres que acepte nuevos elementos. Y cuando los elementos no existían antes, los crea y devuelve un código de estado HTTP de 201 "Created". -Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu contenido, asignando el `status_code` que quieras: +Para lograr eso, importa `JSONResponse`, y devuelve tu contenido allí directamente, configurando el `status_code` que deseas: -{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *} +{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *} /// warning | Advertencia -Cuando devuelves directamente una `Response`, como en los ejemplos anteriores, será devuelta directamente. +Cuando devuelves un `Response` directamente, como en el ejemplo anterior, se devuelve directamente. -No será serializado con el modelo, etc. +No se serializará con un modelo, etc. -Asegúrate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`). +Asegúrate de que tenga los datos que deseas que tenga y que los valores sean JSON válidos (si estás usando `JSONResponse`). /// /// note | Detalles Técnicos -También podrías utilizar `from starlette.responses import JSONResponse`. +También podrías usar `from starlette.responses import JSONResponse`. -**FastAPI** provee las mismas `starlette.responses` que `fastapi.responses` simplemente como una convención para ti, el desarrollador. Pero la mayoría de las respuestas disponibles vienen directamente de Starlette. Lo mismo con `status`. +**FastAPI** proporciona los mismos `starlette.responses` que `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles provienen directamente de Starlette. Lo mismo con `status`. /// ## OpenAPI y documentación de API -Si quieres devolver códigos de estado y respuestas adicionales directamente, estas no estarán incluidas en el schema de OpenAPI (documentación de API), porque FastAPI no tiene una manera de conocer de antemano lo que vas a devolver. +Si devuelves códigos de estado adicionales y responses directamente, no se incluirán en el esquema de OpenAPI (la documentación de la API), porque FastAPI no tiene una forma de saber de antemano qué vas a devolver. -Pero puedes documentar eso en tu código usando [Respuestas Adicionales](additional-responses.md){.internal-link target=_blank}. +Pero puedes documentarlo en tu código, usando: [Responses Adicionales](additional-responses.md){.internal-link target=_blank}. diff --git a/docs/es/docs/advanced/index.md b/docs/es/docs/advanced/index.md index 10a1ff0d5..0626a1563 100644 --- a/docs/es/docs/advanced/index.md +++ b/docs/es/docs/advanced/index.md @@ -1,21 +1,36 @@ -# Guía de Usuario Avanzada +# Guía avanzada del usuario -## Características Adicionales +## Funcionalidades adicionales -El [Tutorial - Guía de Usuario](../tutorial/index.md){.internal-link target=_blank} principal debe ser suficiente para darte un paseo por todas las características principales de **FastAPI** +El [Tutorial - Guía del usuario](../tutorial/index.md){.internal-link target=_blank} principal debería ser suficiente para darte un recorrido por todas las funcionalidades principales de **FastAPI**. -En las secciones siguientes verás otras opciones, configuraciones, y características adicionales. +En las siguientes secciones verás otras opciones, configuraciones y funcionalidades adicionales. /// tip | Consejo -Las próximas secciones **no son necesariamente "avanzadas"**. +Las siguientes secciones **no son necesariamente "avanzadas"**. -Y es posible que para tu caso, la solución se encuentre en una de estas. +Y es posible que para tu caso de uso, la solución esté en una de ellas. /// ## Lee primero el Tutorial -Puedes continuar usando la mayoría de las características de **FastAPI** con el conocimiento del [Tutorial - Guía de Usuario](../tutorial/index.md){.internal-link target=_blank} principal. +Aún podrías usar la mayoría de las funcionalidades en **FastAPI** con el conocimiento del [Tutorial - Guía del usuario](../tutorial/index.md){.internal-link target=_blank} principal. -En las siguientes secciones se asume que lo has leído y conoces esas ideas principales. +Y las siguientes secciones asumen que ya lo leíste y que conoces esas ideas principales. + +## Cursos externos + +Aunque el [Tutorial - Guía del usuario](../tutorial/index.md){.internal-link target=_blank} y esta **Guía avanzada del usuario** están escritos como un tutorial guiado (como un libro) y deberían ser suficientes para que **aprendas FastAPI**, podrías querer complementarlo con cursos adicionales. + +O podría ser que simplemente prefieras tomar otros cursos porque se adaptan mejor a tu estilo de aprendizaje. + +Algunos proveedores de cursos ✨ [**sponsorean FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, esto asegura el desarrollo continuo y saludable de FastAPI y su **ecosistema**. + +Y muestra su verdadero compromiso con FastAPI y su **comunidad** (tú), ya que no solo quieren brindarte una **buena experiencia de aprendizaje** sino que también quieren asegurarse de que tengas un **buen y saludable framework**, FastAPI. 🙇 + +Podrías querer probar sus cursos: + +* Talk Python Training +* Desarrollo guiado por pruebas diff --git a/docs/es/docs/advanced/path-operation-advanced-configuration.md b/docs/es/docs/advanced/path-operation-advanced-configuration.md index 600e2e074..2b20819aa 100644 --- a/docs/es/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/es/docs/advanced/path-operation-advanced-configuration.md @@ -1,53 +1,204 @@ -# Configuración avanzada de las operaciones de path +# Configuración Avanzada de Path Operation -## OpenAPI operationId +## operationId de OpenAPI /// warning | Advertencia -Si no eres una persona "experta" en OpenAPI, probablemente no necesitas leer esto. +Si no eres un "experto" en OpenAPI, probablemente no necesites esto. /// -Puedes asignar el `operationId` de OpenAPI para ser usado en tu *operación de path* con el parámetro `operation_id`. +Puedes establecer el `operationId` de OpenAPI para ser usado en tu *path operation* con el parámetro `operation_id`. -En este caso tendrías que asegurarte de que sea único para cada operación. +Tienes que asegurarte de que sea único para cada operación. {* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} -### Usando el nombre de la *función de la operación de path* en el operationId +### Usar el nombre de la *función de path operation* como el operationId -Si quieres usar tus nombres de funciones de API como `operationId`s, puedes iterar sobre todos ellos y sobrescribir `operation_id` de cada *operación de path* usando su `APIRoute.name`. +Si quieres usar los nombres de las funciones de tus APIs como `operationId`s, puedes iterar sobre todas ellas y sobrescribir el `operation_id` de cada *path operation* usando su `APIRoute.name`. -Deberías hacerlo después de adicionar todas tus *operaciones de path*. +Deberías hacerlo después de agregar todas tus *path operations*. -{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12,13,14,15,16,17,18,19,20,21,24] *} +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2, 12:21, 24] *} /// tip | Consejo -Si llamas manualmente a `app.openapi()`, debes actualizar el `operationId`s antes de hacerlo. +Si llamas manualmente a `app.openapi()`, deberías actualizar los `operationId`s antes de eso. /// /// warning | Advertencia -Si haces esto, debes asegurarte de que cada una de tus *funciones de las operaciones de path* tenga un nombre único. +Si haces esto, tienes que asegurarte de que cada una de tus *funciones de path operation* tenga un nombre único. -Incluso si están en diferentes módulos (archivos Python). +Incluso si están en diferentes módulos (archivos de Python). /// ## Excluir de OpenAPI -Para excluir una *operación de path* del esquema OpenAPI generado (y por tanto del la documentación generada automáticamente), usa el parámetro `include_in_schema` y asigna el valor como `False`; +Para excluir una *path operation* del esquema OpenAPI generado (y por lo tanto, de los sistemas de documentación automática), utiliza el parámetro `include_in_schema` y configúralo en `False`: {* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## Descripción avanzada desde el docstring -Puedes limitar las líneas usadas desde el docstring de una *operación de path* para OpenAPI. +Puedes limitar las líneas usadas del docstring de una *función de path operation* para OpenAPI. -Agregar un `\f` (un carácter de "form feed" escapado) hace que **FastAPI** trunque el output utilizada para OpenAPI en ese punto. +Añadir un `\f` (un carácter de separación de página escapado) hace que **FastAPI** trunque la salida usada para OpenAPI en este punto. -No será mostrado en la documentación, pero otras herramientas (como Sphinx) serán capaces de usar el resto. +No aparecerá en la documentación, pero otras herramientas (como Sphinx) podrán usar el resto. -{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19,20,21,22,23,24,25,26,27,28,29] *} +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} + +## Responses Adicionales + +Probablemente has visto cómo declarar el `response_model` y el `status_code` para una *path operation*. + +Eso define los metadatos sobre el response principal de una *path operation*. + +También puedes declarar responses adicionales con sus modelos, códigos de estado, etc. + +Hay un capítulo entero en la documentación sobre ello, puedes leerlo en [Responses Adicionales en OpenAPI](additional-responses.md){.internal-link target=_blank}. + +## OpenAPI Extra + +Cuando declaras una *path operation* en tu aplicación, **FastAPI** genera automáticamente los metadatos relevantes sobre esa *path operation* para incluirlos en el esquema de OpenAPI. + +/// note | Nota + +En la especificación de OpenAPI se llama el Objeto de Operación. + +/// + +Tiene toda la información sobre la *path operation* y se usa para generar la documentación automática. + +Incluye los `tags`, `parameters`, `requestBody`, `responses`, etc. + +Este esquema de OpenAPI específico de *path operation* normalmente se genera automáticamente por **FastAPI**, pero también puedes extenderlo. + +/// tip | Consejo + +Este es un punto de extensión de bajo nivel. + +Si solo necesitas declarar responses adicionales, una forma más conveniente de hacerlo es con [Responses Adicionales en OpenAPI](additional-responses.md){.internal-link target=_blank}. + +/// + +Puedes extender el esquema de OpenAPI para una *path operation* usando el parámetro `openapi_extra`. + +### Extensiones de OpenAPI + +Este `openapi_extra` puede ser útil, por ejemplo, para declarar [Extensiones de OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions): + +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} + +Si abres la documentación automática de la API, tu extensión aparecerá en la parte inferior de la *path operation* específica. + + + +Y si ves el OpenAPI resultante (en `/openapi.json` en tu API), verás tu extensión como parte de la *path operation* específica también: + +```JSON hl_lines="22" +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + } + }, + "x-aperture-labs-portal": "blue" + } + } + } +} +``` + +### Esquema de *path operation* personalizada de OpenAPI + +El diccionario en `openapi_extra` se combinará profundamente con el esquema de OpenAPI generado automáticamente para la *path operation*. + +Por lo tanto, podrías añadir datos adicionales al esquema generado automáticamente. + +Por ejemplo, podrías decidir leer y validar el request con tu propio código, sin usar las funcionalidades automáticas de FastAPI con Pydantic, pero aún podrías querer definir el request en el esquema de OpenAPI. + +Podrías hacer eso con `openapi_extra`: + +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[19:36, 39:40] *} + +En este ejemplo, no declaramos ningún modelo Pydantic. De hecho, el cuerpo del request ni siquiera se parse como JSON, se lee directamente como `bytes`, y la función `magic_data_reader()` sería la encargada de parsearlo de alguna manera. + +Sin embargo, podemos declarar el esquema esperado para el cuerpo del request. + +### Tipo de contenido personalizado de OpenAPI + +Usando este mismo truco, podrías usar un modelo Pydantic para definir el esquema JSON que luego se incluye en la sección personalizada del esquema OpenAPI para la *path operation*. + +Y podrías hacer esto incluso si el tipo de datos en el request no es JSON. + +Por ejemplo, en esta aplicación no usamos la funcionalidad integrada de FastAPI para extraer el esquema JSON de los modelos Pydantic ni la validación automática para JSON. De hecho, estamos declarando el tipo de contenido del request como YAML, no JSON: + +//// tab | Pydantic v2 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22, 24] *} + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[17:22, 24] *} + +//// + +/// info | Información + +En la versión 1 de Pydantic el método para obtener el esquema JSON para un modelo se llamaba `Item.schema()`, en la versión 2 de Pydantic, el método se llama `Item.model_json_schema()`. + +/// + +Sin embargo, aunque no estamos usando la funcionalidad integrada por defecto, aún estamos usando un modelo Pydantic para generar manualmente el esquema JSON para los datos que queremos recibir en YAML. + +Luego usamos el request directamente, y extraemos el cuerpo como `bytes`. Esto significa que FastAPI ni siquiera intentará parsear la carga útil del request como JSON. + +Y luego en nuestro código, parseamos ese contenido YAML directamente, y nuevamente estamos usando el mismo modelo Pydantic para validar el contenido YAML: + +//// tab | Pydantic v2 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[26:33] *} + +//// + +/// info | Información + +En la versión 1 de Pydantic el método para parsear y validar un objeto era `Item.parse_obj()`, en la versión 2 de Pydantic, el método se llama `Item.model_validate()`. + +/// + +/// tip | Consejo + +Aquí reutilizamos el mismo modelo Pydantic. + +Pero de la misma manera, podríamos haberlo validado de alguna otra forma. + +/// diff --git a/docs/es/docs/advanced/response-change-status-code.md b/docs/es/docs/advanced/response-change-status-code.md index 6a44ea94e..e0889c474 100644 --- a/docs/es/docs/advanced/response-change-status-code.md +++ b/docs/es/docs/advanced/response-change-status-code.md @@ -1,31 +1,31 @@ -# Response - Cambiar el Status Code +# Response - Cambiar Código de Estado -Probablemente ya has leído con anterioridad que puedes establecer un [Response Status Code](../tutorial/response-status-code.md){.internal-link target=_blank} por defecto. +Probablemente leíste antes que puedes establecer un [Código de Estado de Response](../tutorial/response-status-code.md){.internal-link target=_blank} por defecto. -Pero en algunos casos necesitas retornar un status code diferente al predeterminado. +Pero en algunos casos necesitas devolver un código de estado diferente al predeterminado. -## Casos de uso +## Caso de uso -Por ejemplo, imagina que quieres retornar un HTTP status code de "OK" `200` por defecto. +Por ejemplo, imagina que quieres devolver un código de estado HTTP de "OK" `200` por defecto. -Pero si los datos no existen, quieres crearlos y retornar un HTTP status code de "CREATED" `201`. +Pero si los datos no existieran, quieres crearlos y devolver un código de estado HTTP de "CREATED" `201`. -Pero aún quieres poder filtrar y convertir los datos que retornas con un `response_model`. +Pero todavía quieres poder filtrar y convertir los datos que devuelves con un `response_model`. Para esos casos, puedes usar un parámetro `Response`. -## Usar un parámetro `Response` +## Usa un parámetro `Response` -Puedes declarar un parámetro de tipo `Response` en tu *función de la operación de path* (como puedes hacer para cookies y headers). +Puedes declarar un parámetro de tipo `Response` en tu *función de path operation* (como puedes hacer para cookies y headers). -Y luego puedes establecer el `status_code` en ese objeto de respuesta *temporal*. +Y luego puedes establecer el `status_code` en ese objeto de response *temporal*. {* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} -Y luego puedes retornar cualquier objeto que necesites, como normalmente lo harías (un `dict`, un modelo de base de datos, etc). +Y luego puedes devolver cualquier objeto que necesites, como lo harías normalmente (un `dict`, un modelo de base de datos, etc.). -Y si declaraste un `response_model`, aún se usará para filtrar y convertir el objeto que retornaste. +Y si declaraste un `response_model`, todavía se utilizará para filtrar y convertir el objeto que devolviste. -**FastAPI** usará esa respuesta *temporal* para extraer el código de estado (también cookies y headers), y los pondrá en la respuesta final que contiene el valor que retornaste, filtrado por cualquier `response_model`. +**FastAPI** usará ese response *temporal* para extraer el código de estado (también cookies y headers), y los pondrá en el response final que contiene el valor que devolviste, filtrado por cualquier `response_model`. -También puedes declarar la dependencia del parámetro `Response`, y establecer el código de estado en ellos. Pero ten en cuenta que el último en establecerse será el que gane. +También puedes declarar el parámetro `Response` en dependencias y establecer el código de estado en ellas. Pero ten en cuenta que el último establecido prevalecerá. diff --git a/docs/es/docs/advanced/response-directly.md b/docs/es/docs/advanced/response-directly.md index 3cab11d99..8594011d6 100644 --- a/docs/es/docs/advanced/response-directly.md +++ b/docs/es/docs/advanced/response-directly.md @@ -1,18 +1,18 @@ -# Devolver una respuesta directamente +# Devolver una Response Directamente -Cuando creas una *operación de path* normalmente puedes devolver cualquier dato: un `dict`, una `list`, un modelo Pydantic, un modelo de base de datos, etc. +Cuando creas una *path operation* en **FastAPI**, normalmente puedes devolver cualquier dato desde ella: un `dict`, una `list`, un modelo de Pydantic, un modelo de base de datos, etc. -Por defecto, **FastAPI** convertiría automáticamente ese valor devuelto a JSON usando el `jsonable_encoder` explicado en [Codificador Compatible JSON](../tutorial/encoder.md){.internal-link target=_blank}. +Por defecto, **FastAPI** convertiría automáticamente ese valor de retorno a JSON usando el `jsonable_encoder` explicado en [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank}. -Luego, tras bastidores, pondría esos datos compatibles con JSON (por ejemplo, un `dict`) dentro de una `JSONResponse` que se usaría para enviar la respuesta al cliente. +Luego, detrás de escena, pondría esos datos compatibles con JSON (por ejemplo, un `dict`) dentro de un `JSONResponse` que se usaría para enviar el response al cliente. -Pero puedes devolver una `JSONResponse` directamente de tu *operación de path*. +Pero puedes devolver un `JSONResponse` directamente desde tus *path operations*. -Esto puede ser útil, por ejemplo, para devolver cookies o headers personalizados. +Esto podría ser útil, por ejemplo, para devolver headers o cookies personalizados. ## Devolver una `Response` -De hecho, puedes devolver cualquier `Response` o cualquier subclase de la misma. +De hecho, puedes devolver cualquier `Response` o cualquier subclase de ella. /// tip | Consejo @@ -22,44 +22,44 @@ De hecho, puedes devolver cualquier `Response` o cualquier subclase de la misma. Y cuando devuelves una `Response`, **FastAPI** la pasará directamente. -No hará ninguna conversión de datos con modelos Pydantic, no convertirá el contenido a ningún tipo, etc. +No hará ninguna conversión de datos con los modelos de Pydantic, no convertirá los contenidos a ningún tipo, etc. -Esto te da mucha flexibilidad. Puedes devolver cualquier tipo de dato, sobrescribir cualquier declaración de datos o validación, etc. +Esto te da mucha flexibilidad. Puedes devolver cualquier tipo de datos, sobrescribir cualquier declaración o validación de datos, etc. -## Usando el `jsonable_encoder` en una `Response` +## Usar el `jsonable_encoder` en una `Response` -Como **FastAPI** no realiza ningún cambio en la `Response` que devuelves, debes asegurarte de que el contenido está listo. +Como **FastAPI** no realiza cambios en una `Response` que devuelves, tienes que asegurarte de que sus contenidos estén listos para ello. -Por ejemplo, no puedes poner un modelo Pydantic en una `JSONResponse` sin primero convertirlo a un `dict` con todos los tipos de datos (como `datetime`, `UUID`, etc) convertidos a tipos compatibles con JSON. +Por ejemplo, no puedes poner un modelo de Pydantic en un `JSONResponse` sin primero convertirlo a un `dict` con todos los tipos de datos (como `datetime`, `UUID`, etc.) convertidos a tipos compatibles con JSON. -Para esos casos, puedes usar el `jsonable_encoder` para convertir tus datos antes de pasarlos a la respuesta: +Para esos casos, puedes usar el `jsonable_encoder` para convertir tus datos antes de pasarlos a un response: -{* ../../docs_src/response_directly/tutorial001.py hl[4,6,20,21] *} +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} -/// note | Detalles Técnicos +/// note | Nota -También puedes usar `from starlette.responses import JSONResponse`. +También podrías usar `from starlette.responses import JSONResponse`. -**FastAPI** provee `starlette.responses` como `fastapi.responses`, simplemente como una conveniencia para ti, el desarrollador. Pero la mayoría de las respuestas disponibles vienen directamente de Starlette. +**FastAPI** proporciona los mismos `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette. /// -## Devolviendo una `Response` personalizada +## Devolver una `Response` personalizada -El ejemplo anterior muestra las partes que necesitas, pero no es muy útil todavía, dado que podrías simplemente devolver el `item` directamente, y **FastAPI** lo pondría en una `JSONResponse` por ti, convirtiéndolo en un `dict`, etc. Todo esto por defecto. +El ejemplo anterior muestra todas las partes que necesitas, pero aún no es muy útil, ya que podrías haber devuelto el `item` directamente, y **FastAPI** lo colocaría en un `JSONResponse` por ti, convirtiéndolo a un `dict`, etc. Todo eso por defecto. -Ahora, veamos cómo puedes usarlo para devolver una respuesta personalizada. +Ahora, veamos cómo podrías usar eso para devolver un response personalizado. -Digamos que quieres devolver una respuesta XML. +Digamos que quieres devolver un response en XML. -Podrías poner tu contenido XML en un string, ponerlo en una `Response` y devolverlo: +Podrías poner tu contenido XML en un string, poner eso en un `Response`, y devolverlo: {* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ## Notas -Cuando devuelves una `Response` directamente, los datos no son validados, convertidos (serializados), ni documentados automáticamente. +Cuando devuelves una `Response` directamente, sus datos no son validados, convertidos (serializados), ni documentados automáticamente. -Pero todavía es posible documentarlo como es descrito en [Respuestas adicionales en OpenAPI](additional-responses.md){.internal-link target=_blank}. +Pero aún puedes documentarlo como se describe en [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}. -Puedes ver en secciones posteriores como usar/declarar esas `Response`s personalizadas aún teniendo conversión automática de datos, documentación, etc. +Puedes ver en secciones posteriores cómo usar/declarar estas `Response`s personalizadas mientras todavía tienes conversión automática de datos, documentación, etc. diff --git a/docs/es/docs/advanced/response-headers.md b/docs/es/docs/advanced/response-headers.md index a7a506142..49eaa53c1 100644 --- a/docs/es/docs/advanced/response-headers.md +++ b/docs/es/docs/advanced/response-headers.md @@ -1,43 +1,41 @@ -# Headers de Respuesta +# Response Headers -## Usar un parámetro `Response` +## Usa un parámetro `Response` -Puedes declarar un parámetro de tipo `Response` en tu *función de operación de path* (de manera similar como se hace con las cookies). +Puedes declarar un parámetro de tipo `Response` en tu *función de path operation* (como puedes hacer para cookies). -Y entonces, podrás configurar las cookies en ese objeto de response *temporal*. +Y luego puedes establecer headers en ese objeto de response *temporal*. -{* ../../docs_src/response_headers/tutorial002.py hl[1,7:8] *} +{* ../../docs_src/response_headers/tutorial002.py hl[1, 7:8] *} -Posteriormente, puedes devolver cualquier objeto que necesites, como normalmente harías (un `dict`, un modelo de base de datos, etc). +Y luego puedes devolver cualquier objeto que necesites, como harías normalmente (un `dict`, un modelo de base de datos, etc). -Si declaraste un `response_model`, este se continuará usando para filtrar y convertir el objeto que devolviste. +Y si declaraste un `response_model`, aún se usará para filtrar y convertir el objeto que devolviste. -**FastAPI** usará ese response *temporal* para extraer los headers (al igual que las cookies y el status code), además las pondrá en el response final que contendrá el valor retornado y filtrado por algún `response_model`. +**FastAPI** usará ese response *temporal* para extraer los headers (también cookies y el código de estado), y los pondrá en el response final que contiene el valor que devolviste, filtrado por cualquier `response_model`. -También puedes declarar el parámetro `Response` en dependencias, así como configurar los headers (y las cookies) en ellas. +También puedes declarar el parámetro `Response` en dependencias y establecer headers (y cookies) en ellas. +## Retorna una `Response` directamente -## Retornar una `Response` directamente +También puedes agregar headers cuando devuelves un `Response` directamente. -Adicionalmente, puedes añadir headers cuando se retorne una `Response` directamente. - -Crea un response tal como se describe en [Retornar una respuesta directamente](response-directly.md){.internal-link target=_blank} y pasa los headers como un parámetro adicional: +Crea un response como se describe en [Retorna un Response Directamente](response-directly.md){.internal-link target=_blank} y pasa los headers como un parámetro adicional: {* ../../docs_src/response_headers/tutorial001.py hl[10:12] *} /// note | Detalles Técnicos -También podrías utilizar `from starlette.responses import Response` o `from starlette.responses import JSONResponse`. - -**FastAPI** proporciona las mismas `starlette.responses` en `fastapi.responses` sólo que de una manera más conveniente para ti, el desarrollador. En otras palabras, muchas de las responses disponibles provienen directamente de Starlette. +También podrías usar `from starlette.responses import Response` o `from starlette.responses import JSONResponse`. +**FastAPI** proporciona las mismas `starlette.responses` como `fastapi.responses` solo por conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles provienen directamente de Starlette. -Y como la `Response` puede ser usada frecuentemente para configurar headers y cookies, **FastAPI** también la provee en `fastapi.Response`. +Y como el `Response` se puede usar frecuentemente para establecer headers y cookies, **FastAPI** también lo proporciona en `fastapi.Response`. /// ## Headers Personalizados -Ten en cuenta que se pueden añadir headers propietarios personalizados usando el prefijo 'X-'. +Ten en cuenta que los headers propietarios personalizados se pueden agregar usando el prefijo 'X-'. -Si tienes headers personalizados y deseas que un cliente pueda verlos en el navegador, es necesario que los añadas a tus configuraciones de CORS (puedes leer más en [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}), usando el parámetro `expose_headers` documentado en Starlette's CORS docs. +Pero si tienes headers personalizados que quieres que un cliente en un navegador pueda ver, necesitas agregarlos a tus configuraciones de CORS (leer más en [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}), usando el parámetro `expose_headers` documentado en la documentación CORS de Starlette. diff --git a/docs/es/docs/advanced/security/index.md b/docs/es/docs/advanced/security/index.md index 92de67d6a..e4ccb5978 100644 --- a/docs/es/docs/advanced/security/index.md +++ b/docs/es/docs/advanced/security/index.md @@ -1,19 +1,19 @@ # Seguridad Avanzada -## Características Adicionales +## Funcionalidades Adicionales -Hay algunas características adicionales para manejar la seguridad además de las que se tratan en el [Tutorial - Guía de Usuario: Seguridad](../../tutorial/security/index.md){.internal-link target=_blank}. +Hay algunas funcionalidades extra para manejar la seguridad aparte de las cubiertas en el [Tutorial - Guía del Usuario: Seguridad](../../tutorial/security/index.md){.internal-link target=_blank}. /// tip | Consejo -Las siguientes secciones **no necesariamente son "avanzadas"**. +Las siguientes secciones **no son necesariamente "avanzadas"**. -Y es posible que para tu caso de uso, la solución esté en alguna de ellas. +Y es posible que para tu caso de uso, la solución esté en una de ellas. /// -## Leer primero el Tutorial +## Lee primero el Tutorial -En las siguientes secciones asumimos que ya has leído el principal [Tutorial - Guía de Usuario: Seguridad](../../tutorial/security/index.md){.internal-link target=_blank}. +Las siguientes secciones asumen que ya leíste el [Tutorial - Guía del Usuario: Seguridad](../../tutorial/security/index.md){.internal-link target=_blank}. -Están basadas en los mismos conceptos, pero permiten algunas funcionalidades adicionales. +Todas están basadas en los mismos conceptos, pero permiten algunas funcionalidades adicionales. diff --git a/docs/es/docs/async.md b/docs/es/docs/async.md index 5ab2ff9a4..a5c272fb3 100644 --- a/docs/es/docs/async.md +++ b/docs/es/docs/async.md @@ -1,18 +1,18 @@ # Concurrencia y async / await -Detalles sobre la sintaxis `async def` para *path operation functions* y un poco de información sobre código asíncrono, concurrencia y paralelismo. +Detalles sobre la sintaxis `async def` para *path operation functions* y algunos antecedentes sobre el código asíncrono, la concurrencia y el paralelismo. -## ¿Tienes prisa? +## ¿Con prisa? TL;DR: -Si estás utilizando libraries de terceros que te dicen que las llames con `await`, del tipo: +Si estás usando paquetes de terceros que te dicen que los llames con `await`, como: ```Python results = await some_library() ``` -Entonces declara tus *path operation functions* con `async def` de la siguiente manera: +Entonces, declara tus *path operation functions* con `async def` así: ```Python hl_lines="2" @app.get('/') @@ -29,7 +29,7 @@ Solo puedes usar `await` dentro de funciones creadas con `async def`. --- -Si estás utilizando libraries de terceros que se comunican con algo (una base de datos, una API, el sistema de archivos, etc.) y no tienes soporte para `await` (este es el caso para la mayoría de las libraries de bases de datos), declara tus *path operation functions* de forma habitual, con solo `def`, de la siguiente manera: +Si estás usando un paquete de terceros que se comunica con algo (una base de datos, una API, el sistema de archivos, etc.) y no tiene soporte para usar `await` (este es actualmente el caso para la mayoría de los paquetes de base de datos), entonces declara tus *path operation functions* como normalmente, usando simplemente `def`, así: ```Python hl_lines="2" @app.get('/') @@ -40,7 +40,7 @@ def results(): --- -Si tu aplicación (de alguna manera) no tiene que comunicarse con nada más y en consecuencia esperar a que responda, usa `async def`. +Si tu aplicación (de alguna manera) no tiene que comunicarse con nada más y esperar a que responda, usa `async def`. --- @@ -48,17 +48,17 @@ Si simplemente no lo sabes, usa `def` normal. --- -**Nota**: puedes mezclar `def` y `async def` en tus *path operation functions* tanto como lo necesites y definir cada una utilizando la mejor opción para ti. FastAPI hará lo correcto con ellos. +**Nota**: Puedes mezclar `def` y `async def` en tus *path operation functions* tanto como necesites y definir cada una utilizando la mejor opción para ti. FastAPI hará lo correcto con ellas. De todos modos, en cualquiera de los casos anteriores, FastAPI seguirá funcionando de forma asíncrona y será extremadamente rápido. -Pero siguiendo los pasos anteriores, FastAPI podrá hacer algunas optimizaciones de rendimiento. +Pero al seguir los pasos anteriores, podrá hacer algunas optimizaciones de rendimiento. ## Detalles Técnicos -Las versiones modernas de Python tienen soporte para **"código asíncrono"** usando algo llamado **"coroutines"**, usando la sintaxis **`async` y `await`**. +Las versiones modernas de Python tienen soporte para **"código asíncrono"** utilizando algo llamado **"coroutines"**, con la sintaxis **`async` y `await`**. -Veamos esa frase por partes en las secciones siguientes: +Veamos esa frase por partes en las secciones a continuación: * **Código Asíncrono** * **`async` y `await`** @@ -66,203 +66,200 @@ Veamos esa frase por partes en las secciones siguientes: ## Código Asíncrono -El código asíncrono sólo significa que el lenguaje 💬 tiene una manera de decirle al sistema / programa 🤖 que, en algún momento del código, 🤖 tendrá que esperar a que *algo más* termine en otro sitio. Digamos que ese *algo más* se llama, por ejemplo, "archivo lento" 📝. +El código asíncrono simplemente significa que el lenguaje 💬 tiene una forma de decirle a la computadora / programa 🤖 que en algún momento del código, tendrá que esperar que *otra cosa* termine en otro lugar. Digamos que esa *otra cosa* se llama "archivo-lento" 📝. -Durante ese tiempo, el sistema puede hacer otras cosas, mientras "archivo lento" 📝 termina. +Entonces, durante ese tiempo, la computadora puede ir y hacer algún otro trabajo, mientras "archivo-lento" 📝 termina. -Entonces el sistema / programa 🤖 volverá cada vez que pueda, sea porque está esperando otra vez, porque 🤖 ha terminado todo el trabajo que tenía en ese momento. Y 🤖 verá si alguna de las tareas por las que estaba esperando ha terminado, haciendo lo que tenía que hacer. +Luego la computadora / programa 🤖 volverá cada vez que tenga una oportunidad porque está esperando nuevamente, o siempre que 🤖 haya terminado todo el trabajo que tenía en ese punto. Y 🤖 comprobará si alguna de las tareas que estaba esperando ya se han completado, haciendo lo que tenía que hacer. -Luego, 🤖 cogerá la primera tarea finalizada (digamos, nuestro "archivo lento" 📝) y continuará con lo que tenía que hacer con esa tarea. +Después, 🤖 toma la primera tarea que termine (digamos, nuestro "archivo-lento" 📝) y continúa con lo que tenía que hacer con ella. -Esa "espera de otra cosa" normalmente se refiere a operaciones I/O que son relativamente "lentas" (en relación a la velocidad del procesador y memoria RAM), como por ejemplo esperar por: +Ese "esperar otra cosa" normalmente se refiere a las operaciones de I/O que son relativamente "lentas" (comparadas con la velocidad del procesador y la memoria RAM), como esperar: -* los datos de cliente que se envían a través de la red -* los datos enviados por tu programa para ser recibidos por el cliente a través de la red -* el contenido de un archivo en disco para ser leído por el sistema y entregado al programa -* los contenidos que tu programa da al sistema para ser escritos en disco -* una operación relacionada con una API remota -* una operación de base de datos -* el retorno de resultados de una consulta de base de datos +* que los datos del cliente se envíen a través de la red +* que los datos enviados por tu programa sean recibidos por el cliente a través de la red +* que el contenido de un archivo en el disco sea leído por el sistema y entregado a tu programa +* que el contenido que tu programa entregó al sistema sea escrito en el disco +* una operación de API remota +* que una operación de base de datos termine +* que una query de base de datos devuelva los resultados * etc. -Como el tiempo de ejecución se consume principalmente al esperar a operaciones de I/O, las llaman operaciones "I/O bound". +Como el tiempo de ejecución se consume principalmente esperando operaciones de I/O, las llaman operaciones "I/O bound". -Se llama "asíncrono" porque el sistema / programa no tiene que estar "sincronizado" con la tarea lenta, esperando el momento exacto en que finaliza la tarea, sin hacer nada, para poder recoger el resultado de la tarea y continuar el trabajo. +Se llama "asíncrono" porque la computadora / programa no tiene que estar "sincronizado" con la tarea lenta, esperando el momento exacto en que la tarea termine, sin hacer nada, para poder tomar el resultado de la tarea y continuar el trabajo. -En lugar de eso, al ser un sistema "asíncrono", una vez finalizada, la tarea puede esperar un poco en la cola (algunos microsegundos) para que la computadora / programa termine lo que estaba haciendo, y luego vuelva para recoger los resultados y seguir trabajando con ellos. +En lugar de eso, al ser un sistema "asíncrono", una vez terminado, la tarea puede esperar un poco en la cola (algunos microsegundos) para que la computadora / programa termine lo que salió a hacer, y luego regrese para tomar los resultados y continuar trabajando con ellos. -Por "síncrono" (contrario a "asíncrono") también se usa habitualmente el término "secuencial", porque el sistema / programa sigue todos los pasos secuencialmente antes de cambiar a una tarea diferente, incluso si esos pasos implican esperas. +Para el "sincrónico" (contrario al "asíncrono") comúnmente también usan el término "secuencial", porque la computadora / programa sigue todos los pasos en secuencia antes de cambiar a una tarea diferente, incluso si esos pasos implican esperar. ### Concurrencia y Hamburguesas -El concepto de código **asíncrono** descrito anteriormente a veces también se llama **"concurrencia"**. Es diferente del **"paralelismo"**. +Esta idea de código **asíncrono** descrita anteriormente a veces también se llama **"concurrencia"**. Es diferente del **"paralelismo"**. -**Concurrencia** y **paralelismo** ambos se relacionan con "cosas diferentes que suceden más o menos al mismo tiempo". +**Concurrencia** y **paralelismo** ambos se relacionan con "diferentes cosas sucediendo más o menos al mismo tiempo". Pero los detalles entre *concurrencia* y *paralelismo* son bastante diferentes. -Para entender las diferencias, imagina la siguiente historia sobre hamburguesas: +Para ver la diferencia, imagina la siguiente historia sobre hamburguesas: ### Hamburguesas Concurrentes -Vas con la persona que te gusta 😍 a pedir comida rápida 🍔, haces cola mientras el cajero 💁 recoge los pedidos de las personas de delante tuyo. +Vas con tu crush a conseguir comida rápida, te pones en fila mientras el cajero toma los pedidos de las personas frente a ti. 😍 -illustration + -Llega tu turno, haces tu pedido de 2 hamburguesas impresionantes para esa persona 😍 y para ti. +Luego es tu turno, haces tu pedido de 2 hamburguesas muy sofisticadas para tu crush y para ti. 🍔🍔 -illustration + -El cajero 💁 le dice algo al chico de la cocina 👨‍🍳 para que sepa que tiene que preparar tus hamburguesas 🍔 (a pesar de que actualmente está preparando las de los clientes anteriores). +El cajero dice algo al cocinero en la cocina para que sepan que tienen que preparar tus hamburguesas (aunque actualmente están preparando las de los clientes anteriores). -illustration + -Pagas 💸. -El cajero 💁 te da el número de tu turno. +Pagas. 💸 + +El cajero te da el número de tu turno. -illustration + -Mientras esperas, vas con esa persona 😍 y eliges una mesa, se sientan y hablan durante un rato largo (ya que las hamburguesas son muy impresionantes y necesitan un rato para prepararse ✨🍔✨). +Mientras esperas, vas con tu crush y eliges una mesa, te sientas y hablas con tu crush por un largo rato (ya que tus hamburguesas son muy sofisticadas y toman un tiempo en prepararse). -Mientras te sientas en la mesa con esa persona 😍, esperando las hamburguesas 🍔, puedes disfrutar ese tiempo admirando lo increíble, inteligente, y bien que se ve ✨😍✨. +Mientras estás sentado en la mesa con tu crush, mientras esperas las hamburguesas, puedes pasar ese tiempo admirando lo increíble, lindo e inteligente que es tu crush ✨😍✨. -illustration + -Mientras esperas y hablas con esa persona 😍, de vez en cuando, verificas el número del mostrador para ver si ya es tu turno. +Mientras esperas y hablas con tu crush, de vez en cuando revisas el número mostrado en el mostrador para ver si ya es tu turno. -Al final, en algún momento, llega tu turno. Vas al mostrador, coges tus hamburguesas 🍔 y vuelves a la mesa. +Luego, en algún momento, finalmente es tu turno. Vas al mostrador, obtienes tus hamburguesas y vuelves a la mesa. -illustration + -Tú y esa persona 😍 se comen las hamburguesas 🍔 y la pasan genial ✨. +Tú y tu crush comen las hamburguesas y pasan un buen rato. ✨ -illustration + /// info | Información -Las ilustraciones fueron creados por Ketrina Thompson. 🎨 +Hermosas ilustraciones de Ketrina Thompson. 🎨 /// --- -Imagina que eres el sistema / programa 🤖 en esa historia. +Imagina que eres la computadora / programa 🤖 en esa historia. -Mientras estás en la cola, estás quieto 😴, esperando tu turno, sin hacer nada muy "productivo". Pero la línea va rápida porque el cajero 💁 solo recibe los pedidos (no los prepara), así que está bien. +Mientras estás en la fila, estás inactivo 😴, esperando tu turno, sin hacer nada muy "productivo". Pero la fila es rápida porque el cajero solo está tomando los pedidos (no preparándolos), así que está bien. -Luego, cuando llega tu turno, haces un trabajo "productivo" real 🤓, procesas el menú, decides lo que quieres, lo que quiere esa persona 😍, pagas 💸, verificas que das el billete o tarjeta correctos, verificas que te cobren correctamente, que el pedido tiene los artículos correctos, etc. +Luego, cuando es tu turno, haces un trabajo realmente "productivo", procesas el menú, decides lo que quieres, obtienes la elección de tu crush, pagas, verificas que das el billete o tarjeta correctos, verificas que te cobren correctamente, verificas que el pedido tenga los artículos correctos, etc. -Pero entonces, aunque aún no tienes tus hamburguesas 🍔, el trabajo hecho con el cajero 💁 está "en pausa" ⏸, porque debes esperar 🕙 a que tus hamburguesas estén listas. +Pero luego, aunque todavía no tienes tus hamburguesas, tu trabajo con el cajero está "en pausa" ⏸, porque tienes que esperar 🕙 a que tus hamburguesas estén listas. -Pero como te alejas del mostrador y te sientas en la mesa con un número para tu turno, puedes cambiar tu atención 🔀 a esa persona 😍 y "trabajar" ⏯ 🤓 en eso. Entonces nuevamente estás haciendo algo muy "productivo" 🤓, como coquetear con esa persona 😍. +Pero como te alejas del mostrador y te sientas en la mesa con un número para tu turno, puedes cambiar 🔀 tu atención a tu crush, y "trabajar" ⏯ 🤓 en eso. Luego, nuevamente estás haciendo algo muy "productivo" como es coquetear con tu crush 😍. -Después, el 💁 cajero dice "he terminado de hacer las hamburguesas" 🍔 poniendo tu número en la pantalla del mostrador, pero no saltas al momento que el número que se muestra es el tuyo. Sabes que nadie robará tus hamburguesas 🍔 porque tienes el número de tu turno y ellos tienen el suyo. +Luego el cajero 💁 dice "he terminado de hacer las hamburguesas" al poner tu número en el mostrador, pero no saltas como loco inmediatamente cuando el número mostrado cambia a tu número de turno. Sabes que nadie robará tus hamburguesas porque tienes el número de tu turno, y ellos tienen el suyo. -Así que esperas a que esa persona 😍 termine la historia (terminas el trabajo actual ⏯ / tarea actual que se está procesando 🤓), sonríes gentilmente y le dices que vas por las hamburguesas ⏸. +Así que esperas a que tu crush termine la historia (termine el trabajo ⏯ / tarea actual que se está procesando 🤓), sonríes amablemente y dices que vas por las hamburguesas ⏸. -Luego vas al mostrador 🔀, a la tarea inicial que ya está terminada ⏯, recoges las hamburguesas 🍔, les dices gracias y las llevas a la mesa. Eso termina esa fase / tarea de interacción con el mostrador ⏹. Eso a su vez, crea una nueva tarea, "comer hamburguesas" 🔀 ⏯, pero la anterior de "conseguir hamburguesas" está terminada ⏹. +Luego vas al mostrador 🔀, a la tarea inicial que ahora está terminada ⏯, recoges las hamburguesas, das las gracias y las llevas a la mesa. Eso termina ese paso / tarea de interacción con el mostrador ⏹. Eso a su vez, crea una nueva tarea, de "comer hamburguesas" 🔀 ⏯, pero la anterior de "obtener hamburguesas" ha terminado ⏹. ### Hamburguesas Paralelas -Ahora imagina que estas no son "Hamburguesas Concurrentes" sino "Hamburguesas Paralelas". +Ahora imaginemos que estas no son "Hamburguesas Concurrentes", sino "Hamburguesas Paralelas". -Vas con la persona que te gusta 😍 por comida rápida paralela 🍔. +Vas con tu crush a obtener comida rápida paralela. -Haces la cola mientras varios cajeros (digamos 8) que a la vez son cocineros 👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳 toman los pedidos de las personas que están delante de ti. +Te pones en fila mientras varios (digamos 8) cajeros que al mismo tiempo son cocineros toman los pedidos de las personas frente a ti. -Todos los que están antes de ti están esperando 🕙 que sus hamburguesas 🍔 estén listas antes de dejar el mostrador porque cada uno de los 8 cajeros prepara la hamburguesa de inmediato antes de recibir el siguiente pedido. +Todos antes que tú están esperando a que sus hamburguesas estén listas antes de dejar el mostrador porque cada uno de los 8 cajeros va y prepara la hamburguesa de inmediato antes de obtener el siguiente pedido. -illustration + -Entonces finalmente es tu turno, haces tu pedido de 2 hamburguesas 🍔 impresionantes para esa persona 😍 y para ti. +Luego, finalmente es tu turno, haces tu pedido de 2 hamburguesas muy sofisticadas para tu crush y para ti. Pagas 💸. -illustration + -El cajero va a la cocina 👨‍🍳. +El cajero va a la cocina. -Esperas, de pie frente al mostrador 🕙, para que nadie más recoja tus hamburguesas 🍔, ya que no hay números para los turnos. +Esperas, de pie frente al mostrador 🕙, para que nadie más tome tus hamburguesas antes que tú, ya que no hay números para los turnos. -illustration + -Como tu y esa persona 😍 están ocupados en impedir que alguien se ponga delante y recoja tus hamburguesas apenas llegan 🕙, tampoco puedes prestarle atención a esa persona 😞. +Como tú y tu crush están ocupados no dejando que nadie se interponga y tome tus hamburguesas cuando lleguen, no puedes prestar atención a tu crush. 😞 -Este es un trabajo "síncrono", estás "sincronizado" con el cajero / cocinero 👨‍🍳. Tienes que esperar y estar allí en el momento exacto en que el cajero / cocinero 👨‍🍳 termina las hamburguesas 🍔 y te las da, o de lo contrario, alguien más podría cogerlas. +Este es un trabajo "sincrónico", estás "sincronizado" con el cajero/cocinero 👨‍🍳. Tienes que esperar 🕙 y estar allí en el momento exacto en que el cajero/cocinero 👨‍🍳 termine las hamburguesas y te las entregue, o de lo contrario, alguien más podría tomarlas. -illustration + -Luego, el cajero / cocinero 👨‍🍳 finalmente regresa con tus hamburguesas 🍔, después de mucho tiempo esperando 🕙 frente al mostrador. +Luego tu cajero/cocinero 👨‍🍳 finalmente regresa con tus hamburguesas, después de mucho tiempo esperando 🕙 allí frente al mostrador. -illustration + -Coges tus hamburguesas 🍔 y vas a la mesa con esa persona 😍. +Tomas tus hamburguesas y vas a la mesa con tu crush. -Sólo las comes y listo 🍔 ⏹. +Simplemente las comes, y has terminado. ⏹ -illustration + -No has hablado ni coqueteado mucho, ya que has pasado la mayor parte del tiempo esperando 🕙 frente al mostrador 😞. +No hubo mucho hablar o coquetear ya que la mayor parte del tiempo se dedicó a esperar 🕙 frente al mostrador. 😞 /// info | Información -Las ilustraciones fueron creados por Ketrina Thompson. 🎨 +Hermosas ilustraciones de Ketrina Thompson. 🎨 /// --- -En este escenario de las hamburguesas paralelas, tú eres un sistema / programa 🤖 con dos procesadores (tú y la persona que te gusta 😍), ambos esperando 🕙 y dedicando su atención ⏯ a estar "esperando en el mostrador" 🕙 durante mucho tiempo. +En este escenario de las hamburguesas paralelas, eres una computadora / programa 🤖 con dos procesadores (tú y tu crush), ambos esperando 🕙 y dedicando su atención ⏯ a estar "esperando en el mostrador" 🕙 por mucho tiempo. -La tienda de comida rápida tiene 8 procesadores (cajeros / cocineros) 👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳. Mientras que la tienda de hamburguesas concurrentes podría haber tenido solo 2 (un cajero y un cocinero) 💁 👨‍🍳. +La tienda de comida rápida tiene 8 procesadores (cajeros/cocineros). Mientras que la tienda de hamburguesas concurrentes podría haber tenido solo 2 (un cajero y un cocinero). -Pero aún así, la experiencia final no es la mejor 😞. +Pero aún así, la experiencia final no es la mejor. 😞 --- -Esta sería la historia paralela equivalente de las hamburguesas 🍔. +Esta sería la historia equivalente de las hamburguesas paralelas. 🍔 -Para un ejemplo más "real" de ésto, imagina un banco. +Para un ejemplo más "de la vida real" de esto, imagina un banco. -Hasta hace poco, la mayoría de los bancos tenían varios cajeros 👨‍💼👨‍💼👨‍💼👨‍💼 y una gran línea 🕙🕙🕙🕙🕙🕙🕙🕙. +Hasta hace poco, la mayoría de los bancos tenían múltiples cajeros 👨‍💼👨‍💼👨‍💼👨‍💼 y una gran fila 🕙🕙🕙🕙🕙🕙🕙🕙. Todos los cajeros haciendo todo el trabajo con un cliente tras otro 👨‍💼⏯. -Y tienes que esperar 🕙 en la fila durante mucho tiempo o perderás tu turno. - -Probablemente no querrás llevar contigo a la persona que te gusta 😍 a hacer encargos al banco 🏦. +Y tienes que esperar 🕙 en la fila por mucho tiempo o pierdes tu turno. -### Conclusión de las Hamburguesa +Probablemente no querrías llevar a tu crush 😍 contigo a hacer trámites en el banco 🏦. -En este escenario de "hamburguesas de comida rápida con tu pareja", debido a que hay mucha espera 🕙, tiene mucho más sentido tener un sistema con concurrencia ⏸🔀⏯. +### Conclusión de las Hamburguesas -Este es el caso de la mayoría de las aplicaciones web. +En este escenario de "hamburguesas de comida rápida con tu crush", como hay mucha espera 🕙, tiene mucho más sentido tener un sistema concurrente ⏸🔀⏯. -Muchos, muchos usuarios, pero el servidor está esperando 🕙 el envío de las peticiones ya que su conexión no es buena. +Este es el caso para la mayoría de las aplicaciones web. -Y luego esperando 🕙 nuevamente a que las respuestas retornen. +Muchos, muchos usuarios, pero tu servidor está esperando 🕙 su conexión no tan buena para enviar sus requests. -Esta "espera" 🕙 se mide en microsegundos, pero aun así, sumando todo, al final es mucha espera. +Y luego esperar 🕙 nuevamente a que los responses regresen. -Es por eso que tiene mucho sentido usar código asíncrono ⏸🔀⏯ para las API web. +Esta "espera" 🕙 se mide en microsegundos, pero aún así, sumándolo todo, es mucha espera al final. -La mayoría de los framework populares de Python existentes (incluidos Flask y Django) se crearon antes de que existieran las nuevas funciones asíncronas en Python. Por lo tanto, las formas en que pueden implementarse admiten la ejecución paralela y una forma más antigua de ejecución asíncrona que no es tan potente como la actual. +Por eso tiene mucho sentido usar código asíncrono ⏸🔀⏯ para las APIs web. -A pesar de que la especificación principal para Python web asíncrono (ASGI) se desarrolló en Django, para agregar soporte para WebSockets. - -Ese tipo de asincronía es lo que hizo popular a NodeJS (aunque NodeJS no es paralelo) y esa es la fortaleza de Go como lenguaje de programación. +Este tipo de asincronía es lo que hizo popular a NodeJS (aunque NodeJS no es paralelo) y esa es la fortaleza de Go como lenguaje de programación. Y ese es el mismo nivel de rendimiento que obtienes con **FastAPI**. -Y como puede tener paralelismo y asincronía al mismo tiempo, obtienes un mayor rendimiento que la mayoría de los frameworks de NodeJS probados y a la par con Go, que es un lenguaje compilado más cercano a C (todo gracias Starlette). +Y como puedes tener paralelismo y asincronía al mismo tiempo, obtienes un mayor rendimiento que la mayoría de los frameworks de NodeJS probados y a la par con Go, que es un lenguaje compilado más cercano a C (todo gracias a Starlette). ### ¿Es la concurrencia mejor que el paralelismo? ¡No! Esa no es la moraleja de la historia. -La concurrencia es diferente al paralelismo. Y es mejor en escenarios **específicos** que implican mucha espera. Debido a eso, generalmente es mucho mejor que el paralelismo para el desarrollo de aplicaciones web. Pero no para todo. +La concurrencia es diferente del paralelismo. Y es mejor en escenarios **específicos** que implican mucha espera. Debido a eso, generalmente es mucho mejor que el paralelismo para el desarrollo de aplicaciones web. Pero no para todo. -Entonces, para explicar eso, imagina la siguiente historia corta: +Así que, para equilibrar eso, imagina la siguiente historia corta: > Tienes que limpiar una casa grande y sucia. @@ -270,80 +267,80 @@ Entonces, para explicar eso, imagina la siguiente historia corta: --- -No hay esperas 🕙, solo hay mucho trabajo por hacer, en varios lugares de la casa. +No hay esperas 🕙 en ninguna parte, solo mucho trabajo por hacer, en múltiples lugares de la casa. -Podrías tener turnos como en el ejemplo de las hamburguesas, primero la sala de estar, luego la cocina, pero como no estás esperando nada, solo limpiando y limpiando, los turnos no afectarían nada. +Podrías tener turnos como en el ejemplo de las hamburguesas, primero la sala de estar, luego la cocina, pero como no estás esperando 🕙 nada, solo limpiando y limpiando, los turnos no afectarían nada. Tomaría la misma cantidad de tiempo terminar con o sin turnos (concurrencia) y habrías hecho la misma cantidad de trabajo. -Pero en este caso, si pudieras traer a los 8 ex cajeros / cocineros / ahora limpiadores 👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳👨‍🍳, y cada uno de ellos (y tú) podría tomar una zona de la casa para limpiarla, podría hacer todo el trabajo en **paralelo**, con la ayuda adicional y terminar mucho antes. +Pero en este caso, si pudieras traer a los 8 ex-cajeros/cocineros/ahora-limpiadores, y cada uno de ellos (más tú) pudiera tomar una zona de la casa para limpiarla, podrías hacer todo el trabajo en **paralelo**, con la ayuda extra, y terminar mucho antes. -En este escenario, cada uno de los limpiadores (incluido tú) sería un procesador, haciendo su parte del trabajo. +En este escenario, cada uno de los limpiadores (incluyéndote) sería un procesador, haciendo su parte del trabajo. -Y como la mayor parte del tiempo de ejecución lo coge el trabajo real (en lugar de esperar), y el trabajo en un sistema lo realiza una CPU , a estos problemas se les llama "CPU bound". +Y como la mayor parte del tiempo de ejecución se dedica al trabajo real (en lugar de esperar), y el trabajo en una computadora lo realiza una CPU, llaman a estos problemas "CPU bound". --- -Ejemplos típicos de operaciones dependientes de CPU son cosas que requieren un procesamiento matemático complejo. +Ejemplos comunes de operaciones limitadas por la CPU son cosas que requieren procesamiento matemático complejo. Por ejemplo: -* **Audio** o **procesamiento de imágenes**. -* **Visión por computadora**: una imagen está compuesta de millones de píxeles, cada píxel tiene 3 valores / colores, procesamiento que normalmente requiere calcular algo en esos píxeles, todo al mismo tiempo. -* **Machine Learning**: normalmente requiere muchas multiplicaciones de "matrices" y "vectores". Imagina en una enorme hoja de cálculo con números y tener que multiplicarlos todos al mismo tiempo. -* **Deep Learning**: este es un subcampo de Machine Learning, por lo tanto, aplica lo mismo. Es solo que no hay una sola hoja de cálculo de números para multiplicar, sino un gran conjunto de ellas, y en muchos casos, usa un procesador especial para construir y / o usar esos modelos. +* **Procesamiento de audio** o **imágenes**. +* **Visión por computadora**: una imagen está compuesta de millones de píxeles, cada píxel tiene 3 valores / colores, procesar eso normalmente requiere calcular algo en esos píxeles, todos al mismo tiempo. +* **Machine Learning**: normalmente requiere muchas multiplicaciones de "matrices" y "vectores". Piensa en una enorme hoja de cálculo con números y multiplicando todos juntos al mismo tiempo. +* **Deep Learning**: este es un subcampo de Machine Learning, por lo tanto, se aplica lo mismo. Es solo que no hay una sola hoja de cálculo de números para multiplicar, sino un enorme conjunto de ellas, y en muchos casos, usas un procesador especial para construir y / o usar esos modelos. ### Concurrencia + Paralelismo: Web + Machine Learning -Con **FastAPI** puedes aprovechar la concurrencia que es muy común para el desarrollo web (atractivo principal de NodeJS). +Con **FastAPI** puedes aprovechar la concurrencia que es muy común para el desarrollo web (la misma atracción principal de NodeJS). -Pero también puedes aprovechar los beneficios del paralelismo y el multiprocesamiento (tener múltiples procesos ejecutándose en paralelo) para cargas de trabajo **CPU bound** como las de los sistemas de Machine Learning. +Pero también puedes explotar los beneficios del paralelismo y la multiprocesamiento (tener múltiples procesos ejecutándose en paralelo) para cargas de trabajo **CPU bound** como las de los sistemas de Machine Learning. -Eso, más el simple hecho de que Python es el lenguaje principal para **Data Science**, Machine Learning y especialmente Deep Learning, hacen de FastAPI una muy buena combinación para las API y aplicaciones web de Data Science / Machine Learning (entre muchas otras). +Eso, más el simple hecho de que Python es el lenguaje principal para **Data Science**, Machine Learning y especialmente Deep Learning, hacen de FastAPI una muy buena opción para APIs web de Data Science / Machine Learning y aplicaciones (entre muchas otras). -Para ver cómo lograr este paralelismo en producción, consulta la sección sobre [Despliegue](deployment/index.md){.internal-link target=_blank}. +Para ver cómo lograr este paralelismo en producción, consulta la sección sobre [Deployment](deployment/index.md){.internal-link target=_blank}. ## `async` y `await` -Las versiones modernas de Python tienen una forma muy intuitiva de definir código asíncrono. Esto hace que se vea como un código "secuencial" normal y que haga la "espera" por ti en los momentos correctos. +Las versiones modernas de Python tienen una forma muy intuitiva de definir código asíncrono. Esto hace que se vea igual que el código "secuencial" normal y hace el "wait" por ti en los momentos adecuados. -Cuando hay una operación que requerirá esperar antes de dar los resultados y tiene soporte para estas nuevas características de Python, puedes programarlo como: +Cuando hay una operación que requerirá esperar antes de dar los resultados y tiene soporte para estas nuevas funcionalidades de Python, puedes programarlo así: ```Python burgers = await get_burgers(2) ``` -La clave aquí es `await`. Eso le dice a Python que tiene que esperar ⏸ a que `get_burgers (2)` termine de hacer lo suyo 🕙 antes de almacenar los resultados en `hamburguesas`. Con eso, Python sabrá que puede ir y hacer otra cosa 🔀 ⏯ mientras tanto (como recibir otra solicitud). +La clave aquí es el `await`. Dice a Python que tiene que esperar ⏸ a que `get_burgers(2)` termine de hacer su cosa 🕙 antes de almacenar los resultados en `burgers`. Con eso, Python sabrá que puede ir y hacer algo más 🔀 ⏯ mientras tanto (como recibir otro request). -Para que `await` funcione, tiene que estar dentro de una función que admita esta asincronía. Para hacer eso, simplemente lo declaras con `async def`: +Para que `await` funcione, tiene que estar dentro de una función que soporte esta asincronía. Para hacer eso, solo declara la función con `async def`: ```Python hl_lines="1" async def get_burgers(number: int): - # Do some asynchronous stuff to create the burgers + # Hacer algunas cosas asíncronas para crear las hamburguesas return burgers ``` -...en vez de `def`: +...en lugar de `def`: ```Python hl_lines="2" -# This is not asynchronous +# Esto no es asíncrono def get_sequential_burgers(number: int): - # Do some sequential stuff to create the burgers + # Hacer algunas cosas secuenciales para crear las hamburguesas return burgers ``` -Con `async def`, Python sabe que, dentro de esa función, debe tener en cuenta las expresiones `wait` y que puede "pausar" ⏸ la ejecución de esa función e ir a hacer otra cosa 🔀 antes de regresar. +Con `async def`, Python sabe que, dentro de esa función, tiene que estar atento a las expresiones `await`, y que puede "pausar" ⏸ la ejecución de esa función e ir a hacer algo más 🔀 antes de regresar. -Cuando desees llamar a una función `async def`, debes "esperarla". Entonces, esto no funcionará: +Cuando deseas llamar a una función `async def`, tienes que "await" dicha función. Así que, esto no funcionará: ```Python -# Esto no funcionará, porque get_burgers se definió con: async def -hamburguesas = get_burgers (2) +# Esto no funcionará, porque get_burgers fue definido con: async def +burgers = get_burgers(2) ``` --- -Por lo tanto, si estás utilizando una library que te dice que puedes llamarla con `await`, debes crear las *path operation functions* que la usan con `async def`, como en: +Así que, si estás usando un paquete que te dice que puedes llamarlo con `await`, necesitas crear las *path operation functions* que lo usen con `async def`, como en: ```Python hl_lines="2-3" @app.get('/burgers') @@ -354,15 +351,25 @@ async def read_burgers(): ### Más detalles técnicos -Es posible que hayas notado que `await` solo se puede usar dentro de las funciones definidas con `async def`. +Podrías haber notado que `await` solo se puede usar dentro de funciones definidas con `async def`. + +Pero al mismo tiempo, las funciones definidas con `async def` deben ser "awaited". Por lo tanto, las funciones con `async def` solo se pueden llamar dentro de funciones definidas con `async def` también. + +Entonces, sobre el huevo y la gallina, ¿cómo llamas a la primera función `async`? + +Si estás trabajando con **FastAPI** no tienes que preocuparte por eso, porque esa "primera" función será tu *path operation function*, y FastAPI sabrá cómo hacer lo correcto. + +Pero si deseas usar `async` / `await` sin FastAPI, también puedes hacerlo. + +### Escribe tu propio código async -Pero al mismo tiempo, las funciones definidas con `async def` deben ser "esperadas". Por lo tanto, las funciones con `async def` solo se pueden invocar dentro de las funciones definidas con `async def` también. +Starlette (y **FastAPI**) están basados en AnyIO, lo que lo hace compatible tanto con la librería estándar de Python asyncio como con Trio. -Entonces, relacionado con la paradoja del huevo y la gallina, ¿cómo se llama a la primera función `async`? +En particular, puedes usar directamente AnyIO para tus casos de uso avanzados de concurrencia que requieran patrones más avanzados en tu propio código. -Si estás trabajando con **FastAPI** no tienes que preocuparte por eso, porque esa "primera" función será tu *path operation function*, y FastAPI sabrá cómo hacer lo pertinente. +E incluso si no estuvieras usando FastAPI, también podrías escribir tus propias aplicaciones asíncronas con AnyIO para ser altamente compatibles y obtener sus beneficios (p.ej. *concurrencia estructurada*). -En el caso de que desees usar `async` / `await` sin FastAPI, revisa la documentación oficial de Python. +Creé otro paquete sobre AnyIO, como una capa delgada, para mejorar un poco las anotaciones de tipos y obtener mejor **autocompletado**, **errores en línea**, etc. También tiene una introducción amigable y tutorial para ayudarte a **entender** y escribir **tu propio código async**: Asyncer. Sería particularmente útil si necesitas **combinar código async con regular** (bloqueante/sincrónico). ### Otras formas de código asíncrono @@ -370,68 +377,68 @@ Este estilo de usar `async` y `await` es relativamente nuevo en el lenguaje. Pero hace que trabajar con código asíncrono sea mucho más fácil. -Esta misma sintaxis (o casi idéntica) también se incluyó recientemente en las versiones modernas de JavaScript (en Browser y NodeJS). +Esta misma sintaxis (o casi idéntica) también se incluyó recientemente en las versiones modernas de JavaScript (en el Navegador y NodeJS). -Pero antes de eso, manejar código asíncrono era bastante más complejo y difícil. +Pero antes de eso, manejar el código asíncrono era mucho más complejo y difícil. -En versiones anteriores de Python, podrías haber utilizado threads o Gevent. Pero el código es mucho más complejo de entender, depurar y desarrollar. +En versiones previas de Python, podrías haber usado hilos o Gevent. Pero el código es mucho más complejo de entender, depurar y razonar. -En versiones anteriores de NodeJS / Browser JavaScript, habrías utilizado "callbacks". Lo que conduce a callback hell. +En versiones previas de NodeJS / JavaScript en el Navegador, habrías usado "callbacks". Lo que lleva al callback hell. ## Coroutines -**Coroutine** es un término sofisticado para referirse a la cosa devuelta por una función `async def`. Python sabe que es algo así como una función que puede iniciar y que terminará en algún momento, pero que también podría pausarse ⏸ internamente, siempre que haya un `await` dentro de ella. +**Coroutines** es simplemente el término muy elegante para la cosa que devuelve una función `async def`. Python sabe que es algo parecido a una función, que puede comenzar y que terminará en algún momento, pero que podría pausar ⏸ internamente también, siempre que haya un `await` dentro de él. -Pero toda esta funcionalidad de usar código asincrónico con `async` y `await` se resume muchas veces como usar "coroutines". Es comparable a la característica principal de Go, las "Goroutines". +Pero toda esta funcionalidad de usar código asíncrono con `async` y `await` a menudo se resume como utilizar "coroutines". Es comparable a la funcionalidad clave principal de Go, las "Goroutines". ## Conclusión Veamos la misma frase de arriba: -> Las versiones modernas de Python tienen soporte para **"código asíncrono"** usando algo llamado **"coroutines"**, con la sintaxis **`async` y `await`**. +> Las versiones modernas de Python tienen soporte para **"código asíncrono"** utilizando algo llamado **"coroutines"**, con la sintaxis **`async` y `await`**. -Eso ya debería tener más sentido ahora. ✨ +Eso debería tener más sentido ahora. ✨ Todo eso es lo que impulsa FastAPI (a través de Starlette) y lo que hace que tenga un rendimiento tan impresionante. -## Detalles muy técnicos +## Detalles Muy Técnicos /// warning | Advertencia Probablemente puedas saltarte esto. -Estos son detalles muy técnicos de cómo **FastAPI** funciona a muy bajo nivel. +Estos son detalles muy técnicos de cómo funciona **FastAPI** en su interior. -Si tienes bastante conocimiento técnico (coroutines, threads, bloqueos, etc.) y tienes curiosidad acerca de cómo FastAPI gestiona `async def` vs `def` normal, continúa. +Si tienes bastante conocimiento técnico (coroutines, hilos, bloqueo, etc.) y tienes curiosidad sobre cómo FastAPI maneja `async def` vs `def` normal, adelante. /// -### Path operation functions +### Funciones de *path operation* -Cuando declaras una *path operation function* con `def` normal en lugar de `async def`, se ejecuta en un threadpool externo que luego es "awaited", en lugar de ser llamado directamente (ya que bloquearía el servidor). +Cuando declaras una *path operation function* con `def` normal en lugar de `async def`, se ejecuta en un threadpool externo que luego es esperado, en lugar de ser llamado directamente (ya que bloquearía el servidor). -Si vienes de otro framework asíncrono que no funciona de la manera descrita anteriormente y estás acostumbrado a definir *path operation functions* del tipo sólo cálculo con `def` simple para una pequeña ganancia de rendimiento (aproximadamente 100 nanosegundos), ten en cuenta que en **FastAPI** el efecto sería bastante opuesto. En estos casos, es mejor usar `async def` a menos que tus *path operation functions* usen un código que realice el bloqueo I/O. +Si vienes de otro framework async que no funciona de la manera descrita anteriormente y estás acostumbrado a definir funciones de *path operation* solo de cómputo trivial con `def` normal para una pequeña ganancia de rendimiento (alrededor de 100 nanosegundos), ten en cuenta que en **FastAPI** el efecto sería bastante opuesto. En estos casos, es mejor usar `async def` a menos que tus *path operation functions* usen código que realice I/O de bloqueo. -Aún así, en ambas situaciones, es probable que **FastAPI** sea [aún más rápido](index.md#rendimiento){.Internal-link target=_blank} que (o al menos comparable) a tu framework anterior. +Aun así, en ambas situaciones, es probable que **FastAPI** [siga siendo más rápida](index.md#performance){.internal-link target=_blank} que (o al menos comparable a) tu framework anterior. ### Dependencias -Lo mismo se aplica para las dependencias. Si una dependencia es una función estándar `def` en lugar de `async def`, se ejecuta en el threadpool externo. +Lo mismo aplica para las [dependencias](tutorial/dependencies/index.md){.internal-link target=_blank}. Si una dependencia es una función estándar `def` en lugar de `async def`, se ejecuta en el threadpool externo. -### Subdependencias +### Sub-dependencias -Puedes tener múltiples dependencias y subdependencias que se requieren unas a otras (como parámetros de las definiciones de cada función), algunas de ellas pueden crearse con `async def` y otras con `def` normal. Igual todo seguiría funcionando correctamente, y las creadas con `def` normal se llamarían en un thread externo (del threadpool) en lugar de ser "awaited". +Puedes tener múltiples dependencias y [sub-dependencias](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} requiriéndose mutuamente (como parámetros de las definiciones de funciones), algunas de ellas podrían ser creadas con `async def` y algunas con `def` normal. Aun funcionará, y las que fueron creadas con `def` normal serían llamadas en un hilo externo (del threadpool) en lugar de ser "awaited". -### Otras funciones de utilidades +### Otras funciones de utilidad -Cualquier otra función de utilidad que llames directamente se puede crear con `def` o `async def` normales y FastAPI no afectará la manera en que la llames. +Cualquier otra función de utilidad que llames directamente puede ser creada con `def` normal o `async def` y FastAPI no afectará la forma en que la llames. -Esto contrasta con las funciones que FastAPI llama por ti: las *path operation functions* y dependencias. +Esto contrasta con las funciones que FastAPI llama por ti: *path operation functions* y dependencias. -Si tu función de utilidad es creada con `def` normal, se llamará directamente (tal cual la escribes en tu código), no en un threadpool, si la función se crea con `async def`, entonces debes usar `await` con esa función cuando la llamas en tu código. +Si tu función de utilidad es una función normal con `def`, será llamada directamente (como la escribas en tu código), no en un threadpool; si la función es creada con `async def` entonces deberías "await" por esa función cuando la llames en tu código. --- -Nuevamente, estos son detalles muy técnicos que probablemente sólo son útiles si los viniste a buscar expresamente. +Nuevamente, estos son detalles muy técnicos que probablemente serían útiles si los buscaste. -De lo contrario, la guía de la sección anterior debería ser suficiente: ¿Tienes prisa?. +De lo contrario, deberías estar bien con las pautas de la sección anterior: ¿Con prisa?. diff --git a/docs/es/docs/benchmarks.md b/docs/es/docs/benchmarks.md index 3e02d4e9f..49d65b6ba 100644 --- a/docs/es/docs/benchmarks.md +++ b/docs/es/docs/benchmarks.md @@ -1,33 +1,34 @@ # Benchmarks -Los benchmarks independientes de TechEmpower muestran aplicaciones de **FastAPI** que se ejecutan en Uvicorn como uno de los frameworks de Python más rápidos disponibles, solo por debajo de Starlette y Uvicorn (utilizados internamente por FastAPI). (*) +Los benchmarks independientes de TechEmpower muestran aplicaciones de **FastAPI** ejecutándose bajo Uvicorn como uno de los frameworks de Python más rápidos disponibles, solo por debajo de Starlette y Uvicorn en sí mismos (utilizados internamente por FastAPI). -Pero al comprobar benchmarks y comparaciones debes tener en cuenta lo siguiente. +Pero al revisar benchmarks y comparaciones, debes tener en cuenta lo siguiente. ## Benchmarks y velocidad -Cuando revisas los benchmarks, es común ver varias herramientas de diferentes tipos comparadas como equivalentes. +Cuando ves los benchmarks, es común ver varias herramientas de diferentes tipos comparadas como equivalentes. -Específicamente, para ver Uvicorn, Starlette y FastAPI comparadas entre sí (entre muchas otras herramientas). +Específicamente, ver Uvicorn, Starlette y FastAPI comparados juntos (entre muchas otras herramientas). -Cuanto más sencillo sea el problema resuelto por la herramienta, mejor rendimiento obtendrá. Y la mayoría de los benchmarks no prueban las funciones adicionales proporcionadas por la herramienta. +Cuanto más simple sea el problema resuelto por la herramienta, mejor rendimiento tendrá. Y la mayoría de los benchmarks no prueban las funcionalidades adicionales proporcionadas por la herramienta. -La jerarquía sería: +La jerarquía es como: -* **Uvicorn**: como servidor ASGI +* **Uvicorn**: un servidor ASGI * **Starlette**: (usa Uvicorn) un microframework web - * **FastAPI**: (usa Starlette) un microframework API con varias características adicionales para construir APIs, con validación de datos, etc. + * **FastAPI**: (usa Starlette) un microframework para APIs con varias funcionalidades adicionales para construir APIs, con validación de datos, etc. + * **Uvicorn**: * Tendrá el mejor rendimiento, ya que no tiene mucho código extra aparte del propio servidor. - * No escribirías una aplicación directamente en Uvicorn. Eso significaría que tu código tendría que incluir más o menos, al menos, todo el código proporcionado por Starlette (o **FastAPI**). Y si hicieras eso, tu aplicación final tendría la misma sobrecarga que si hubieras usado un framework y minimizado el código de tu aplicación y los errores. - * Si estás comparando Uvicorn, compáralo con los servidores de aplicaciones Daphne, Hypercorn, uWSGI, etc. + * No escribirías una aplicación directamente en Uvicorn. Eso significaría que tu código tendría que incluir, más o menos, al menos, todo el código proporcionado por Starlette (o **FastAPI**). Y si hicieras eso, tu aplicación final tendría la misma carga que si hubieras usado un framework, minimizando el código de tu aplicación y los bugs. + * Si estás comparando Uvicorn, compáralo con Daphne, Hypercorn, uWSGI, etc. Servidores de aplicaciones. * **Starlette**: - * Tendrá el siguiente mejor desempeño, después de Uvicorn. De hecho, Starlette usa Uvicorn para correr. Por lo tanto, probablemente sólo pueda volverse "más lento" que Uvicorn al tener que ejecutar más código. - * Pero te proporciona las herramientas para crear aplicaciones web simples, con routing basado en paths, etc. + * Tendrá el siguiente mejor rendimiento, después de Uvicorn. De hecho, Starlette usa Uvicorn para ejecutarse. Así que probablemente solo pueda ser "más lento" que Uvicorn por tener que ejecutar más código. + * Pero te proporciona las herramientas para construir aplicaciones web sencillas, con enrutamiento basado en paths, etc. * Si estás comparando Starlette, compáralo con Sanic, Flask, Django, etc. Frameworks web (o microframeworks). * **FastAPI**: - * De la misma manera que Starlette usa Uvicorn y no puede ser más rápido que él, **FastAPI** usa Starlette, por lo que no puede ser más rápido que él. - * * FastAPI ofrece más características además de las de Starlette. Funciones que casi siempre necesitas al crear una API, como validación y serialización de datos. Y al usarlo, obtienes documentación automática de forma gratuita (la documentación automática ni siquiera agrega gastos generales a las aplicaciones en ejecución, se genera al iniciar). - * Si no usaras FastAPI y usaras Starlette directamente (u otra herramienta, como Sanic, Flask, Responder, etc.), tendrías que implementar toda la validación y serialización de datos tu mismo. Por lo tanto, tu aplicación final seguirá teniendo la misma sobrecarga que si se hubiera creado con FastAPI. Y en muchos casos, esta validación y serialización de datos constituye la mayor cantidad de código escrito en las aplicaciones. - * Entonces, al usar FastAPI estás ahorrando tiempo de desarrollo, errores, líneas de código y probablemente obtendrías el mismo rendimiento (o mejor) que obtendrías si no lo usaras (ya que tendrías que implementarlo todo en tu código). - * Si estás comparando FastAPI, compáralo con un framework de aplicaciones web (o conjunto de herramientas) que proporciona validación, serialización y documentación de datos, como Flask-apispec, NestJS, Molten, etc. Frameworks con validación, serialización y documentación automáticas integradas. + * De la misma forma en que Starlette usa Uvicorn y no puede ser más rápido que él, **FastAPI** usa Starlette, por lo que no puede ser más rápido que él. + * FastAPI ofrece más funcionalidades además de las de Starlette. Funcionalidades que casi siempre necesitas al construir APIs, como la validación y serialización de datos. Y al utilizarlo, obtienes documentación automática gratis (la documentación automática ni siquiera añade carga a las aplicaciones en ejecución, se genera al inicio). + * Si no usabas FastAPI y utilizabas Starlette directamente (u otra herramienta, como Sanic, Flask, Responder, etc.) tendrías que implementar toda la validación y serialización de datos por ti mismo. Entonces, tu aplicación final aún tendría la misma carga que si hubiera sido construida usando FastAPI. Y en muchos casos, esta validación y serialización de datos es la mayor cantidad de código escrito en las aplicaciones. + * Entonces, al usar FastAPI estás ahorrando tiempo de desarrollo, bugs, líneas de código, y probablemente obtendrías el mismo rendimiento (o mejor) que si no lo usaras (ya que tendrías que implementarlo todo en tu código). + * Si estás comparando FastAPI, compáralo con un framework de aplicación web (o conjunto de herramientas) que proporcione validación de datos, serialización y documentación, como Flask-apispec, NestJS, Molten, etc. Frameworks con validación de datos, serialización y documentación automáticas integradas. diff --git a/docs/es/docs/deployment/index.md b/docs/es/docs/deployment/index.md index 74b0e22f0..3b6dcc05d 100644 --- a/docs/es/docs/deployment/index.md +++ b/docs/es/docs/deployment/index.md @@ -1,21 +1,21 @@ -# Despliegue - Introducción +# Despliegue -Desplegar una aplicación hecha con **FastAPI** es relativamente fácil. +Desplegar una aplicación **FastAPI** es relativamente fácil. -## ¿Qué significa desplegar una aplicación? +## Qué Significa Despliegue -**Desplegar** una aplicación significa realizar una serie de pasos para hacerla **disponible para los usuarios**. +**Desplegar** una aplicación significa realizar los pasos necesarios para hacerla **disponible para los usuarios**. -Para una **API web**, normalmente implica ponerla en una **máquina remota**, con un **programa de servidor** que proporcione un buen rendimiento, estabilidad, etc, para que sus **usuarios** puedan **acceder** a la aplicación de manera eficiente y sin interrupciones o problemas. +Para una **API web**, normalmente implica ponerla en una **máquina remota**, con un **programa de servidor** que proporcione buen rendimiento, estabilidad, etc., para que tus **usuarios** puedan **acceder** a la aplicación de manera eficiente y sin interrupciones o problemas. -Esto difiere en las fases de **desarrollo**, donde estás constantemente cambiando el código, rompiéndolo y arreglándolo, deteniendo y reiniciando el servidor de desarrollo, etc. +Esto contrasta con las etapas de **desarrollo**, donde estás constantemente cambiando el código, rompiéndolo y arreglándolo, deteniendo y reiniciando el servidor de desarrollo, etc. -## Estrategias de despliegue +## Estrategias de Despliegue -Existen varias formas de hacerlo dependiendo de tu caso de uso específico y las herramientas que uses. +Hay varias maneras de hacerlo dependiendo de tu caso de uso específico y las herramientas que utilices. -Puedes **desplegar un servidor** tú mismo usando un conjunto de herramientas, puedes usar **servicios en la nube** que haga parte del trabajo por ti, o usar otras posibles opciones. +Podrías **desplegar un servidor** tú mismo utilizando una combinación de herramientas, podrías usar un **servicio en la nube** que hace parte del trabajo por ti, u otras opciones posibles. -Te enseñaré algunos de los conceptos principales que debes tener en cuenta al desplegar aplicaciones hechas con **FastAPI** (aunque la mayoría de estos conceptos aplican para cualquier otro tipo de aplicación web). +Te mostraré algunos de los conceptos principales que probablemente deberías tener en cuenta al desplegar una aplicación **FastAPI** (aunque la mayoría se aplica a cualquier otro tipo de aplicación web). -Podrás ver más detalles para tener en cuenta y algunas de las técnicas para hacerlo en las próximas secciones.✨ +Verás más detalles a tener en cuenta y algunas de las técnicas para hacerlo en las siguientes secciones. ✨ diff --git a/docs/es/docs/deployment/versions.md b/docs/es/docs/deployment/versions.md index 74243da89..d16ecf0a5 100644 --- a/docs/es/docs/deployment/versions.md +++ b/docs/es/docs/deployment/versions.md @@ -1,93 +1,93 @@ -# Acerca de las versiones de FastAPI +# Sobre las versiones de FastAPI -**FastAPI** está siendo utilizado en producción en muchas aplicaciones y sistemas. La cobertura de los tests se mantiene al 100%. Sin embargo, su desarrollo sigue siendo rápido. +**FastAPI** ya se está utilizando en producción en muchas aplicaciones y sistemas. Y la cobertura de tests se mantiene al 100%. Pero su desarrollo sigue avanzando rápidamente. -Se agregan nuevas características frecuentemente, se corrigen errores continuamente y el código está constantemente mejorando. +Se añaden nuevas funcionalidades con frecuencia, se corrigen bugs regularmente, y el código sigue mejorando continuamente. -Por eso las versiones actuales siguen siendo `0.x.x`, esto significa que cada versión puede potencialmente tener *breaking changes*. Las versiones siguen las convenciones de *Semantic Versioning*. +Por eso las versiones actuales siguen siendo `0.x.x`, esto refleja que cada versión podría tener potencialmente cambios incompatibles. Esto sigue las convenciones de Semantic Versioning. -Puedes crear aplicaciones listas para producción con **FastAPI** ahora mismo (y probablemente lo has estado haciendo por algún tiempo), solo tienes que asegurarte de usar la versión que funciona correctamente con el resto de tu código. +Puedes crear aplicaciones de producción con **FastAPI** ahora mismo (y probablemente ya lo has estado haciendo desde hace algún tiempo), solo debes asegurarte de que utilizas una versión que funciona correctamente con el resto de tu código. -## Fijar la versión de `fastapi` +## Fijar tu versión de `fastapi` -Lo primero que debes hacer en tu proyecto es "fijar" la última versión específica de **FastAPI** que sabes que funciona bien con tu aplicación. +Lo primero que debes hacer es "fijar" la versión de **FastAPI** que estás usando a la versión específica más reciente que sabes que funciona correctamente para tu aplicación. -Por ejemplo, digamos que estás usando la versión `0.45.0` en tu aplicación. +Por ejemplo, digamos que estás utilizando la versión `0.112.0` en tu aplicación. -Si usas el archivo `requirements.txt` puedes especificar la versión con: +Si usas un archivo `requirements.txt` podrías especificar la versión con: ```txt -fastapi==0.45.0 +fastapi[standard]==0.112.0 ``` -esto significa que usarás específicamente la versión `0.45.0`. +eso significaría que usarías exactamente la versión `0.112.0`. -También puedes fijar las versiones de esta forma: +O también podrías fijarla con: ```txt -fastapi>=0.45.0,<0.46.0 +fastapi[standard]>=0.112.0,<0.113.0 ``` -esto significa que usarás la versión `0.45.0` o superiores, pero menores a la versión `0.46.0`, por ejemplo, la versión `0.45.2` sería aceptada. +eso significaría que usarías las versiones `0.112.0` o superiores, pero menores que `0.113.0`, por ejemplo, una versión `0.112.2` todavía sería aceptada. -Si usas cualquier otra herramienta para manejar tus instalaciones, como Poetry, Pipenv, u otras, todas tienen una forma que puedes usar para definir versiones específicas para tus paquetes. +Si utilizas cualquier otra herramienta para gestionar tus instalaciones, como `uv`, Poetry, Pipenv, u otras, todas tienen una forma que puedes usar para definir versiones específicas para tus paquetes. ## Versiones disponibles -Puedes ver las versiones disponibles (por ejemplo, para revisar cuál es la actual) en las [Release Notes](../release-notes.md){.internal-link target=_blank}. +Puedes ver las versiones disponibles (por ejemplo, para revisar cuál es la más reciente) en las [Release Notes](../release-notes.md){.internal-link target=_blank}. -## Acerca de las versiones +## Sobre las versiones -Siguiendo las convenciones de *Semantic Versioning*, cualquier versión por debajo de `1.0.0` puede potencialmente tener *breaking changes*. +Siguiendo las convenciones del Semantic Versioning, cualquier versión por debajo de `1.0.0` podría potencialmente añadir cambios incompatibles. -FastAPI también sigue la convención de que cualquier cambio hecho en una "PATCH" version es para solucionar errores y *non-breaking changes*. +FastAPI también sigue la convención de que cualquier cambio de versión "PATCH" es para corrección de bugs y cambios no incompatibles. /// tip | Consejo -El "PATCH" es el último número, por ejemplo, en `0.2.3`, la PATCH version es `3`. +El "PATCH" es el último número, por ejemplo, en `0.2.3`, la versión PATCH es `3`. /// -Entonces, deberías fijar la versión así: +Así que deberías poder fijar a una versión como: ```txt fastapi>=0.45.0,<0.46.0 ``` -En versiones "MINOR" son añadidas nuevas características y posibles breaking changes. +Los cambios incompatibles y nuevas funcionalidades se añaden en versiones "MINOR". /// tip | Consejo -La versión "MINOR" es el número en el medio, por ejemplo, en `0.2.3`, la "MINOR" version es `2`. +El "MINOR" es el número en el medio, por ejemplo, en `0.2.3`, la versión MINOR es `2`. /// ## Actualizando las versiones de FastAPI -Para esto es recomendable primero añadir tests a tu aplicación. +Deberías añadir tests para tu aplicación. -Con **FastAPI** es muy fácil (gracias a Starlette), revisa la documentación [Testing](../tutorial/testing.md){.internal-link target=_blank} +Con **FastAPI** es muy fácil (gracias a Starlette), revisa la documentación: [Testing](../tutorial/testing.md){.internal-link target=_blank} -Luego de tener los tests, puedes actualizar la versión de **FastAPI** a una más reciente y asegurarte de que tu código funciona correctamente ejecutando los tests. +Después de tener tests, puedes actualizar la versión de **FastAPI** a una más reciente, y asegurarte de que todo tu código está funcionando correctamente ejecutando tus tests. -Si todo funciona correctamente, o haces los cambios necesarios para que esto suceda, y todos tus tests pasan, entonces puedes fijar tu versión de `fastapi` a la más reciente. +Si todo está funcionando, o después de hacer los cambios necesarios, y todos tus tests pasan, entonces puedes fijar tu `fastapi` a esa nueva versión más reciente. -## Acerca de Starlette +## Sobre Starlette No deberías fijar la versión de `starlette`. -Diferentes versiones de **FastAPI** pueden usar una versión específica de Starlette. +Diferentes versiones de **FastAPI** utilizarán una versión más reciente específica de Starlette. -Entonces, puedes dejar que **FastAPI** se asegure por sí mismo de qué versión de Starlette usar. +Así que, puedes simplemente dejar que **FastAPI** use la versión correcta de Starlette. -## Acerca de Pydantic +## Sobre Pydantic -Pydantic incluye los tests para **FastAPI** dentro de sus propios tests, esto significa que las versiones de Pydantic (superiores a `1.0.0`) son compatibles con FastAPI. +Pydantic incluye los tests para **FastAPI** con sus propios tests, así que nuevas versiones de Pydantic (por encima de `1.0.0`) siempre son compatibles con FastAPI. -Puedes fijar Pydantic a cualquier versión superior a `1.0.0` e inferior a `2.0.0` que funcione para ti. +Puedes fijar Pydantic a cualquier versión por encima de `1.0.0` que funcione para ti. Por ejemplo: ```txt -pydantic>=1.2.0,<2.0.0 +pydantic>=2.7.0,<3.0.0 ``` diff --git a/docs/es/docs/features.md b/docs/es/docs/features.md index b75918dff..472fdd736 100644 --- a/docs/es/docs/features.md +++ b/docs/es/docs/features.md @@ -1,43 +1,43 @@ -# Características +# Funcionalidades -## Características de FastAPI +## Funcionalidades de FastAPI -**FastAPI** te provee lo siguiente: +**FastAPI** te ofrece lo siguiente: ### Basado en estándares abiertos -* OpenAPI para la creación de APIs, incluyendo declaraciones de path operations, parámetros, body requests, seguridad, etc. -* Documentación automática del modelo de datos con JSON Schema (dado que OpenAPI mismo está basado en JSON Schema). -* Diseñado alrededor de estos estándares después de un estudio meticuloso. En vez de ser una capa añadida a último momento. -* Esto también permite la **generación automática de código de cliente** para muchos lenguajes. +* OpenAPI para la creación de APIs, incluyendo declaraciones de path operations, parámetros, request bodies, seguridad, etc. +* Documentación automática de modelos de datos con JSON Schema (ya que OpenAPI en sí mismo está basado en JSON Schema). +* Diseñado alrededor de estos estándares, tras un estudio meticuloso. En lugar de ser una capa adicional. +* Esto también permite el uso de **generación de código cliente automática** en muchos idiomas. ### Documentación automática -Documentación interactiva de la API e interfaces web de exploración. Hay múltiples opciones, dos incluidas por defecto, porque el framework está basado en OpenAPI. +Interfaces web de documentación y exploración de APIs interactivas. Como el framework está basado en OpenAPI, hay múltiples opciones, 2 incluidas por defecto. -* Swagger UI, con exploración interactiva, llama y prueba tu API directamente desde tu navegador. +* Swagger UI, con exploración interactiva, llama y prueba tu API directamente desde el navegador. -![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) +![Interacción Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) -* Documentación alternativa de la API con ReDoc. +* Documentación alternativa de API con ReDoc. ![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) -### Simplemente Python moderno +### Solo Python moderno -Todo está basado en las declaraciones de tipo de **Python 3.8** estándar (gracias a Pydantic). No necesitas aprender una sintaxis nueva, solo Python moderno. +Todo está basado en declaraciones estándar de **tipos en Python** (gracias a Pydantic). Sin nueva sintaxis que aprender. Solo Python moderno estándar. -Si necesitas un repaso de 2 minutos de cómo usar los tipos de Python (así no uses FastAPI) prueba el tutorial corto: [Python Types](python-types.md){.internal-link target=_blank}. +Si necesitas un repaso de 2 minutos sobre cómo usar tipos en Python (aunque no uses FastAPI), revisa el tutorial corto: [Tipos en Python](python-types.md){.internal-link target=_blank}. -Escribes Python estándar con tipos así: +Escribes Python estándar con tipos: ```Python from datetime import date from pydantic import BaseModel -# Declaras la variable como un str -# y obtienes soporte del editor dentro de la función +# Declara una variable como un str +# y obtiene soporte del editor dentro de la función def main(user_id: str): return user_id @@ -49,7 +49,7 @@ class User(BaseModel): joined: date ``` -Este puede ser usado como: +Que luego puede ser usado como: ```Python my_user: User = User(id=3, name="John Doe", joined="2018-07-19") @@ -67,135 +67,135 @@ my_second_user: User = User(**second_user_data) `**second_user_data` significa: -Pasa las keys y los valores del dict `second_user_data` directamente como argumentos de key-value, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")` +Pasa las claves y valores del dict `second_user_data` directamente como argumentos de clave-valor, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")` /// ### Soporte del editor -El framework fue diseñado en su totalidad para ser fácil e intuitivo de usar. Todas las decisiones fueron probadas en múltiples editores antes de comenzar el desarrollo para asegurar la mejor experiencia de desarrollo. +Todo el framework fue diseñado para ser fácil e intuitivo de usar, todas las decisiones fueron probadas en múltiples editores incluso antes de comenzar el desarrollo, para asegurar la mejor experiencia de desarrollo. -En la última encuesta a desarrolladores de Python fue claro que la característica más usada es el "auto-completado". +En las encuestas a desarrolladores de Python, es claro que una de las funcionalidades más usadas es el "autocompletado". -El framework **FastAPI** está creado para satisfacer eso. El auto-completado funciona en todas partes. +Todo el framework **FastAPI** está basado para satisfacer eso. El autocompletado funciona en todas partes. -No vas a tener que volver a la documentación seguido. +Rara vez necesitarás regresar a la documentación. -Así es como tu editor te puede ayudar: +Aquí está cómo tu editor podría ayudarte: * en Visual Studio Code: -![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) +![soporte del editor](https://fastapi.tiangolo.com/img/vscode-completion.png) * en PyCharm: -![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png) +![soporte del editor](https://fastapi.tiangolo.com/img/pycharm-completion.png) -Obtendrás completado para tu código que podrías haber considerado imposible antes. Por ejemplo, el key `price` dentro del JSON body (que podría haber estado anidado) que viene de un request. +Obtendrás autocompletado en código que podrías considerar imposible antes. Por ejemplo, la clave `price` dentro de un cuerpo JSON (que podría haber estado anidado) que proviene de un request. -Ya no pasará que escribas los nombres de key equivocados, o que tengas que revisar constantemente la documentación o desplazarte arriba y abajo para saber si usaste `username` o `user_name`. +No más escribir nombres de claves incorrectos, yendo de un lado a otro entre la documentación, o desplazándote hacia arriba y abajo para encontrar si finalmente usaste `username` o `user_name`. -### Corto +### Breve -Tiene **configuraciones por defecto** razonables para todo, con configuraciones opcionales en todas partes. Todos los parámetros pueden ser ajustados para tus necesidades y las de tu API. +Tiene **valores predeterminados** sensatos para todo, con configuraciones opcionales en todas partes. Todos los parámetros se pueden ajustar finamente para hacer lo que necesitas y para definir el API que necesitas. -Pero, todo **simplemente funciona** por defecto. +Pero por defecto, todo **"simplemente funciona"**. ### Validación -* Validación para la mayoría (¿o todos?) los **tipos de datos** de Python incluyendo: +* Validación para la mayoría (¿o todas?) de los **tipos de datos** de Python, incluyendo: * Objetos JSON (`dict`). - * JSON array (`list`) definiendo tipos de ítem. - * Campos de texto (`str`) definiendo longitudes mínimas y máximas. + * Array JSON (`list`) definiendo tipos de elementos. + * Campos de cadena de caracteres (`str`), definiendo longitudes mínimas y máximas. * Números (`int`, `float`) con valores mínimos y máximos, etc. -* Validación para tipos más exóticos como: +* Validación para tipos más exóticos, como: * URL. * Email. * UUID. * ...y otros. -Toda la validación es manejada por **Pydantic**, que es robusto y sólidamente establecido. +Toda la validación es manejada por **Pydantic**, una herramienta bien establecida y robusta. ### Seguridad y autenticación -La seguridad y la autenticación están integradas. Sin ningún compromiso con bases de datos ni modelos de datos. +Seguridad y autenticación integradas. Sin ningún compromiso con bases de datos o modelos de datos. -Todos los schemes de seguridad están definidos en OpenAPI incluyendo: +Todos los esquemas de seguridad definidos en OpenAPI, incluyendo: -* HTTP Basic. -* **OAuth2** (también con **JWT tokens**). Prueba el tutorial en [OAuth2 with JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. +* HTTP Básico. +* **OAuth2** (también con **tokens JWT**). Revisa el tutorial sobre [OAuth2 con JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. * API keys en: * Headers. - * Parámetros de Query. + * Parámetros de query. * Cookies, etc. -Más todas las características de seguridad de Starlette (incluyendo **session cookies**). +Además de todas las características de seguridad de Starlette (incluyendo **cookies de sesión**). -Todo ha sido construido como herramientas y componentes reutilizables que son fácilmente integrados con tus sistemas, almacenamiento de datos, bases de datos relacionales y no relacionales, etc. +Todo construido como herramientas y componentes reutilizables que son fáciles de integrar con tus sistemas, almacenes de datos, bases de datos relacionales y NoSQL, etc. -### Dependency Injection +### Inyección de dependencias -FastAPI incluye un sistema de Dependency Injection extremadamente poderoso y fácil de usar. +FastAPI incluye un sistema de Inyección de Dependencias extremadamente fácil de usar, pero extremadamente potente. -* Inclusive las dependencias pueden tener dependencias creando una jerarquía o un **"grafo" de dependencias**. -* Todas son **manejadas automáticamente** por el framework. -* Todas las dependencias pueden requerir datos de los requests y aumentar las restricciones del *path operation* y la documentación automática. -* **Validación automática** inclusive para parámetros del *path operation* definidos en las dependencias. -* Soporte para sistemas complejos de autenticación de usuarios, **conexiones con bases de datos**, etc. -* **Sin comprometerse** con bases de datos, frontend, etc. Pero permitiendo integración fácil con todos ellos. +* Incluso las dependencias pueden tener dependencias, creando una jerarquía o **"gráfico de dependencias"**. +* Todo **manejado automáticamente** por el framework. +* Todas las dependencias pueden requerir datos de los requests y **aumentar las restricciones de la path operation** y la documentación automática. +* **Validación automática** incluso para los parámetros de *path operation* definidos en las dependencias. +* Soporte para sistemas de autenticación de usuario complejos, **conexiones a bases de datos**, etc. +* **Sin compromisos** con bases de datos, frontends, etc. Pero fácil integración con todos ellos. ### "Plug-ins" ilimitados -O dicho de otra manera, no hay necesidad para "plug-ins". Importa y usa el código que necesites. +O de otra manera, no hay necesidad de ellos, importa y usa el código que necesitas. -Cualquier integración está diseñada para que sea tan sencilla de usar (con dependencias) que puedas crear un "plug-in" para tu aplicación en dos líneas de código usando la misma estructura y sintaxis que usaste para tus *path operations*. +Cualquier integración está diseñada para ser tan simple de usar (con dependencias) que puedes crear un "plug-in" para tu aplicación en 2 líneas de código usando la misma estructura y sintaxis utilizada para tus *path operations*. ### Probado -* Cobertura de pruebas al 100%. -* Base de código 100% anotada con tipos. +* 100% de cobertura de tests. +* Código completamente anotado con tipos. * Usado en aplicaciones en producción. -## Características de Starlette +## Funcionalidades de Starlette -**FastAPI** está basado y es completamente compatible con Starlette. Tanto así, que cualquier código de Starlette que tengas también funcionará. +**FastAPI** es totalmente compatible con (y está basado en) Starlette. Así que, cualquier código adicional de Starlette que tengas, también funcionará. -`FastAPI` es realmente una sub-clase de `Starlette`. Así que, si ya conoces o usas Starlette, muchas de las características funcionarán de la misma manera. +`FastAPI` es en realidad una subclase de `Starlette`. Así que, si ya conoces o usas Starlette, la mayoría de las funcionalidades funcionarán de la misma manera. -Con **FastAPI** obtienes todas las características de **Starlette** (porque FastAPI es simplemente Starlette en esteroides): +Con **FastAPI** obtienes todas las funcionalidades de **Starlette** (ya que FastAPI es simplemente Starlette potenciado): -* Desempeño realmente impresionante. Es uno de los frameworks de Python más rápidos, a la par con **NodeJS** y **Go**. +* Rendimiento seriamente impresionante. Es uno de los frameworks de Python más rápidos disponibles, a la par de **NodeJS** y **Go**. * Soporte para **WebSocket**. -* Tareas en background. -* Eventos de startup y shutdown. -* Cliente de pruebas construido con HTTPX. -* **CORS**, GZip, Static Files, Streaming responses. -* Soporte para **Session and Cookie**. -* Cobertura de pruebas al 100%. -* Base de código 100% anotada con tipos. +* Tareas en segundo plano en el mismo proceso. +* Eventos de inicio y apagado. +* Cliente de prueba basado en HTTPX. +* **CORS**, GZip, archivos estáticos, responses en streaming. +* Soporte para **Session y Cookie**. +* Cobertura de tests del 100%. +* Código completamente anotado con tipos. -## Características de Pydantic +## Funcionalidades de Pydantic -**FastAPI** está basado y es completamente compatible con Pydantic. Tanto así, que cualquier código de Pydantic que tengas también funcionará. +**FastAPI** es totalmente compatible con (y está basado en) Pydantic. Por lo tanto, cualquier código adicional de Pydantic que tengas, también funcionará. -Esto incluye a librerías externas basadas en Pydantic como ORMs y ODMs para bases de datos. +Incluyendo paquetes externos también basados en Pydantic, como ORMs, ODMs para bases de datos. -Esto también significa que en muchos casos puedes pasar el mismo objeto que obtuviste de un request **directamente a la base de datos**, dado que todo es validado automáticamente. +Esto también significa que, en muchos casos, puedes pasar el mismo objeto que obtienes de un request **directamente a la base de datos**, ya que todo se valida automáticamente. -Lo mismo aplica para el sentido contrario. En muchos casos puedes pasar el objeto que obtienes de la base de datos **directamente al cliente**. +Lo mismo aplica al revés, en muchos casos puedes simplemente pasar el objeto que obtienes de la base de datos **directamente al cliente**. -Con **FastAPI** obtienes todas las características de **Pydantic** (dado que FastAPI está basado en Pydantic para todo el manejo de datos): +Con **FastAPI** obtienes todas las funcionalidades de **Pydantic** (ya que FastAPI está basado en Pydantic para todo el manejo de datos): -* **Sin dificultades para entender**: - * No necesitas aprender un nuevo micro-lenguaje de definición de schemas. - * Si sabes tipos de Python, sabes cómo usar Pydantic. -* Interactúa bien con tu **IDE/linter/cerebro**: - * Porque las estructuras de datos de Pydantic son solo instances de clases que tu defines, el auto-completado, el linting, mypy y tu intuición deberían funcionar bien con tus datos validados. +* **Sin complicaciones**: + * Sin micro-lenguaje de definición de esquemas nuevo que aprender. + * Si conoces los tipos en Python sabes cómo usar Pydantic. +* Se lleva bien con tu **IDE/linter/cerebro**: + * Porque las estructuras de datos de pydantic son solo instances de clases que defines; autocompletado, linting, mypy y tu intuición deberían funcionar correctamente con tus datos validados. * Valida **estructuras complejas**: - * Usa modelos jerárquicos de modelos de Pydantic, `typing` de Python, `List` y `Dict`, etc. - * Los validadores también permiten que se definan fácil y claramente schemas complejos de datos. Estos son chequeados y documentados como JSON Schema. - * Puedes tener objetos de **JSON profundamente anidados** y que todos sean validados y anotados. + * Uso de modelos jerárquicos de Pydantic, `List` y `Dict` de `typing` de Python, etc. + * Y los validadores permiten definir, verificar y documentar de manera clara y fácil esquemas de datos complejos como JSON Schema. + * Puedes tener objetos JSON profundamente **anidados** y validarlos todos y anotarlos. * **Extensible**: - * Pydantic permite que se definan tipos de datos a la medida o puedes extender la validación con métodos en un modelo decorado con el decorador de validación. -* Cobertura de pruebas al 100%. + * Pydantic permite definir tipos de datos personalizados o puedes extender la validación con métodos en un modelo decorados con el decorador validator. +* Cobertura de tests del 100%. diff --git a/docs/es/docs/how-to/graphql.md b/docs/es/docs/how-to/graphql.md index 2c0e80d77..52f163809 100644 --- a/docs/es/docs/how-to/graphql.md +++ b/docs/es/docs/how-to/graphql.md @@ -1,60 +1,60 @@ # GraphQL -Como **FastAPI** está basado en el estándar **ASGI**, es muy fácil integrar cualquier library **GraphQL** que sea compatible con ASGI. +Como **FastAPI** se basa en el estándar **ASGI**, es muy fácil integrar cualquier paquete de **GraphQL** que también sea compatible con ASGI. -Puedes combinar *operaciones de path* regulares de la library de FastAPI con GraphQL en la misma aplicación. +Puedes combinar las *path operations* normales de FastAPI con GraphQL en la misma aplicación. /// tip | Consejo -**GraphQL** resuelve algunos casos de uso específicos. +**GraphQL** resuelve algunos casos de uso muy específicos. -Tiene **ventajas** y **desventajas** cuando lo comparas con **APIs web** comunes. +Tiene **ventajas** y **desventajas** en comparación con las **APIs web** comunes. -Asegúrate de evaluar si los **beneficios** para tu caso de uso compensan las **desventajas.** 🤓 +Asegúrate de evaluar si los **beneficios** para tu caso de uso compensan los **inconvenientes**. 🤓 /// -## Librerías GraphQL +## Paquetes de GraphQL -Aquí hay algunas de las libraries de **GraphQL** que tienen soporte con **ASGI** las cuales podrías usar con **FastAPI**: +Aquí algunos de los paquetes de **GraphQL** que tienen soporte **ASGI**. Podrías usarlos con **FastAPI**: * Strawberry 🍓 * Con documentación para FastAPI * Ariadne * Con documentación para FastAPI * Tartiflette - * Con Tartiflette ASGI para proveer integración con ASGI + * Con Tartiflette ASGI para proporcionar integración con ASGI * Graphene * Con starlette-graphene3 ## GraphQL con Strawberry -Si necesitas o quieres trabajar con **GraphQL**, **Strawberry** es la library **recomendada** por el diseño más cercano a **FastAPI**, el cual es completamente basado en **anotaciones de tipo**. +Si necesitas o quieres trabajar con **GraphQL**, **Strawberry** es el paquete **recomendado** ya que tiene un diseño muy similar al diseño de **FastAPI**, todo basado en **anotaciones de tipos**. -Dependiendo de tus casos de uso, podrías preferir usar una library diferente, pero si me preguntas, probablemente te recomendaría **Strawberry**. +Dependiendo de tu caso de uso, podrías preferir usar un paquete diferente, pero si me preguntas, probablemente te sugeriría probar **Strawberry**. -Aquí hay una pequeña muestra de cómo podrías integrar Strawberry con FastAPI: +Aquí tienes una pequeña vista previa de cómo podrías integrar Strawberry con FastAPI: {* ../../docs_src/graphql/tutorial001.py hl[3,22,25:26] *} Puedes aprender más sobre Strawberry en la documentación de Strawberry. -Y también en la documentación sobre Strawberry con FastAPI. +Y también la documentación sobre Strawberry con FastAPI. -## Clase obsoleta `GraphQLApp` en Starlette +## `GraphQLApp` viejo de Starlette -Versiones anteriores de Starlette incluyen la clase `GraphQLApp` para integrarlo con Graphene. +Las versiones anteriores de Starlette incluían una clase `GraphQLApp` para integrar con Graphene. -Esto fue marcado como obsoleto en Starlette, pero si aún tienes código que lo usa, puedes fácilmente **migrar** a starlette-graphene3, la cual cubre el mismo caso de uso y tiene una **interfaz casi idéntica.** +Fue deprecada de Starlette, pero si tienes código que lo usaba, puedes fácilmente **migrar** a starlette-graphene3, que cubre el mismo caso de uso y tiene una **interfaz casi idéntica**. /// tip | Consejo -Si necesitas GraphQL, te recomendaría revisar Strawberry, que es basada en anotaciones de tipo en vez de clases y tipos personalizados. +Si necesitas GraphQL, aún te recomendaría revisar Strawberry, ya que se basa en anotaciones de tipos en lugar de clases y tipos personalizados. /// -## Aprende más +## Aprende Más -Puedes aprender más acerca de **GraphQL** en la documentación oficial de GraphQL. +Puedes aprender más sobre **GraphQL** en la documentación oficial de GraphQL. -También puedes leer más acerca de cada library descrita anteriormente en sus enlaces. +También puedes leer más sobre cada uno de esos paquetes descritos arriba en sus enlaces. diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md index 73d9b679e..db8da6933 100644 --- a/docs/es/docs/index.md +++ b/docs/es/docs/index.md @@ -8,18 +8,21 @@ FastAPI

- FastAPI framework, alto desempeño, fácil de aprender, rápido de programar, listo para producción + FastAPI framework, alto rendimiento, fácil de aprender, rápido de programar, listo para producción

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

--- @@ -29,21 +32,21 @@ **Código Fuente**: https://github.com/fastapi/fastapi --- -FastAPI es un web framework moderno y rápido (de alto rendimiento) para construir APIs con Python basado en las anotaciones de tipos estándar de Python. -Sus características principales son: +FastAPI es un framework web moderno, rápido (de alto rendimiento), para construir APIs con Python basado en las anotaciones de tipos estándar de Python. -* **Rapidez**: Alto rendimiento, a la par con **NodeJS** y **Go** (gracias a Starlette y Pydantic). [Uno de los frameworks de Python más rápidos](#rendimiento). +Las características clave son: -* **Rápido de programar**: Incrementa la velocidad de desarrollo entre 200% y 300%. * -* **Menos errores**: Reduce los errores humanos (de programador) aproximadamente un 40%. * -* **Intuitivo**: Gran soporte en los editores con auto completado en todas partes. Gasta menos tiempo debugging. -* **Fácil**: Está diseñado para ser fácil de usar y aprender. Gastando menos tiempo leyendo documentación. -* **Corto**: Minimiza la duplicación de código. Múltiples funcionalidades con cada declaración de parámetros. Menos errores. -* **Robusto**: Crea código listo para producción con documentación automática interactiva. -* **Basado en estándares**: Basado y totalmente compatible con los estándares abiertos para APIs: OpenAPI (conocido previamente como Swagger) y JSON Schema. +* **Rápido**: Muy alto rendimiento, a la par con **NodeJS** y **Go** (gracias a Starlette y Pydantic). [Uno de los frameworks Python más rápidos disponibles](#performance). +* **Rápido de programar**: Aumenta la velocidad para desarrollar funcionalidades en aproximadamente un 200% a 300%. * +* **Menos bugs**: Reduce en aproximadamente un 40% los errores inducidos por humanos (desarrolladores). * +* **Intuitivo**: Gran soporte para editores. Autocompletado en todas partes. Menos tiempo depurando. +* **Fácil**: Diseñado para ser fácil de usar y aprender. Menos tiempo leyendo documentación. +* **Corto**: Minimiza la duplicación de código. Múltiples funcionalidades desde cada declaración de parámetro. Menos bugs. +* **Robusto**: Obtén código listo para producción. Con documentación interactiva automática. +* **Basado en estándares**: Basado (y completamente compatible) con los estándares abiertos para APIs: OpenAPI (anteriormente conocido como Swagger) y JSON Schema. -* Esta estimación está basada en pruebas con un equipo de desarrollo interno construyendo aplicaciones listas para producción. +* estimación basada en pruebas con un equipo de desarrollo interno, construyendo aplicaciones de producción. ## Sponsors @@ -64,41 +67,47 @@ Sus características principales son: ## Opiniones -"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" +"_[...] Estoy usando **FastAPI** un montón estos días. [...] De hecho, estoy planeando usarlo para todos los servicios de **ML de mi equipo en Microsoft**. Algunos de ellos se están integrando en el núcleo del producto **Windows** y algunos productos de **Office**._"
Kabir Khan - Microsoft (ref)
--- -"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_" +"_Adoptamos el paquete **FastAPI** para crear un servidor **REST** que pueda ser consultado para obtener **predicciones**. [para Ludwig]_" -
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
+
Piero Molino, Yaroslav Dudin, y Sai Sumanth Miryala - Uber (ref)
--- -"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_" +"_**Netflix** se complace en anunciar el lanzamiento de código abierto de nuestro framework de orquestación de **gestión de crisis**: **Dispatch**! [construido con **FastAPI**]_"
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
--- -"_I’m over the moon excited about **FastAPI**. It’s so fun!_" +"_Estoy súper emocionado con **FastAPI**. ¡Es tan divertido!_" -
Brian Okken - Python Bytes podcast host (ref)
+ --- -"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" +"_Honestamente, lo que has construido parece súper sólido y pulido. En muchos aspectos, es lo que quería que **Hug** fuera; es realmente inspirador ver a alguien construir eso._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - creador de Hug (ref)
--- -"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_" +"_Si estás buscando aprender un **framework moderno** para construir APIs REST, échale un vistazo a **FastAPI** [...] Es rápido, fácil de usar y fácil de aprender [...]_" + +"_Nos hemos cambiado a **FastAPI** para nuestras **APIs** [...] Creo que te gustará [...]_" + +
Ines Montani - Matthew Honnibal - fundadores de Explosion AI - creadores de spaCy (ref) - (ref)
+ +--- -"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_" +"_Si alguien está buscando construir una API de Python para producción, altamente recomendaría **FastAPI**. Está **hermosamente diseñado**, es **simple de usar** y **altamente escalable**, se ha convertido en un **componente clave** en nuestra estrategia de desarrollo API primero y está impulsando muchas automatizaciones y servicios como nuestro Ingeniero Virtual TAC._" -
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+
Deon Pillsbury - Cisco (ref)
--- @@ -106,41 +115,33 @@ Sus características principales son: -Si estás construyendo un app de CLI para ser usada en la terminal en vez de una API web, fíjate en **Typer**. +Si estás construyendo una aplicación de CLI para ser usada en el terminal en lugar de una API web, revisa **Typer**. -**Typer** es el hermano menor de FastAPI. La intención es que sea el **FastAPI de las CLIs**. ⌨️ 🚀 +**Typer** es el hermano pequeño de FastAPI. Y está destinado a ser el **FastAPI de las CLIs**. ⌨️ 🚀 ## Requisitos -FastAPI está sobre los hombros de gigantes: +FastAPI se apoya en hombros de gigantes: * Starlette para las partes web. * Pydantic para las partes de datos. ## Instalación -
- -```console -$ pip install fastapi - ----> 100% -``` - -
- -También vas a necesitar un servidor ASGI para producción cómo Uvicorn o Hypercorn. +Crea y activa un entorno virtual y luego instala FastAPI:
```console -$ pip install "uvicorn[standard]" +$ pip install "fastapi[standard]" ---> 100% ```
+**Nota**: Asegúrate de poner `"fastapi[standard]"` entre comillas para asegurar que funcione en todas las terminales. + ## Ejemplo ### Créalo @@ -148,9 +149,10 @@ $ pip install "uvicorn[standard]" * Crea un archivo `main.py` con: ```Python -from fastapi import FastAPI from typing import Union +from fastapi import FastAPI + app = FastAPI() @@ -169,10 +171,11 @@ def read_item(item_id: int, q: Union[str, None] = None): Si tu código usa `async` / `await`, usa `async def`: -```Python hl_lines="7 12" -from fastapi import FastAPI +```Python hl_lines="9 14" from typing import Union +from fastapi import FastAPI + app = FastAPI() @@ -188,7 +191,7 @@ async def read_item(item_id: int, q: Union[str, None] = None): **Nota**: -Si no lo sabes, revisa la sección _"¿Con prisa?"_ sobre `async` y `await` en la documentación. +Si no lo sabes, revisa la sección _"¿Con prisa?"_ sobre `async` y `await` en la documentación. @@ -199,11 +202,24 @@ Corre el servidor con:
```console -$ uvicorn main:app --reload - +$ fastapi dev main.py + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + │ fastapi run │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] +INFO: Started reloader process [2248755] using WatchFiles +INFO: Started server process [2248757] INFO: Waiting for application startup. INFO: Application startup complete. ``` @@ -211,13 +227,13 @@ INFO: Application startup complete.
-Sobre el comando uvicorn main:app --reload... +Acerca del comando fastapi dev main.py... + +El comando `fastapi dev` lee tu archivo `main.py`, detecta la app **FastAPI** en él y arranca un servidor usando Uvicorn. -El comando `uvicorn main:app` se refiere a: +Por defecto, `fastapi dev` comenzará con auto-recarga habilitada para el desarrollo local. -* `main`: el archivo `main.py` (el"modulo" de Python). -* `app`: el objeto creado dentro de `main.py` con la línea `app = FastAPI()`. -* `--reload`: hace que el servidor se reinicie después de cambios en el código. Esta opción solo debe ser usada en desarrollo. +Puedes leer más sobre esto en la documentación del CLI de FastAPI.
@@ -225,7 +241,7 @@ El comando `uvicorn main:app` se refiere a: Abre tu navegador en http://127.0.0.1:8000/items/5?q=somequery. -Verás la respuesta de JSON cómo: +Verás el response JSON como: ```JSON {"item_id": 5, "q": "somequery"} @@ -233,37 +249,38 @@ Verás la respuesta de JSON cómo: Ya creaste una API que: -* Recibe HTTP requests en los _paths_ `/` y `/items/{item_id}`. -* Ambos _paths_ toman operaciones `GET` (también conocido como HTTP _methods_). -* El _path_ `/items/{item_id}` tiene un _path parameter_ `item_id` que debería ser un `int`. -* El _path_ `/items/{item_id}` tiene un `str` _query parameter_ `q` opcional. +* Recibe requests HTTP en los _paths_ `/` y `/items/{item_id}`. +* Ambos _paths_ toman _operaciones_ `GET` (también conocidas como métodos HTTP). +* El _path_ `/items/{item_id}` tiene un _parámetro de path_ `item_id` que debe ser un `int`. +* El _path_ `/items/{item_id}` tiene un _parámetro de query_ `q` opcional que es un `str`. -### Documentación interactiva de APIs +### Documentación interactiva de la API Ahora ve a http://127.0.0.1:8000/docs. -Verás la documentación automática e interactiva de la API (proveída por Swagger UI): +Verás la documentación interactiva automática de la API (proporcionada por Swagger UI): ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) -### Documentación alternativa de la API +### Documentación de API Alternativa -Ahora, ve a http://127.0.0.1:8000/redoc. +Y ahora, ve a http://127.0.0.1:8000/redoc. -Ahora verás la documentación automática alternativa (proveída por ReDoc): +Verás la documentación alternativa automática (proporcionada por ReDoc): ![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) -## Mejora al ejemplo +## Actualización del Ejemplo -Ahora modifica el archivo `main.py` para recibir un body del `PUT` request. +Ahora modifica el archivo `main.py` para recibir un body desde un request `PUT`. -Declara el body usando las declaraciones de tipo estándares de Python gracias a Pydantic. +Declara el body usando tipos estándar de Python, gracias a Pydantic. + +```Python hl_lines="4 9-12 25-27" +from typing import Union -```Python hl_lines="2 7-10 23-25" from fastapi import FastAPI from pydantic import BaseModel -from typing import Union app = FastAPI() @@ -289,9 +306,9 @@ def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id} ``` -El servidor debería recargar automáticamente (porque añadiste `--reload` al comando `uvicorn` que está más arriba). +El servidor `fastapi dev` debería recargarse automáticamente. -### Mejora a la documentación interactiva de APIs +### Actualización de la Documentación Interactiva de la API Ahora ve a http://127.0.0.1:8000/docs. @@ -299,29 +316,29 @@ Ahora ve a http://127.0.0.1:8000/redoc. +Y ahora, ve a http://127.0.0.1:8000/redoc. -* La documentación alternativa también reflejará el nuevo parámetro de query y el body: +* La documentación alternativa también reflejará el nuevo parámetro de query y body: ![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) ### Resumen -En resumen, declaras los tipos de parámetros, body, etc. **una vez** como parámetros de la función. +En resumen, declaras **una vez** los tipos de parámetros, body, etc. como parámetros de función. -Lo haces con tipos modernos estándar de Python. +Lo haces con tipos estándar modernos de Python. -No tienes que aprender una sintaxis nueva, los métodos o clases de una library específica, etc. +No tienes que aprender una nueva sintaxis, los métodos o clases de un paquete específico, etc. Solo **Python** estándar. @@ -331,7 +348,7 @@ Por ejemplo, para un `int`: item_id: int ``` -o para un modelo más complejo de `Item`: +o para un modelo `Item` más complejo: ```Python item: Item @@ -339,62 +356,62 @@ item: Item ...y con esa única declaración obtienes: -* Soporte del editor incluyendo: - * Auto completado. - * Anotaciones de tipos. +* Soporte para editores, incluyendo: + * Autocompletado. + * Chequeo de tipos. * Validación de datos: - * Errores automáticos y claros cuándo los datos son inválidos. - * Validación, incluso para objetos JSON profundamente anidados. -* Conversión de datos de input: viniendo de la red a datos y tipos de Python. Leyendo desde: + * Errores automáticos y claros cuando los datos son inválidos. + * Validación incluso para objetos JSON profundamente anidados. +* Conversión de datos de entrada: de la red a los datos y tipos de Python. Leyendo desde: * JSON. - * Path parameters. - * Query parameters. + * Parámetros de path. + * Parámetros de query. * Cookies. * Headers. - * Formularios. + * Forms. * Archivos. -* Conversión de datos de output: convirtiendo de datos y tipos de Python a datos para la red (como JSON): +* Conversión de datos de salida: convirtiendo de datos y tipos de Python a datos de red (como JSON): * Convertir tipos de Python (`str`, `int`, `float`, `bool`, `list`, etc). * Objetos `datetime`. * Objetos `UUID`. - * Modelos de bases de datos. + * Modelos de base de datos. * ...y muchos más. -* Documentación automática e interactiva incluyendo 2 interfaces de usuario alternativas: +* Documentación interactiva automática de la API, incluyendo 2 interfaces de usuario alternativas: * Swagger UI. * ReDoc. --- -Volviendo al ejemplo de código anterior, **FastAPI** va a: - -* Validar que existe un `item_id` en el path para requests usando `GET` y `PUT`. -* Validar que el `item_id` es del tipo `int` para requests de tipo `GET` y `PUT`. - * Si no lo es, el cliente verá un mensaje de error útil y claro. -* Revisar si existe un query parameter opcional llamado `q` (cómo en `http://127.0.0.1:8000/items/foo?q=somequery`) para requests de tipo `GET`. - * Como el parámetro `q` fue declarado con `= None` es opcional. - * Sin el `None` sería obligatorio (cómo lo es el body en el caso con `PUT`). -* Para requests de tipo `PUT` a `/items/{item_id}` leer el body como JSON: - * Revisar si tiene un atributo requerido `name` que debe ser un `str`. - * Revisar si tiene un atributo requerido `price` que debe ser un `float`. - * Revisar si tiene un atributo opcional `is_offer`, que debe ser un `bool`si está presente. - * Todo esto funcionaría para objetos JSON profundamente anidados. -* Convertir de y a JSON automáticamente. -* Documentar todo con OpenAPI que puede ser usado por: +Volviendo al ejemplo de código anterior, **FastAPI**: + +* Validará que haya un `item_id` en el path para requests `GET` y `PUT`. +* Validará que el `item_id` sea del tipo `int` para requests `GET` y `PUT`. + * Si no lo es, el cliente verá un error útil y claro. +* Comprobará si hay un parámetro de query opcional llamado `q` (como en `http://127.0.0.1:8000/items/foo?q=somequery`) para requests `GET`. + * Como el parámetro `q` está declarado con `= None`, es opcional. + * Sin el `None` sería requerido (como lo es el body en el caso con `PUT`). +* Para requests `PUT` a `/items/{item_id}`, leerá el body como JSON: + * Comprobará que tiene un atributo requerido `name` que debe ser un `str`. + * Comprobará que tiene un atributo requerido `price` que debe ser un `float`. + * Comprobará que tiene un atributo opcional `is_offer`, que debe ser un `bool`, si está presente. + * Todo esto también funcionaría para objetos JSON profundamente anidados. +* Convertirá de y a JSON automáticamente. +* Documentará todo con OpenAPI, que puede ser usado por: * Sistemas de documentación interactiva. - * Sistemas de generación automática de código de cliente para muchos lenguajes. -* Proveer directamente 2 interfaces de documentación web interactivas. + * Sistemas de generación automática de código cliente, para muchos lenguajes. +* Proporcionará 2 interfaces web de documentación interactiva directamente. --- -Hasta ahora, escasamente vimos lo básico pero ya tienes una idea de cómo funciona. +Solo tocamos los conceptos básicos, pero ya te haces una idea de cómo funciona todo. -Intenta cambiando la línea a: +Intenta cambiar la línea con: ```Python return {"item_name": item.name, "item_id": item_id} ``` -...de: +...desde: ```Python ... "item_name": item.name ... @@ -406,56 +423,74 @@ Intenta cambiando la línea a: ... "item_price": item.price ... ``` -... y mira como el editor va a auto-completar los atributos y sabrá sus tipos: +...y observa cómo tu editor autocompleta los atributos y conoce sus tipos: -![soporte de editor](https://fastapi.tiangolo.com/img/vscode-completion.png) +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) -Para un ejemplo más completo que incluye más características ve el Tutorial - Guía de Usuario. +Para un ejemplo más completo incluyendo más funcionalidades, ve al Tutorial - Guía del Usuario. -**Spoiler alert**: el Tutorial - Guía de Usuario incluye: +**Alerta de spoilers**: el tutorial - guía del usuario incluye: -* Declaración de **parámetros** en otros lugares diferentes cómo los: **headers**, **cookies**, **formularios** y **archivos**. -* Cómo agregar **requisitos de validación** cómo `maximum_length` o `regex`. -* Un sistema de **Dependency Injection** poderoso y fácil de usar. -* Seguridad y autenticación incluyendo soporte para **OAuth2** con **JWT tokens** y **HTTP Basic** auth. -* Técnicas más avanzadas, pero igual de fáciles, para declarar **modelos de JSON profundamente anidados** (gracias a Pydantic). -* Muchas características extra (gracias a Starlette) como: +* Declaración de **parámetros** desde otros lugares diferentes como: **headers**, **cookies**, **campos de formulario** y **archivos**. +* Cómo establecer **restricciones de validación** como `maximum_length` o `regex`. +* Un sistema de **Inyección de Dependencias** muy poderoso y fácil de usar. +* Seguridad y autenticación, incluyendo soporte para **OAuth2** con **tokens JWT** y autenticación **HTTP Basic**. +* Técnicas más avanzadas (pero igualmente fáciles) para declarar **modelos JSON profundamente anidados** (gracias a Pydantic). +* Integración con **GraphQL** usando Strawberry y otros paquetes. +* Muchas funcionalidades extra (gracias a Starlette) como: * **WebSockets** - * **GraphQL** - * pruebas extremadamente fáciles con HTTPX y `pytest` + * pruebas extremadamente fáciles basadas en HTTPX y `pytest` * **CORS** - * **Cookie Sessions** - * ...y mucho más. + * **Sesiones de Cookies** + * ...y más. ## Rendimiento -Benchmarks independientes de TechEmpower muestran que aplicaciones de **FastAPI** corriendo con Uvicorn cómo uno de los frameworks de Python más rápidos, únicamente debajo de Starlette y Uvicorn (usados internamente por FastAPI). (*) +Benchmarks independientes de TechEmpower muestran aplicaciones **FastAPI** ejecutándose bajo Uvicorn como uno de los frameworks Python más rápidos disponibles, solo por debajo de Starlette y Uvicorn (usados internamente por FastAPI). (*) + +Para entender más sobre esto, ve la sección Benchmarks. -Para entender más al respecto revisa la sección Benchmarks. +## Dependencias -## Dependencias Opcionales +FastAPI depende de Pydantic y Starlette. + +### Dependencias `standard` + +Cuando instalas FastAPI con `pip install "fastapi[standard]"` viene con el grupo `standard` de dependencias opcionales: Usadas por Pydantic: -* email-validator - para validación de emails. +* email-validator - para validación de correos electrónicos. + +Usadas por Starlette: + +* httpx - Requerido si deseas usar el `TestClient`. +* jinja2 - Requerido si deseas usar la configuración de plantilla predeterminada. +* python-multipart - Requerido si deseas soportar "parsing" de forms, con `request.form()`. + +Usadas por FastAPI / Starlette: + +* uvicorn - para el servidor que carga y sirve tu aplicación. Esto incluye `uvicorn[standard]`, que incluye algunas dependencias (por ejemplo, `uvloop`) necesarias para servir con alto rendimiento. +* `fastapi-cli` - para proporcionar el comando `fastapi`. + +### Sin Dependencias `standard` + +Si no deseas incluir las dependencias opcionales `standard`, puedes instalar con `pip install fastapi` en lugar de `pip install "fastapi[standard]"`. + +### Dependencias Opcionales Adicionales -Usados por Starlette: +Existen algunas dependencias adicionales que podrías querer instalar. -* httpx - Requerido si quieres usar el `TestClient`. -* jinja2 - Requerido si quieres usar la configuración por defecto de templates. -* python-multipart - Requerido si quieres dar soporte a "parsing" de formularios, con `request.form()`. -* itsdangerous - Requerido para dar soporte a `SessionMiddleware`. -* pyyaml - Requerido para dar soporte al `SchemaGenerator` de Starlette (probablemente no lo necesites con FastAPI). -* graphene - Requerido para dar soporte a `GraphQLApp`. +Dependencias opcionales adicionales de Pydantic: -Usado por FastAPI / Starlette: +* pydantic-settings - para la gestión de configuraciones. +* pydantic-extra-types - para tipos extra para ser usados con Pydantic. -* uvicorn - para el servidor que carga y sirve tu aplicación. -* orjson - Requerido si quieres usar `ORJSONResponse`. -* ujson - Requerido si quieres usar `UJSONResponse`. +Dependencias opcionales adicionales de FastAPI: -Puedes instalarlos con `pip install fastapi[all]`. +* orjson - Requerido si deseas usar `ORJSONResponse`. +* ujson - Requerido si deseas usar `UJSONResponse`. ## Licencia -Este proyecto está licenciado bajo los términos de la licencia del MIT. +Este proyecto tiene licencia bajo los términos de la licencia MIT. diff --git a/docs/es/docs/learn/index.md b/docs/es/docs/learn/index.md index b8d26cf34..cc6c7cc3f 100644 --- a/docs/es/docs/learn/index.md +++ b/docs/es/docs/learn/index.md @@ -1,5 +1,5 @@ -# Aprender +# Aprende Aquí están las secciones introductorias y los tutoriales para aprender **FastAPI**. -Podrías considerar esto como un **libro**, un **curso**, la forma **oficial** y recomendada de aprender FastAPI. 😎 +Podrías considerar esto un **libro**, un **curso**, la forma **oficial** y recomendada de aprender FastAPI. 😎 diff --git a/docs/es/docs/project-generation.md b/docs/es/docs/project-generation.md index 6aa570397..559995151 100644 --- a/docs/es/docs/project-generation.md +++ b/docs/es/docs/project-generation.md @@ -1,28 +1,28 @@ -# Plantilla de FastAPI Full Stack +# Plantilla Full Stack FastAPI -Las plantillas, aunque típicamente vienen con una configuración específica, están diseñadas para ser flexibles y personalizables. Esto te permite modificarlas y adaptarlas a los requisitos de tu proyecto, lo que las convierte en un excelente punto de partida. 🏁 +Las plantillas, aunque normalmente vienen con una configuración específica, están diseñadas para ser flexibles y personalizables. Esto te permite modificarlas y adaptarlas a los requisitos de tu proyecto, haciéndolas un excelente punto de partida. 🏁 -Puedes utilizar esta plantilla para comenzar, ya que incluye gran parte de la configuración inicial, seguridad, base de datos y algunos endpoints de API ya realizados. +Puedes usar esta plantilla para comenzar, ya que incluye gran parte de la configuración inicial, seguridad, base de datos y algunos endpoints de API ya hechos para ti. -Repositorio en GitHub: [Full Stack FastAPI Template](https://github.com/tiangolo/full-stack-fastapi-template) +Repositorio de GitHub: Plantilla Full Stack FastAPI -## Plantilla de FastAPI Full Stack - Tecnología y Características +## Plantilla Full Stack FastAPI - Tecnología y Funcionalidades -- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) para el backend API en Python. - - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) para las interacciones con la base de datos SQL en Python (ORM). - - 🔍 [Pydantic](https://docs.pydantic.dev), utilizado por FastAPI, para la validación de datos y la gestión de configuraciones. - - 💾 [PostgreSQL](https://www.postgresql.org) como la base de datos SQL. +- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) para la API del backend en Python. + - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) para las interacciones con bases de datos SQL en Python (ORM). + - 🔍 [Pydantic](https://docs.pydantic.dev), utilizado por FastAPI, para la validación de datos y gestión de configuraciones. + - 💾 [PostgreSQL](https://www.postgresql.org) como base de datos SQL. - 🚀 [React](https://react.dev) para el frontend. - - 💃 Usando TypeScript, hooks, [Vite](https://vitejs.dev) y otras partes de un stack de frontend moderno. + - 💃 Usando TypeScript, hooks, [Vite](https://vitejs.dev), y otras partes de una stack moderna de frontend. - 🎨 [Chakra UI](https://chakra-ui.com) para los componentes del frontend. - - 🤖 Un cliente frontend generado automáticamente. + - 🤖 Un cliente de frontend generado automáticamente. - 🧪 [Playwright](https://playwright.dev) para pruebas End-to-End. - 🦇 Soporte para modo oscuro. - 🐋 [Docker Compose](https://www.docker.com) para desarrollo y producción. - 🔒 Hashing seguro de contraseñas por defecto. -- 🔑 Autenticación con token JWT. +- 🔑 Autenticación con tokens JWT. - 📫 Recuperación de contraseñas basada en email. -- ✅ Tests con [Pytest](https://pytest.org). +- ✅ Pruebas con [Pytest](https://pytest.org). - 📞 [Traefik](https://traefik.io) como proxy inverso / balanceador de carga. -- 🚢 Instrucciones de despliegue utilizando Docker Compose, incluyendo cómo configurar un proxy frontend Traefik para manejar certificados HTTPS automáticos. +- 🚢 Instrucciones de despliegue usando Docker Compose, incluyendo cómo configurar un proxy Traefik frontend para manejar certificados HTTPS automáticos. - 🏭 CI (integración continua) y CD (despliegue continuo) basados en GitHub Actions. diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md index de502314e..769204f8f 100644 --- a/docs/es/docs/python-types.md +++ b/docs/es/docs/python-types.md @@ -1,20 +1,20 @@ -# Introducción a los Tipos de Python +# Introducción a Tipos en Python -**Python 3.6+** tiene soporte para "type hints" opcionales. +Python tiene soporte para "anotaciones de tipos" opcionales (también llamadas "type hints"). -Estos **type hints** son una nueva sintaxis, desde Python 3.6+, que permite declarar el tipo de una variable. +Estas **"anotaciones de tipos"** o type hints son una sintaxis especial que permite declarar el tipo de una variable. -Usando las declaraciones de tipos para tus variables, los editores y otras herramientas pueden proveerte un soporte mejor. +Al declarar tipos para tus variables, los editores y herramientas te pueden proporcionar un mejor soporte. -Este es solo un **tutorial corto** sobre los Python type hints. Solo cubre lo mínimo necesario para usarlos con **FastAPI**... realmente es muy poco lo que necesitas. +Este es solo un **tutorial rápido / recordatorio** sobre las anotaciones de tipos en Python. Cubre solo lo mínimo necesario para usarlas con **FastAPI**... que en realidad es muy poco. -Todo **FastAPI** está basado en estos type hints, lo que le da muchas ventajas y beneficios. +**FastAPI** se basa completamente en estas anotaciones de tipos, dándole muchas ventajas y beneficios. -Pero, así nunca uses **FastAPI** te beneficiarás de aprender un poco sobre los type hints. +Pero incluso si nunca usas **FastAPI**, te beneficiaría aprender un poco sobre ellas. /// note | Nota -Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al siguiente capítulo. +Si eres un experto en Python, y ya sabes todo sobre las anotaciones de tipos, salta al siguiente capítulo. /// @@ -24,8 +24,7 @@ Comencemos con un ejemplo simple: {* ../../docs_src/python_types/tutorial001.py *} - -Llamar este programa nos muestra el siguiente output: +Llamar a este programa genera: ``` John Doe @@ -33,38 +32,37 @@ John Doe La función hace lo siguiente: -* Toma un `first_name` y un `last_name`. -* Convierte la primera letra de cada uno en una letra mayúscula con `title()`. -* Las concatena con un espacio en la mitad. +* Toma un `first_name` y `last_name`. +* Convierte la primera letra de cada uno a mayúsculas con `title()`. +* Concatena ambos con un espacio en el medio. {* ../../docs_src/python_types/tutorial001.py hl[2] *} - ### Edítalo Es un programa muy simple. -Ahora, imagina que lo estás escribiendo desde cero. +Pero ahora imagina que lo escribieras desde cero. -En algún punto habrías comenzado con la definición de la función, tenías los parámetros listos... +En algún momento habrías empezado la definición de la función, tenías los parámetros listos... -Pero, luego tienes que llamar "ese método que convierte la primera letra en una mayúscula". +Pero luego tienes que llamar "ese método que convierte la primera letra a mayúscula". -Era `upper`? O era `uppercase`? `first_uppercase`? `capitalize`? +¿Era `upper`? ¿Era `uppercase`? `first_uppercase`? `capitalize`? -Luego lo intentas con el viejo amigo de los programadores, el auto-completado del editor. +Entonces, pruebas con el amigo del viejo programador, el autocompletado del editor. -Escribes el primer parámetro de la función `first_name`, luego un punto (`.`) y luego presionas `Ctrl+Space` para iniciar el auto-completado. +Escribes el primer parámetro de la función, `first_name`, luego un punto (`.`) y luego presionas `Ctrl+Espacio` para activar el autocompletado. -Tristemente, no obtienes nada útil: +Pero, tristemente, no obtienes nada útil: - + -### Añade tipos +### Añadir tipos -Vamos a modificar una única línea de la versión previa. +Modifiquemos una sola línea de la versión anterior. -Vamos a cambiar exactamente este fragmento, los parámetros de la función, de: +Cambiaremos exactamente este fragmento, los parámetros de la función, de: ```Python first_name, last_name @@ -78,60 +76,57 @@ a: Eso es todo. -Esos son los "type hints": +Esas son las "anotaciones de tipos": {* ../../docs_src/python_types/tutorial002.py hl[1] *} - -No es lo mismo a declarar valores por defecto, como sería con: +Eso no es lo mismo que declarar valores predeterminados como sería con: ```Python first_name="john", last_name="doe" ``` -Es algo diferente. +Es una cosa diferente. -Estamos usando los dos puntos (`:`), no un símbolo de igual (`=`). +Estamos usando dos puntos (`:`), no igualdades (`=`). -Añadir los type hints normalmente no cambia lo que sucedería si ellos no estuviesen presentes. +Y agregar anotaciones de tipos normalmente no cambia lo que sucede de lo que ocurriría sin ellas. -Pero ahora imagina que nuevamente estás creando la función, pero con los type hints. +Pero ahora, imagina que nuevamente estás en medio de la creación de esa función, pero con anotaciones de tipos. -En el mismo punto intentas iniciar el auto-completado con `Ctrl+Space` y ves: +En el mismo punto, intentas activar el autocompletado con `Ctrl+Espacio` y ves: - + -Con esto puedes moverte hacia abajo viendo las opciones hasta que encuentras una que te suene: +Con eso, puedes desplazarte, viendo las opciones, hasta que encuentres la que "te suene": - + ## Más motivación -Mira esta función que ya tiene type hints: +Revisa esta función, ya tiene anotaciones de tipos: {* ../../docs_src/python_types/tutorial003.py hl[1] *} +Porque el editor conoce los tipos de las variables, no solo obtienes autocompletado, también obtienes chequeo de errores: -Como el editor conoce el tipo de las variables no solo obtienes auto-completado, si no que también obtienes chequeo de errores: + - - -Ahora que sabes que tienes que arreglarlo convierte `age` a un string con `str(age)`: +Ahora sabes que debes corregirlo, convertir `age` a un string con `str(age)`: {* ../../docs_src/python_types/tutorial004.py hl[2] *} +## Declaración de tipos -## Declarando tipos - -Acabas de ver el lugar principal para declarar los type hints. Como parámetros de las funciones. +Acabas de ver el lugar principal para declarar anotaciones de tipos. Como parámetros de función. -Este es también el lugar principal en que los usarías con **FastAPI**. +Este también es el lugar principal donde los utilizarías con **FastAPI**. ### Tipos simples -Puedes declarar todos los tipos estándar de Python, no solamente `str`. +Puedes declarar todos los tipos estándar de Python, no solo `str`. -Por ejemplo, puedes usar: +Puedes usar, por ejemplo: * `int` * `float` @@ -140,143 +135,442 @@ Por ejemplo, puedes usar: {* ../../docs_src/python_types/tutorial005.py hl[1] *} +### Tipos genéricos con parámetros de tipo + +Hay algunas estructuras de datos que pueden contener otros valores, como `dict`, `list`, `set` y `tuple`. Y los valores internos también pueden tener su propio tipo. + +Estos tipos que tienen tipos internos se denominan tipos "**genéricos**". Y es posible declararlos, incluso con sus tipos internos. + +Para declarar esos tipos y los tipos internos, puedes usar el módulo estándar de Python `typing`. Existe específicamente para soportar estas anotaciones de tipos. + +#### Versiones más recientes de Python + +La sintaxis que utiliza `typing` es **compatible** con todas las versiones, desde Python 3.6 hasta las versiones más recientes, incluyendo Python 3.9, Python 3.10, etc. -### Tipos con sub-tipos +A medida que avanza Python, las **versiones más recientes** vienen con soporte mejorado para estas anotaciones de tipos y en muchos casos ni siquiera necesitarás importar y usar el módulo `typing` para declarar las anotaciones de tipos. -Existen algunas estructuras de datos que pueden contener otros valores, como `dict`, `list`, `set` y `tuple`. Los valores internos pueden tener su propio tipo también. +Si puedes elegir una versión más reciente de Python para tu proyecto, podrás aprovechar esa simplicidad adicional. -Para declarar esos tipos y sub-tipos puedes usar el módulo estándar de Python `typing`. +En toda la documentación hay ejemplos compatibles con cada versión de Python (cuando hay una diferencia). -Él existe específicamente para dar soporte a este tipo de type hints. +Por ejemplo, "**Python 3.6+**" significa que es compatible con Python 3.6 o superior (incluyendo 3.7, 3.8, 3.9, 3.10, etc). Y "**Python 3.9+**" significa que es compatible con Python 3.9 o superior (incluyendo 3.10, etc). + +Si puedes usar las **últimas versiones de Python**, utiliza los ejemplos para la última versión, esos tendrán la **mejor y más simple sintaxis**, por ejemplo, "**Python 3.10+**". + +#### Lista + +Por ejemplo, vamos a definir una variable para ser una `list` de `str`. + +//// tab | Python 3.9+ + +Declara la variable, con la misma sintaxis de dos puntos (`:`). + +Como tipo, pon `list`. + +Como la lista es un tipo que contiene algunos tipos internos, los pones entre corchetes: + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006_py39.py!} +``` -#### Listas +//// -Por ejemplo, vamos a definir una variable para que sea una `list` compuesta de `str`. +//// tab | Python 3.8+ De `typing`, importa `List` (con una `L` mayúscula): -{* ../../docs_src/python_types/tutorial006.py hl[1] *} +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006.py!} +``` + +Declara la variable, con la misma sintaxis de dos puntos (`:`). + +Como tipo, pon el `List` que importaste de `typing`. + +Como la lista es un tipo que contiene algunos tipos internos, los pones entre corchetes: + +```Python hl_lines="4" +{!> ../../docs_src/python_types/tutorial006.py!} +``` +//// -Declara la variable con la misma sintaxis de los dos puntos (`:`). +/// info | Información -Pon `List` como el tipo. +Esos tipos internos en los corchetes se denominan "parámetros de tipo". -Como la lista es un tipo que permite tener un "sub-tipo" pones el sub-tipo en corchetes `[]`: +En este caso, `str` es el parámetro de tipo pasado a `List` (o `list` en Python 3.9 y superior). -{* ../../docs_src/python_types/tutorial006.py hl[4] *} +/// +Eso significa: "la variable `items` es una `list`, y cada uno de los ítems en esta lista es un `str`". -Esto significa: la variable `items` es una `list` y cada uno de los ítems en esta lista es un `str`. +/// tip | Consejo -Con esta declaración tu editor puede proveerte soporte inclusive mientras está procesando ítems de la lista. +Si usas Python 3.9 o superior, no tienes que importar `List` de `typing`, puedes usar el mismo tipo `list` regular en su lugar. + +/// -Sin tipos el auto-completado en este tipo de estructura es casi imposible de lograr: +Al hacer eso, tu editor puede proporcionar soporte incluso mientras procesa elementos de la lista: - + -Observa que la variable `item` es unos de los elementos en la lista `items`. +Sin tipos, eso es casi imposible de lograr. -El editor aún sabe que es un `str` y provee soporte para ello. +Nota que la variable `item` es uno de los elementos en la lista `items`. -#### Tuples y Sets +Y aún así, el editor sabe que es un `str` y proporciona soporte para eso. + +#### Tuple y Set Harías lo mismo para declarar `tuple`s y `set`s: -{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial007_py39.py!} +``` +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial007.py!} +``` + +//// Esto significa: * La variable `items_t` es un `tuple` con 3 ítems, un `int`, otro `int`, y un `str`. -* La variable `items_s` es un `set` y cada uno de sus ítems es de tipo `bytes`. +* La variable `items_s` es un `set`, y cada uno de sus ítems es del tipo `bytes`. + +#### Dict + +Para definir un `dict`, pasas 2 parámetros de tipo, separados por comas. -#### Diccionarios (Dicts) +El primer parámetro de tipo es para las claves del `dict`. -Para definir un `dict` le pasas 2 sub-tipos separados por comas. +El segundo parámetro de tipo es para los valores del `dict`: -El primer sub-tipo es para los keys del `dict`. +//// tab | Python 3.9+ -El segundo sub-tipo es para los valores del `dict`: +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008_py39.py!} +``` + +//// -{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} +//// tab | Python 3.8+ +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008.py!} +``` + +//// Esto significa: * La variable `prices` es un `dict`: - * Los keys de este `dict` son de tipo `str` (Digamos que son el nombre de cada ítem). - * Los valores de este `dict` son de tipo `float` (Digamos que son el precio de cada ítem). + * Las claves de este `dict` son del tipo `str` (digamos, el nombre de cada ítem). + * Los valores de este `dict` son del tipo `float` (digamos, el precio de cada ítem). + +#### Union + +Puedes declarar que una variable puede ser cualquier de **varios tipos**, por ejemplo, un `int` o un `str`. + +En Python 3.6 y posterior (incluyendo Python 3.10) puedes usar el tipo `Union` de `typing` y poner dentro de los corchetes los posibles tipos a aceptar. + +En Python 3.10 también hay una **nueva sintaxis** donde puedes poner los posibles tipos separados por una barra vertical (`|`). + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008b.py!} +``` + +//// + +En ambos casos, esto significa que `item` podría ser un `int` o un `str`. + +#### Posiblemente `None` + +Puedes declarar que un valor podría tener un tipo, como `str`, pero que también podría ser `None`. + +En Python 3.6 y posteriores (incluyendo Python 3.10) puedes declararlo importando y usando `Optional` del módulo `typing`. + +```Python hl_lines="1 4" +{!../../docs_src/python_types/tutorial009.py!} +``` + +Usar `Optional[str]` en lugar de solo `str` te permitirá al editor ayudarte a detectar errores donde podrías estar asumiendo que un valor siempre es un `str`, cuando en realidad también podría ser `None`. + +`Optional[Something]` es realmente un atajo para `Union[Something, None]`, son equivalentes. + +Esto también significa que en Python 3.10, puedes usar `Something | None`: + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009.py!} +``` + +//// + +//// tab | Python 3.8+ alternative + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009b.py!} +``` + +//// + +#### Uso de `Union` u `Optional` + +Si estás usando una versión de Python inferior a 3.10, aquí tienes un consejo desde mi punto de vista muy **subjetivo**: + +* 🚨 Evita usar `Optional[SomeType]` +* En su lugar ✨ **usa `Union[SomeType, None]`** ✨. + +Ambos son equivalentes y debajo son lo mismo, pero recomendaría `Union` en lugar de `Optional` porque la palabra "**opcional**" parecería implicar que el valor es opcional, y en realidad significa "puede ser `None`", incluso si no es opcional y aún es requerido. + +Creo que `Union[SomeType, None]` es más explícito sobre lo que significa. + +Se trata solo de las palabras y nombres. Pero esas palabras pueden afectar cómo tú y tus compañeros de equipo piensan sobre el código. + +Como ejemplo, tomemos esta función: + +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} + +El parámetro `name` está definido como `Optional[str]`, pero **no es opcional**, no puedes llamar a la función sin el parámetro: + +```Python +say_hi() # ¡Oh, no, esto lanza un error! 😱 +``` + +El parámetro `name` sigue siendo **requerido** (no *opcional*) porque no tiene un valor predeterminado. Aún así, `name` acepta `None` como valor: + +```Python +say_hi(name=None) # Esto funciona, None es válido 🎉 +``` + +La buena noticia es que, una vez que estés en Python 3.10, no tendrás que preocuparte por eso, ya que podrás simplemente usar `|` para definir uniones de tipos: + +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} + +Y entonces no tendrás que preocuparte por nombres como `Optional` y `Union`. 😎 + +#### Tipos genéricos + +Estos tipos que toman parámetros de tipo en corchetes se llaman **Tipos Genéricos** o **Genéricos**, por ejemplo: + +//// tab | Python 3.10+ + +Puedes usar los mismos tipos integrados como genéricos (con corchetes y tipos dentro): + +* `list` +* `tuple` +* `set` +* `dict` + +Y lo mismo que con Python 3.8, desde el módulo `typing`: + +* `Union` +* `Optional` (lo mismo que con Python 3.8) +* ...y otros. + +En Python 3.10, como alternativa a usar los genéricos `Union` y `Optional`, puedes usar la barra vertical (`|`) para declarar uniones de tipos, eso es mucho mejor y más simple. + +//// + +//// tab | Python 3.9+ + +Puedes usar los mismos tipos integrados como genéricos (con corchetes y tipos dentro): + +* `list` +* `tuple` +* `set` +* `dict` + +Y lo mismo que con Python 3.8, desde el módulo `typing`: + +* `Union` +* `Optional` +* ...y otros. + +//// + +//// tab | Python 3.8+ + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...y otros. + +//// ### Clases como tipos También puedes declarar una clase como el tipo de una variable. -Digamos que tienes una clase `Person`con un nombre: +Digamos que tienes una clase `Person`, con un nombre: + +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + +Luego puedes declarar una variable para que sea de tipo `Person`: -{* ../../docs_src/python_types/tutorial009.py hl[1:3] *} +{* ../../docs_src/python_types/tutorial010.py hl[6] *} +Y luego, nuevamente, obtienes todo el soporte del editor: -Entonces puedes declarar una variable que sea de tipo `Person`: + -{* ../../docs_src/python_types/tutorial009.py hl[6] *} +Nota que esto significa "`one_person` es una **instance** de la clase `Person`". +No significa "`one_person` es la **clase** llamada `Person`". -Una vez más tendrás todo el soporte del editor: +## Modelos Pydantic - +Pydantic es un paquete de Python para realizar la validación de datos. -## Modelos de Pydantic +Declaras la "forma" de los datos como clases con atributos. -Pydantic es una library de Python para llevar a cabo validación de datos. +Y cada atributo tiene un tipo. -Tú declaras la "forma" de los datos mediante clases con atributos. +Entonces creas un instance de esa clase con algunos valores y validará los valores, los convertirá al tipo adecuado (si es el caso) y te dará un objeto con todos los datos. -Cada atributo tiene un tipo. +Y obtienes todo el soporte del editor con ese objeto resultante. -Luego creas un instance de esa clase con algunos valores y Pydantic validará los valores, los convertirá al tipo apropiado (si ese es el caso) y te dará un objeto con todos los datos. +Un ejemplo de la documentación oficial de Pydantic: -Y obtienes todo el soporte del editor con el objeto resultante. +//// tab | Python 3.10+ -Tomado de la documentación oficial de Pydantic: +```Python +{!> ../../docs_src/python_types/tutorial011_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/python_types/tutorial011_py39.py!} +``` + +//// -{* ../../docs_src/python_types/tutorial010.py *} +//// tab | Python 3.8+ +```Python +{!> ../../docs_src/python_types/tutorial011.py!} +``` + +//// /// info | Información -Para aprender más sobre Pydantic mira su documentación. +Para saber más sobre Pydantic, revisa su documentación. /// -**FastAPI** está todo basado en Pydantic. +**FastAPI** está completamente basado en Pydantic. + +Verás mucho más de todo esto en práctica en el [Tutorial - Guía del Usuario](tutorial/index.md){.internal-link target=_blank}. + +/// tip | Consejo + +Pydantic tiene un comportamiento especial cuando utilizas `Optional` o `Union[Something, None]` sin un valor por defecto, puedes leer más sobre ello en la documentación de Pydantic sobre Required Optional fields. + +/// + +## Anotaciones de tipos con metadata + +Python también tiene una funcionalidad que permite poner **metadata adicional** en estas anotaciones de tipos usando `Annotated`. + +//// tab | Python 3.9+ -Vas a ver mucho más de esto en práctica en el [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}. +En Python 3.9, `Annotated` es parte de la librería estándar, así que puedes importarlo desde `typing`. + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +En versiones por debajo de Python 3.9, importas `Annotated` de `typing_extensions`. + +Ya estará instalado con **FastAPI**. + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013.py!} +``` + +//// + +Python en sí no hace nada con este `Annotated`. Y para los editores y otras herramientas, el tipo sigue siendo `str`. + +Pero puedes usar este espacio en `Annotated` para proporcionar a **FastAPI** metadata adicional sobre cómo quieres que se comporte tu aplicación. + +Lo importante a recordar es que **el primer *parámetro de tipo*** que pasas a `Annotated` es el **tipo real**. El resto es solo metadata para otras herramientas. + +Por ahora, solo necesitas saber que `Annotated` existe, y que es Python estándar. 😎 + +Luego verás lo **poderoso** que puede ser. + +/// tip | Consejo + +El hecho de que esto sea **Python estándar** significa que seguirás obteniendo la **mejor experiencia de desarrollador posible** en tu editor, con las herramientas que usas para analizar y refactorizar tu código, etc. ✨ + +Y también que tu código será muy compatible con muchas otras herramientas y paquetes de Python. 🚀 + +/// -## Type hints en **FastAPI** +## Anotaciones de tipos en **FastAPI** -**FastAPI** aprovecha estos type hints para hacer varias cosas. +**FastAPI** aprovecha estas anotaciones de tipos para hacer varias cosas. -Con **FastAPI** declaras los parámetros con type hints y obtienes: +Con **FastAPI** declaras parámetros con anotaciones de tipos y obtienes: -* **Soporte en el editor**. -* **Type checks**. +* **Soporte del editor**. +* **Chequeo de tipos**. ...y **FastAPI** usa las mismas declaraciones para: -* **Definir requerimientos**: desde request path parameters, query parameters, headers, bodies, dependencies, etc. -* **Convertir datos**: desde el request al tipo requerido. -* **Validar datos**: viniendo de cada request: +* **Definir requerimientos**: de parámetros de path de la request, parámetros de query, headers, bodies, dependencias, etc. +* **Convertir datos**: de la request al tipo requerido. +* **Validar datos**: provenientes de cada request: * Generando **errores automáticos** devueltos al cliente cuando los datos son inválidos. * **Documentar** la API usando OpenAPI: - * que en su caso es usada por las interfaces de usuario de la documentación automática e interactiva. + * Que luego es usada por las interfaces de documentación interactiva automática. -Puede que todo esto suene abstracto. Pero no te preocupes que todo lo verás en acción en el [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}. +Todo esto puede sonar abstracto. No te preocupes. Verás todo esto en acción en el [Tutorial - Guía del Usuario](tutorial/index.md){.internal-link target=_blank}. -Lo importante es que usando los tipos de Python estándar en un único lugar (en vez de añadir más clases, decorator, etc.) **FastAPI** hará mucho del trabajo por ti. +Lo importante es que al usar tipos estándar de Python, en un solo lugar (en lugar de agregar más clases, decoradores, etc.), **FastAPI** hará gran parte del trabajo por ti. /// info | Información -Si ya pasaste por todo el tutorial y volviste a la sección de los tipos, una buena referencia es la "cheat sheet" de `mypy`. +Si ya revisaste todo el tutorial y volviste para ver más sobre tipos, un buen recurso es la "cheat sheet" de `mypy`. /// diff --git a/docs/es/docs/tutorial/cookie-params.md b/docs/es/docs/tutorial/cookie-params.md index 9a3b1a00b..45b113ff9 100644 --- a/docs/es/docs/tutorial/cookie-params.md +++ b/docs/es/docs/tutorial/cookie-params.md @@ -1,30 +1,30 @@ # Parámetros de Cookie -Puedes definir parámetros de Cookie de la misma manera que defines parámetros de `Query` y `Path`. +Puedes definir parámetros de Cookie de la misma manera que defines los parámetros `Query` y `Path`. ## Importar `Cookie` Primero importa `Cookie`: -{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3]*} +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## Declarar parámetros de `Cookie` Luego declara los parámetros de cookie usando la misma estructura que con `Path` y `Query`. -El primer valor es el valor por defecto, puedes pasar todos los parámetros adicionales de validación o anotación: +Puedes definir el valor por defecto así como toda la validación extra o los parámetros de anotación: -{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9]*} +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} /// note | Detalles Técnicos `Cookie` es una clase "hermana" de `Path` y `Query`. También hereda de la misma clase común `Param`. -Pero recuerda que cuando importas `Query`, `Path`, `Cookie` y otros de `fastapi`, en realidad son funciones que devuelven clases especiales. +Pero recuerda que cuando importas `Query`, `Path`, `Cookie` y otros desde `fastapi`, en realidad son funciones que devuelven clases especiales. /// -/// info +/// info | Información Para declarar cookies, necesitas usar `Cookie`, porque de lo contrario los parámetros serían interpretados como parámetros de query. diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md index 4cc4cc11d..5d869c22f 100644 --- a/docs/es/docs/tutorial/first-steps.md +++ b/docs/es/docs/tutorial/first-steps.md @@ -1,50 +1,74 @@ -# Primeros pasos +# Primeros Pasos -Un archivo muy simple de FastAPI podría verse así: +El archivo FastAPI más simple podría verse así: {* ../../docs_src/first_steps/tutorial001.py *} -Copia eso a un archivo `main.py`. +Copia eso en un archivo `main.py`. -Corre el servidor en vivo: +Ejecuta el servidor en vivo:
```console -$ uvicorn main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] -INFO: Waiting for application startup. -INFO: Application startup complete. +$ 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. ```
-/// note | Nota - -El comando `uvicorn main:app` se refiere a: - -* `main`: el archivo `main.py` (el "módulo" de Python). -* `app`: el objeto creado dentro de `main.py` con la línea `app = FastAPI()`. -* `--reload`: hace que el servidor se reinicie cada vez que cambia el código. Úsalo únicamente para desarrollo. - -/// - -En el output, hay una línea que dice más o menos: +En el resultado, hay una línea con algo como: ```hl_lines="4" INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` -Esa línea muestra la URL dónde se está sirviendo tu app en tu maquina local. +Esa línea muestra la URL donde tu aplicación está siendo servida, en tu máquina local. -### Revísalo +### Compruébalo Abre tu navegador en http://127.0.0.1:8000. -Verás la respuesta en JSON: +Verás el response JSON como: ```JSON {"message": "Hello World"} @@ -52,55 +76,55 @@ Verás la respuesta en JSON: ### Documentación interactiva de la API -Ahora dirígete a http://127.0.0.1:8000/docs. +Ahora ve a http://127.0.0.1:8000/docs. -Ahí verás la documentación automática e interactiva de la API (proveída por Swagger UI): +Verás la documentación interactiva automática de la API (proporcionada por Swagger UI): ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) ### Documentación alternativa de la API -Ahora, dirígete a http://127.0.0.1:8000/redoc. +Y ahora, ve a http://127.0.0.1:8000/redoc. -Aquí verás la documentación automática alternativa (proveída por ReDoc): +Verás la documentación alternativa automática (proporcionada por ReDoc): ![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) ### OpenAPI -**FastAPI** genera un "schema" con toda tu API usando el estándar para definir APIs, **OpenAPI**. +**FastAPI** genera un "esquema" con toda tu API utilizando el estándar **OpenAPI** para definir APIs. -#### "Schema" +#### "Esquema" -Un "schema" es una definición o descripción de algo. No es el código que la implementa, sino solo una descripción abstracta. +Un "esquema" es una definición o descripción de algo. No el código que lo implementa, sino solo una descripción abstracta. -#### "Schema" de la API +#### Esquema de la API -En este caso, OpenAPI es una especificación que dicta como se debe definir el schema de tu API. +En este caso, OpenAPI es una especificación que dicta cómo definir un esquema de tu API. -La definición del schema incluye los paths de tu API, los parámetros que podría recibir, etc. +Esta definición de esquema incluye los paths de tu API, los posibles parámetros que toman, etc. -#### "Schema" de datos +#### Esquema de Datos -El concepto "schema" también se puede referir a la forma de algunos datos, como un contenido en formato JSON. +El término "esquema" también podría referirse a la forma de algunos datos, como el contenido JSON. -En ese caso haría referencia a los atributos del JSON, los tipos de datos que tiene, etc. +En ese caso, significaría los atributos del JSON, los tipos de datos que tienen, etc. #### OpenAPI y JSON Schema -OpenAPI define un schema de API para tu API. Ese schema incluye definiciones (o "schemas") de los datos enviados y recibidos por tu API usando **JSON Schema**, el estándar para los schemas de datos en JSON. +OpenAPI define un esquema de API para tu API. Y ese esquema incluye definiciones (o "esquemas") de los datos enviados y recibidos por tu API utilizando **JSON Schema**, el estándar para esquemas de datos JSON. #### Revisa el `openapi.json` -Si sientes curiosidad por saber cómo se ve el schema de OpenAPI en bruto, FastAPI genera automáticamente un (schema) JSON con la descripción de todo tu API. +Si tienes curiosidad por cómo se ve el esquema OpenAPI en bruto, FastAPI automáticamente genera un JSON (esquema) con las descripciones de toda tu API. -Lo puedes ver directamente en: http://127.0.0.1:8000/openapi.json. +Puedes verlo directamente en: http://127.0.0.1:8000/openapi.json. -Esto te mostrará un JSON que comienza con algo como: +Mostrará un JSON que empieza con algo como: ```JSON { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": { "title": "FastAPI", "version": "0.1.0" @@ -119,73 +143,45 @@ Esto te mostrará un JSON que comienza con algo como: ... ``` -#### ¿Para qué se usa OpenAPI? +#### Para qué sirve OpenAPI -El schema de OpenAPI es lo que alimenta a los dos sistemas de documentación interactiva incluidos. +El esquema OpenAPI es lo que impulsa los dos sistemas de documentación interactiva incluidos. -También hay docenas de alternativas, todas basadas en OpenAPI. Podrías añadir fácilmente cualquiera de esas alternativas a tu aplicación construida con **FastAPI**. +Y hay docenas de alternativas, todas basadas en OpenAPI. Podrías añadir fácilmente cualquiera de esas alternativas a tu aplicación construida con **FastAPI**. -También podrías usarlo para generar código automáticamente, para los clientes que se comunican con tu API. Por ejemplo, frontend, móvil o aplicaciones de IoT. +También podrías usarlo para generar código automáticamente, para clientes que se comuniquen con tu API. Por ejemplo, aplicaciones frontend, móviles o IoT. -## Repaso, paso a paso +## Recapitulación, paso a paso ### Paso 1: importa `FastAPI` {* ../../docs_src/first_steps/tutorial001.py hl[1] *} -`FastAPI` es una clase de Python que provee toda la funcionalidad para tu API. +`FastAPI` es una clase de Python que proporciona toda la funcionalidad para tu API. /// note | Detalles Técnicos `FastAPI` es una clase que hereda directamente de `Starlette`. -También puedes usar toda la funcionalidad de Starlette. +Puedes usar toda la funcionalidad de Starlette con `FastAPI` también. /// -### Paso 2: crea un "instance" de `FastAPI` +### Paso 2: crea una "instance" de `FastAPI` {* ../../docs_src/first_steps/tutorial001.py hl[3] *} -Aquí la variable `app` será un instance de la clase `FastAPI`. +Aquí la variable `app` será una "instance" de la clase `FastAPI`. -Este será el punto de interacción principal para crear todo tu API. - -Esta `app` es la misma a la que nos referimos cuando usamos el comando de `uvicorn`: - -
- -```console -$ uvicorn main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -Si creas un app como: - -{* ../../docs_src/first_steps/tutorial002.py hl[3] *} - -y lo guardas en un archivo `main.py`, entonces ejecutarías `uvicorn` así: - -
- -```console -$ uvicorn main:my_awesome_api --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
+Este será el punto principal de interacción para crear toda tu API. -### Paso 3: crea una *operación de path* +### Paso 3: crea una *path operation* #### Path -"Path" aquí se refiere a la última parte de una URL comenzando desde el primer `/`. +"Path" aquí se refiere a la última parte de la URL empezando desde la primera `/`. -Entonces, en una URL como: +Así que, en una URL como: ``` https://example.com/items/foo @@ -197,19 +193,19 @@ https://example.com/items/foo /items/foo ``` -/// info | Información +/// info -Un "path" también se conoce habitualmente como "endpoint", "route" o "ruta". +Un "path" también es comúnmente llamado "endpoint" o "ruta". /// -Cuando construyes una API, el "path" es la manera principal de separar los "intereses" y los "recursos". +Mientras construyes una API, el "path" es la forma principal de separar "concerns" y "resources". #### Operación -"Operación" aquí se refiere a uno de los "métodos" de HTTP. +"Operación" aquí se refiere a uno de los "métodos" HTTP. -Uno como: +Uno de: * `POST` * `GET` @@ -223,43 +219,43 @@ Uno como: * `PATCH` * `TRACE` -En el protocolo de HTTP, te puedes comunicar con cada path usando uno (o más) de estos "métodos". +En el protocolo HTTP, puedes comunicarte con cada path usando uno (o más) de estos "métodos". --- -Cuando construyes APIs, normalmente usas uno de estos métodos específicos de HTTP para realizar una acción específica. +Al construir APIs, normalmente usas estos métodos HTTP específicos para realizar una acción específica. Normalmente usas: * `POST`: para crear datos. * `GET`: para leer datos. * `PUT`: para actualizar datos. -* `DELETE`: para borrar datos. +* `DELETE`: para eliminar datos. -Así que en OpenAPI, cada uno de estos métodos de HTTP es referido como una "operación". +Así que, en OpenAPI, cada uno de los métodos HTTP se llama una "operation". -Nosotros también los llamaremos "**operación**". +Vamos a llamarlas "**operaciones**" también. -#### Define un *decorador de operaciones de path* +#### Define un *path operation decorator* {* ../../docs_src/first_steps/tutorial001.py hl[6] *} -El `@app.get("/")` le dice a **FastAPI** que la función que tiene justo debajo está a cargo de manejar los requests que van a: +El `@app.get("/")` le dice a **FastAPI** que la función justo debajo se encarga de manejar requests que vayan a: * el path `/` -* usando una operación get +* usando una get operation /// info | Información sobre `@decorator` -Esa sintaxis `@algo` se llama un "decorador" en Python. +Esa sintaxis `@algo` en Python se llama un "decorador". -Lo pones encima de una función. Es como un lindo sombrero decorado (creo que de ahí salió el concepto). +Lo pones encima de una función. Como un bonito sombrero decorativo (supongo que de ahí viene el término). -Un "decorador" toma la función que tiene debajo y hace algo con ella. +Un "decorador" toma la función de abajo y hace algo con ella. -En nuestro caso, este decorador le dice a **FastAPI** que la función que está debajo corresponde al **path** `/` con una **operación** `get`. +En nuestro caso, este decorador le dice a **FastAPI** que la función de abajo corresponde al **path** `/` con una **operation** `get`. -Es el "**decorador de operaciones de path**". +Es el "**path operation decorator**". /// @@ -269,67 +265,67 @@ También puedes usar las otras operaciones: * `@app.put()` * `@app.delete()` -y las más exóticas: +Y los más exóticos: * `@app.options()` * `@app.head()` * `@app.patch()` * `@app.trace()` -/// tip | Consejo +/// tip -Tienes la libertad de usar cada operación (método de HTTP) como quieras. +Eres libre de usar cada operación (método HTTP) como quieras. -**FastAPI** no impone ningún significado específico. +**FastAPI** no fuerza ningún significado específico. -La información que está presentada aquí es una guía, no un requerimiento. +La información aquí se presenta como una guía, no un requisito. -Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando únicamente operaciones `POST`. +Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando solo operaciones `POST`. /// -### Paso 4: define la **función de la operación de path** +### Paso 4: define la **path operation function** -Esta es nuestra "**función de la operación de path**": +Esta es nuestra "**path operation function**": * **path**: es `/`. -* **operación**: es `get`. -* **función**: es la función debajo del "decorador" (debajo de `@app.get("/")`). +* **operation**: es `get`. +* **function**: es la función debajo del "decorador" (debajo de `@app.get("/")`). {* ../../docs_src/first_steps/tutorial001.py hl[7] *} -Esto es una función de Python. +Esta es una función de Python. -Esta función será llamada por **FastAPI** cada vez que reciba un request en la URL "`/`" usando una operación `GET`. +Será llamada por **FastAPI** cuando reciba un request en la URL "`/`" usando una operación `GET`. -En este caso es una función `async`. +En este caso, es una función `async`. --- -También podrías definirla como una función estándar en lugar de `async def`: +También podrías definirla como una función normal en lugar de `async def`: {* ../../docs_src/first_steps/tutorial003.py hl[7] *} /// note | Nota -Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#tienes-prisa){.internal-link target=_blank}. +Si no sabes la diferencia, revisa la sección [Async: *"¿Tienes prisa?"*](../async.md#in-a-hurry){.internal-link target=_blank}. /// -### Paso 5: devuelve el contenido +### Paso 5: retorna el contenido {* ../../docs_src/first_steps/tutorial001.py hl[8] *} -Puedes devolver `dict`, `list`, valores singulares como un `str`, `int`, etc. +Puedes retornar un `dict`, `list`, valores singulares como `str`, `int`, etc. -También puedes devolver modelos de Pydantic (ya verás más sobre esto más adelante). +También puedes retornar modelos de Pydantic (verás más sobre eso más adelante). -Hay muchos objetos y modelos que pueden ser convertidos automáticamente a JSON (incluyendo ORMs, etc.). Intenta usar tus favoritos, es muy probable que ya tengan soporte. +Hay muchos otros objetos y modelos que serán automáticamente convertidos a JSON (incluyendo ORMs, etc). Intenta usar tus favoritos, es altamente probable que ya sean compatibles. -## Repaso +## Recapitulación * Importa `FastAPI`. -* Crea un instance de `app`. -* Escribe un **decorador de operación de path** (como `@app.get("/")`). -* Escribe una **función de la operación de path** (como `def root(): ...` arriba). -* Corre el servidor de desarrollo (como `uvicorn main:app --reload`). +* Crea una instancia `app`. +* Escribe un **path operation decorator** usando decoradores como `@app.get("/")`. +* Define una **path operation function**; por ejemplo, `def root(): ...`. +* Ejecuta el servidor de desarrollo usando el comando `fastapi dev`. diff --git a/docs/es/docs/tutorial/index.md b/docs/es/docs/tutorial/index.md index fa13450f0..dcfc6cdfb 100644 --- a/docs/es/docs/tutorial/index.md +++ b/docs/es/docs/tutorial/index.md @@ -1,81 +1,102 @@ -# Tutorial - Guía de Usuario +# Tutorial - Guía del Usuario -Este tutorial te muestra cómo usar **FastAPI** con la mayoría de sus características paso a paso. +Este tutorial te muestra cómo usar **FastAPI** con la mayoría de sus funcionalidades, paso a paso. -Cada sección se basa gradualmente en las anteriores, pero está estructurada en temas separados, así puedes ir directamente a cualquier tema en concreto para resolver tus necesidades específicas sobre la API. +Cada sección se basa gradualmente en las anteriores, pero está estructurada para separar temas, de manera que puedas ir directamente a cualquier sección específica para resolver tus necesidades específicas de API. -Funciona también como una referencia futura, para que puedas volver y ver exactamente lo que necesitas. +También está diseñado para funcionar como una referencia futura para que puedas volver y ver exactamente lo que necesitas. ## Ejecuta el código -Todos los bloques de código se pueden copiar y usar directamente (en realidad son archivos Python probados). +Todos los bloques de código pueden ser copiados y usados directamente (de hecho, son archivos Python probados). -Para ejecutar cualquiera de los ejemplos, copia el código en un archivo llamado `main.py`, y ejecuta `uvicorn` de la siguiente manera en tu terminal: +Para ejecutar cualquiera de los ejemplos, copia el código a un archivo `main.py`, y comienza `fastapi dev` con:
```console -$ uvicorn main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] -INFO: Waiting for application startup. -INFO: Application startup complete. +$ 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. + ```
-Se **RECOMIENDA** que escribas o copies el código, lo edites y lo ejecutes localmente. +Es **ALTAMENTE recomendable** que escribas o copies el código, lo edites y lo ejecutes localmente. -Usarlo en tu editor de código es lo que realmente te muestra los beneficios de FastAPI, al ver la poca cantidad de código que tienes que escribir, todas las verificaciones de tipo, auto-completado, etc. +Usarlo en tu editor es lo que realmente te muestra los beneficios de FastAPI, al ver cuán poco código tienes que escribir, todos los chequeos de tipos, autocompletado, etc. --- -## Instala FastAPI +## Instalar FastAPI El primer paso es instalar FastAPI. -Para el tutorial, es posible que quieras instalarlo con todas las dependencias y características opcionales: +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, actívalo, y luego **instala FastAPI**:
```console -$ pip install "fastapi[all]" +$ pip install "fastapi[standard]" ---> 100% ```
-...eso también incluye `uvicorn` que puedes usar como el servidor que ejecuta tu código. - /// note | Nota -También puedes instalarlo parte por parte. - -Esto es lo que probablemente harías una vez que desees implementar tu aplicación en producción: - -``` -pip install fastapi -``` - -También debes instalar `uvicorn` para que funcione como tu servidor: - -``` -pip install "uvicorn[standard]" -``` +Cuando instalas con `pip install "fastapi[standard]"` viene con algunas dependencias opcionales estándar por defecto. -Y lo mismo para cada una de las dependencias opcionales que quieras utilizar. +Si no quieres tener esas dependencias opcionales, en su lugar puedes instalar `pip install fastapi`. /// -## Guía Avanzada de Usuario +## Guía Avanzada del Usuario -También hay una **Guía Avanzada de Usuario** que puedes leer luego de este **Tutorial - Guía de Usuario**. +También hay una **Guía Avanzada del Usuario** que puedes leer después de esta **Tutorial - Guía del Usuario**. -La **Guía Avanzada de Usuario**, se basa en este tutorial, utiliza los mismos conceptos y enseña algunas características adicionales. +La **Guía Avanzada del Usuario** se basa en esta, utiliza los mismos conceptos y te enseña algunas funcionalidades adicionales. -Pero primero deberías leer el **Tutorial - Guía de Usuario** (lo que estas leyendo ahora mismo). +Pero primero deberías leer la **Tutorial - Guía del Usuario** (lo que estás leyendo ahora mismo). -La guía esa diseñada para que puedas crear una aplicación completa con solo el **Tutorial - Guía de Usuario**, y luego extenderlo de diferentes maneras, según tus necesidades, utilizando algunas de las ideas adicionales de la **Guía Avanzada de Usuario**. +Está diseñada para que puedas construir una aplicación completa solo con la **Tutorial - Guía del Usuario**, y luego extenderla de diferentes maneras, dependiendo de tus necesidades, utilizando algunas de las ideas adicionales de la **Guía Avanzada del Usuario**. diff --git a/docs/es/docs/tutorial/path-params.md b/docs/es/docs/tutorial/path-params.md index f36c4f493..12a1b647b 100644 --- a/docs/es/docs/tutorial/path-params.md +++ b/docs/es/docs/tutorial/path-params.md @@ -1,12 +1,12 @@ -# Parámetros de path +# Parámetros de Path -Puedes declarar los "parámetros" o "variables" con la misma sintaxis que usan los format strings de Python: +Puedes declarar "parámetros" o "variables" de path con la misma sintaxis que se usa en los format strings de Python: {* ../../docs_src/path_params/tutorial001.py hl[6:7] *} -El valor del parámetro de path `item_id` será pasado a tu función como el argumento `item_id`. +El valor del parámetro de path `item_id` se pasará a tu función como el argumento `item_id`. -Entonces, si corres este ejemplo y vas a http://127.0.0.1:8000/items/foo, verás una respuesta de: +Así que, si ejecutas este ejemplo y vas a http://127.0.0.1:8000/items/foo, verás un response de: ```JSON {"item_id":"foo"} @@ -14,21 +14,21 @@ Entonces, si corres este ejemplo y vas a Conversión de datos +## Conversión de datos -Si corres este ejemplo y abres tu navegador en http://127.0.0.1:8000/items/3 verás una respuesta de: +Si ejecutas este ejemplo y abres tu navegador en http://127.0.0.1:8000/items/3, verás un response de: ```JSON {"item_id":3} @@ -36,160 +36,168 @@ Si corres este ejemplo y abres tu navegador en "parsing" automático del request. +Entonces, con esa declaración de tipo, **FastAPI** te ofrece "parsing" automático de requests. /// ## Validación de datos -Pero si abres tu navegador en http://127.0.0.1:8000/items/foo verás este lindo error de HTTP: +Pero si vas al navegador en http://127.0.0.1:8000/items/foo, verás un bonito error HTTP de: ```JSON { - "detail": [ - { - "loc": [ - "path", - "item_id" - ], - "msg": "value is not a valid integer", - "type": "type_error.integer" - } - ] + "detail": [ + { + "type": "int_parsing", + "loc": [ + "path", + "item_id" + ], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": "https://errors.pydantic.dev/2.1/v/int_parsing" + } + ] } ``` -debido a que el parámetro de path `item_id` tenía el valor `"foo"`, que no es un `int`. +porque el parámetro de path `item_id` tenía un valor de `"foo"`, que no es un `int`. -El mismo error aparecería si pasaras un `float` en vez de un `int` como en: http://127.0.0.1:8000/items/4.2 +El mismo error aparecería si proporcionaras un `float` en lugar de un `int`, como en: http://127.0.0.1:8000/items/4.2 /// check | Revisa -Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos. +Entonces, con la misma declaración de tipo de Python, **FastAPI** te ofrece validación de datos. -Observa que el error también muestra claramente el punto exacto en el que no pasó la validación. +Nota que el error también indica claramente el punto exacto donde la validación falló. -Esto es increíblemente útil cuando estás desarrollando y debugging código que interactúa con tu API. +Esto es increíblemente útil mientras desarrollas y depuras código que interactúa con tu API. /// ## Documentación -Cuando abras tu navegador en http://127.0.0.1:8000/docs verás la documentación automática e interactiva del API como: +Y cuando abras tu navegador en http://127.0.0.1:8000/docs, verás una documentación de API automática e interactiva como: /// check | Revisa -Nuevamente, con la misma declaración de tipo de Python, **FastAPI** te da documentación automática e interactiva (integrándose con Swagger UI) +Nuevamente, solo con esa misma declaración de tipo de Python, **FastAPI** te ofrece documentación automática e interactiva (integrando Swagger UI). -Observa que el parámetro de path está declarado como un integer. +Nota que el parámetro de path está declarado como un entero. /// ## Beneficios basados en estándares, documentación alternativa -Debido a que el schema generado es del estándar OpenAPI hay muchas herramientas compatibles. +Y porque el esquema generado es del estándar OpenAPI, hay muchas herramientas compatibles. -Es por esto que **FastAPI** mismo provee una documentación alternativa de la API (usando ReDoc), a la que puedes acceder en http://127.0.0.1:8000/redoc: +Debido a esto, el propio **FastAPI** proporciona una documentación de API alternativa (usando ReDoc), a la cual puedes acceder en http://127.0.0.1:8000/redoc: -De la misma manera hay muchas herramientas compatibles. Incluyendo herramientas de generación de código para muchos lenguajes. +De la misma manera, hay muchas herramientas compatibles. Incluyendo herramientas de generación de código para muchos lenguajes. ## Pydantic -Toda la validación de datos es realizada tras bastidores por Pydantic, así que obtienes todos sus beneficios. Así sabes que estás en buenas manos. +Toda la validación de datos se realiza internamente con Pydantic, así que obtienes todos los beneficios de esta. Y sabes que estás en buenas manos. -Puedes usar las mismas declaraciones de tipos con `str`, `float`, `bool` y otros tipos de datos más complejos. +Puedes usar las mismas declaraciones de tipo con `str`, `float`, `bool` y muchos otros tipos de datos complejos. -Exploraremos varios de estos tipos en los próximos capítulos del tutorial. +Varios de estos se exploran en los siguientes capítulos del tutorial. ## El orden importa -Cuando creas *operaciones de path* puedes encontrarte con situaciones en las que tengas un path fijo. +Al crear *path operations*, puedes encontrarte en situaciones donde tienes un path fijo. -Digamos algo como `/users/me` que sea para obtener datos del usuario actual. +Como `/users/me`, imaginemos que es para obtener datos sobre el usuario actual. -... y luego puedes tener el path `/users/{user_id}` para obtener los datos sobre un usuario específico asociados a un ID de usuario. +Y luego también puedes tener un path `/users/{user_id}` para obtener datos sobre un usuario específico por algún ID de usuario. -Porque las *operaciones de path* son evaluadas en orden, tienes que asegurarte de que el path para `/users/me` sea declarado antes que el path para `/users/{user_id}`: +Debido a que las *path operations* se evalúan en orden, necesitas asegurarte de que el path para `/users/me` se declara antes que el de `/users/{user_id}`: {* ../../docs_src/path_params/tutorial003.py hl[6,11] *} -De otra manera el path para `/users/{user_id}` coincidiría también con `/users/me` "pensando" que está recibiendo el parámetro `user_id` con el valor `"me"`. +De lo contrario, el path para `/users/{user_id}` también coincidiría para `/users/me`, "pensando" que está recibiendo un parámetro `user_id` con un valor de `"me"`. + +De manera similar, no puedes redefinir una path operation: + +{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *} + +La primera siempre será utilizada ya que el path coincide primero. ## Valores predefinidos -Si tienes una *operación de path* que recibe un *parámetro de path* pero quieres que los valores posibles del *parámetro de path* sean predefinidos puedes usar un `Enum` estándar de Python. +Si tienes una *path operation* que recibe un *path parameter*, pero quieres que los valores posibles válidos del *path parameter* estén predefinidos, puedes usar un `Enum` estándar de Python. -### Crea una clase `Enum` +### Crear una clase `Enum` -Importa `Enum` y crea una sub-clase que herede desde `str` y desde `Enum`. +Importa `Enum` y crea una subclase que herede de `str` y de `Enum`. -Al heredar desde `str` la documentación de la API podrá saber que los valores deben ser de tipo `string` y podrá mostrarlos correctamente. +Al heredar de `str`, la documentación de la API podrá saber que los valores deben ser de tipo `string` y podrá representarlos correctamente. -Luego crea atributos de clase con valores fijos, que serán los valores disponibles válidos: +Luego crea atributos de clase con valores fijos, que serán los valores válidos disponibles: {* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} /// info | Información -Las Enumerations (o enums) están disponibles en Python desde la versión 3.4. +Las enumeraciones (o enums) están disponibles en Python desde la versión 3.4. /// /// tip | Consejo -Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de modelos de Machine Learning. +Si te estás preguntando, "AlexNet", "ResNet" y "LeNet" son solo nombres de modelos de Machine Learning. /// -### Declara un *parámetro de path* +### Declarar un *path parameter* -Luego, crea un *parámetro de path* con anotaciones de tipos usando la clase enum que creaste (`ModelName`): +Luego crea un *path parameter* con una anotación de tipo usando la clase enum que creaste (`ModelName`): {* ../../docs_src/path_params/tutorial005.py hl[16] *} ### Revisa la documentación -Debido a que los valores disponibles para el *parámetro de path* están predefinidos, la documentación interactiva los puede mostrar bien: +Como los valores disponibles para el *path parameter* están predefinidos, la documentación interactiva puede mostrarlos de manera ordenada: -### Trabajando con los *enumerations* de Python +### Trabajando con *enumeraciones* de Python -El valor del *parámetro de path* será un *enumeration member*. +El valor del *path parameter* será un *miembro* de enumeración. -#### Compara *enumeration members* +#### Comparar *miembros* de enumeraciones -Puedes compararlo con el *enumeration member* en el enum (`ModelName`) que creaste: +Puedes compararlo con el *miembro* de enumeración en tu enum creada `ModelName`: {* ../../docs_src/path_params/tutorial005.py hl[17] *} -#### Obtén el *enumeration value* +#### Obtener el valor de *enumeración* -Puedes obtener el valor exacto (un `str` en este caso) usando `model_name.value`, o en general, `your_enum_member.value`: +Puedes obtener el valor actual (un `str` en este caso) usando `model_name.value`, o en general, `your_enum_member.value`: {* ../../docs_src/path_params/tutorial005.py hl[20] *} /// tip | Consejo -También podrías obtener el valor `"lenet"` con `ModelName.lenet.value`. +También podrías acceder al valor `"lenet"` con `ModelName.lenet.value`. /// -#### Devuelve *enumeration members* +#### Devolver *miembros* de enumeración -Puedes devolver *enum members* desde tu *operación de path* inclusive en un body de JSON anidado (por ejemplo, un `dict`). +Puedes devolver *miembros de enum* desde tu *path operation*, incluso anidados en un cuerpo JSON (por ejemplo, un `dict`). -Ellos serán convertidos a sus valores correspondientes (strings en este caso) antes de devolverlos al cliente: +Serán convertidos a sus valores correspondientes (cadenas en este caso) antes de devolverlos al cliente: {* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} -En tu cliente obtendrás una respuesta en JSON como: +En tu cliente recibirás un response JSON como: ```JSON { @@ -198,53 +206,53 @@ En tu cliente obtendrás una respuesta en JSON como: } ``` -## Parámetros de path parameters que contienen paths +## Parámetros de path conteniendo paths -Digamos que tienes una *operación de path* con un path `/files/{file_path}`. +Imaginemos que tienes una *path operation* con un path `/files/{file_path}`. -Pero necesitas que el mismo `file_path` contenga un path como `home/johndoe/myfile.txt`. +Pero necesitas que `file_path` en sí mismo contenga un *path*, como `home/johndoe/myfile.txt`. Entonces, la URL para ese archivo sería algo como: `/files/home/johndoe/myfile.txt`. ### Soporte de OpenAPI -OpenAPI no soporta una manera de declarar un *parámetro de path* que contenga un path, dado que esto podría llevar a escenarios que son difíciles de probar y definir. +OpenAPI no soporta una manera de declarar un *path parameter* para que contenga un *path* dentro, ya que eso podría llevar a escenarios que son difíciles de probar y definir. -Sin embargo, lo puedes hacer en **FastAPI** usando una de las herramientas internas de Starlette. +Sin embargo, todavía puedes hacerlo en **FastAPI**, usando una de las herramientas internas de Starlette. -La documentación seguirá funcionando, aunque no añadirá ninguna información diciendo que el parámetro debería contener un path. +Y la documentación seguiría funcionando, aunque no agregue ninguna documentación indicando que el parámetro debe contener un path. -### Convertidor de path +### Convertidor de Path -Usando una opción directamente desde Starlette puedes declarar un *parámetro de path* que contenga un path usando una URL como: +Usando una opción directamente de Starlette puedes declarar un *path parameter* conteniendo un *path* usando una URL como: ``` /files/{file_path:path} ``` -En este caso el nombre del parámetro es `file_path` y la última parte, `:path`, le dice que el parámetro debería coincidir con cualquier path. +En este caso, el nombre del parámetro es `file_path`, y la última parte, `:path`, indica que el parámetro debería coincidir con cualquier *path*. -Entonces lo puedes usar con: +Así que, puedes usarlo con: {* ../../docs_src/path_params/tutorial004.py hl[6] *} /// tip | Consejo -Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt` con un slash inicial (`/`). +Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt`, con una barra inclinada (`/`) inicial. -En este caso la URL sería `/files//home/johndoe/myfile.txt` con un slash doble (`//`) entre `files` y `home`. +En ese caso, la URL sería: `/files//home/johndoe/myfile.txt`, con una doble barra inclinada (`//`) entre `files` y `home`. /// -## Repaso +## Resumen -Con **FastAPI**, usando declaraciones de tipo de Python intuitivas y estándares, obtienes: +Con **FastAPI**, al usar declaraciones de tipo estándar de Python, cortas e intuitivas, obtienes: -* Soporte en el editor: chequeo de errores, auto-completado, etc. -* "Parsing" de datos +* Soporte del editor: chequeo de errores, autocompletado, etc. +* "parsing" de datos * Validación de datos -* Anotación de la API y documentación automática +* Anotación de API y documentación automática -Solo tienes que declararlos una vez. +Y solo tienes que declararlos una vez. -Esa es probablemente la principal ventaja visible de **FastAPI** sobre otros frameworks alternativos (aparte del rendimiento puro). +Probablemente esa sea la principal ventaja visible de **FastAPI** en comparación con otros frameworks alternativos (aparte del rendimiento bruto). diff --git a/docs/es/docs/tutorial/query-params.md b/docs/es/docs/tutorial/query-params.md index 8cc4c5671..09c66a545 100644 --- a/docs/es/docs/tutorial/query-params.md +++ b/docs/es/docs/tutorial/query-params.md @@ -1,10 +1,10 @@ -# Parámetros de query +# Parámetros de Query -Cuando declaras otros parámetros de la función que no hacen parte de los parámetros de path estos se interpretan automáticamente como parámetros de "query". +Cuando declaras otros parámetros de función que no son parte de los parámetros de path, son automáticamente interpretados como parámetros de "query". {* ../../docs_src/query_params/tutorial001.py hl[9] *} -El query es el conjunto de pares de key-value que van después del `?` en la URL, separados por caracteres `&`. +La query es el conjunto de pares clave-valor que van después del `?` en una URL, separados por caracteres `&`. Por ejemplo, en la URL: @@ -17,36 +17,36 @@ http://127.0.0.1:8000/items/?skip=0&limit=10 * `skip`: con un valor de `0` * `limit`: con un valor de `10` -Dado que son parte de la URL son strings "naturalmente". +Como son parte de la URL, son "naturalmente" strings. -Pero cuando los declaras con tipos de Python (en el ejemplo arriba, como `int`) son convertidos a ese tipo y son validados con él. +Pero cuando los declaras con tipos de Python (en el ejemplo anterior, como `int`), son convertidos a ese tipo y validados respecto a él. -Todo el proceso que aplicaba a los parámetros de path también aplica a los parámetros de query: +Todo el mismo proceso que se aplica para los parámetros de path también se aplica para los parámetros de query: * Soporte del editor (obviamente) -* "Parsing" de datos +* "Parsing" de datos * Validación de datos * Documentación automática -## Configuraciones por defecto +## Valores por defecto -Como los parámetros de query no están fijos en una parte del path pueden ser opcionales y pueden tener valores por defecto. +Como los parámetros de query no son una parte fija de un path, pueden ser opcionales y pueden tener valores por defecto. -El ejemplo arriba tiene `skip=0` y `limit=10` como los valores por defecto. +En el ejemplo anterior, tienen valores por defecto de `skip=0` y `limit=10`. -Entonces, si vas a la URL: +Entonces, ir a la URL: ``` http://127.0.0.1:8000/items/ ``` -Sería lo mismo que ir a: +sería lo mismo que ir a: ``` http://127.0.0.1:8000/items/?skip=0&limit=10 ``` -Pero, si por ejemplo vas a: +Pero si vas a, por ejemplo: ``` http://127.0.0.1:8000/items/?skip=20 @@ -54,36 +54,26 @@ http://127.0.0.1:8000/items/?skip=20 Los valores de los parámetros en tu función serán: -* `skip=20`: porque lo definiste en la URL -* `limit=10`: porque era el valor por defecto +* `skip=20`: porque lo configuraste en la URL +* `limit=10`: porque ese era el valor por defecto ## Parámetros opcionales -Del mismo modo puedes declarar parámetros de query opcionales definiendo el valor por defecto como `None`: +De la misma manera, puedes declarar parámetros de query opcionales, estableciendo su valor por defecto en `None`: -{* ../../docs_src/query_params/tutorial002.py hl[9] *} - -En este caso el parámetro de la función `q` será opcional y será `None` por defecto. +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} /// check | Revisa -También puedes notar que **FastAPI** es lo suficientemente inteligente para darse cuenta de que el parámetro de path `item_id` es un parámetro de path y que `q` no lo es, y por lo tanto es un parámetro de query. - -/// - -/// note | Nota - -FastAPI sabrá que `q` es opcional por el `= None`. - -El `Union` en `Union[str, None]` no es usado por FastAPI (FastAPI solo usará la parte `str`), pero el `Union[str, None]` le permitirá a tu editor ayudarte a encontrar errores en tu código. +Además, nota que **FastAPI** es lo suficientemente inteligente para notar que el parámetro de path `item_id` es un parámetro de path y `q` no lo es, por lo tanto, es un parámetro de query. /// -## Conversión de tipos de parámetros de query +## Conversión de tipos en parámetros de query -También puedes declarar tipos `bool` y serán convertidos: +También puedes declarar tipos `bool`, y serán convertidos: -{* ../../docs_src/query_params/tutorial003.py hl[9] *} +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} En este caso, si vas a: @@ -115,54 +105,56 @@ o http://127.0.0.1:8000/items/foo?short=yes ``` -o cualquier otra variación (mayúsculas, primera letra en mayúscula, etc.) tu función verá el parámetro `short` con un valor `bool` de `True`. Si no, lo verá como `False`. +o cualquier otra variación (mayúsculas, primera letra en mayúscula, etc.), tu función verá el parámetro `short` con un valor `bool` de `True`. De lo contrario, será `False`. -## Múltiples parámetros de path y query +## Múltiples parámetros de path y de query -Puedes declarar múltiples parámetros de path y parámetros de query al mismo tiempo. **FastAPI** sabe cuál es cuál. +Puedes declarar múltiples parámetros de path y de query al mismo tiempo, **FastAPI** sabe cuál es cuál. -No los tienes que declarar en un orden específico. +Y no tienes que declararlos en un orden específico. Serán detectados por nombre: -{* ../../docs_src/query_params/tutorial004.py hl[8,10] *} +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Parámetros de query requeridos -Cuando declaras un valor por defecto para los parámetros que no son de path (por ahora solo hemos visto parámetros de query), entonces no es requerido. +Cuando declaras un valor por defecto para parámetros que no son de path (por ahora, solo hemos visto parámetros de query), entonces no es requerido. -Si no quieres añadir un valor específico sino solo hacerlo opcional, pon el valor por defecto como `None`. +Si no quieres agregar un valor específico pero solo hacer que sea opcional, establece el valor por defecto como `None`. -Pero cuando quieres hacer que un parámetro de query sea requerido, puedes simplemente no declararle un valor por defecto: +Pero cuando quieres hacer un parámetro de query requerido, simplemente no declares ningún valor por defecto: {* ../../docs_src/query_params/tutorial005.py hl[6:7] *} -Aquí el parámetro de query `needy` es un parámetro de query requerido, del tipo `str`. +Aquí el parámetro de query `needy` es un parámetro de query requerido de tipo `str`. -Si abres tu navegador en una URL como: +Si abres en tu navegador una URL como: ``` http://127.0.0.1:8000/items/foo-item ``` -...sin añadir el parámetro `needy` requerido, verás un error como: +...sin agregar el parámetro requerido `needy`, verás un error como: ```JSON { - "detail": [ - { - "loc": [ - "query", - "needy" - ], - "msg": "field required", - "type": "value_error.missing" - } - ] + "detail": [ + { + "type": "missing", + "loc": [ + "query", + "needy" + ], + "msg": "Field required", + "input": null, + "url": "https://errors.pydantic.dev/2.1/v/missing" + } + ] } ``` -Dado que `needy` es un parámetro requerido necesitarías declararlo en la URL: +Como `needy` es un parámetro requerido, necesitarías establecerlo en la URL: ``` http://127.0.0.1:8000/items/foo-item?needy=sooooneedy @@ -177,11 +169,11 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy } ``` -Por supuesto que también puedes definir algunos parámetros como requeridos, con un valor por defecto y otros completamente opcionales: +Y por supuesto, puedes definir algunos parámetros como requeridos, algunos con un valor por defecto, y algunos enteramente opcionales: -{* ../../docs_src/query_params/tutorial006.py hl[10] *} +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} -En este caso hay 3 parámetros de query: +En este caso, hay 3 parámetros de query: * `needy`, un `str` requerido. * `skip`, un `int` con un valor por defecto de `0`. @@ -189,6 +181,6 @@ En este caso hay 3 parámetros de query: /// tip | Consejo -También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#valores-predefinidos){.internal-link target=_blank}. +También podrías usar `Enum`s de la misma manera que con [Parámetros de Path](path-params.md#predefined-values){.internal-link target=_blank}. /// From a6afa805cde4ddb2a6d79a64a923c8177ff28c90 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 30 Dec 2024 17:47:07 +0000 Subject: [PATCH 603/932] =?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 [skip ci] --- 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 dfd16b030..c62f551e1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Update existing Spanish translations using the new LLM-assisted system using PydanticAI. PR [#13118](https://github.com/fastapi/fastapi/pull/13118) by [@tiangolo](https://github.com/tiangolo). * 🌐 Update Chinese translation for `docs/zh/docs/advanced/security/oauth2-scopes.md`. PR [#13110](https://github.com/fastapi/fastapi/pull/13110) by [@ChenPu2002](https://github.com/ChenPu2002). * 🌐 Add Indonesian translation for `docs/id/docs/tutorial/path-params.md`. PR [#13086](https://github.com/fastapi/fastapi/pull/13086) by [@gerry-sabar](https://github.com/gerry-sabar). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/sql-databases.md`. PR [#13093](https://github.com/fastapi/fastapi/pull/13093) by [@GeumBinLee](https://github.com/GeumBinLee). From fe5b2e491e52a9066506100b7ca9b0e8cb6e0cea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 30 Dec 2024 18:26:57 +0000 Subject: [PATCH 604/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20new=20Spanish=20tr?= =?UTF-8?q?anslations=20for=20all=20docs=20with=20new=20LLM-assisted=20sys?= =?UTF-8?q?tem=20using=20PydanticAI=20(#13122)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: User --- docs/es/docs/advanced/additional-responses.md | 247 +++++ .../es/docs/advanced/advanced-dependencies.md | 65 ++ docs/es/docs/advanced/async-tests.md | 99 ++ docs/es/docs/advanced/behind-a-proxy.md | 361 ++++++++ docs/es/docs/advanced/custom-response.md | 312 +++++++ docs/es/docs/advanced/dataclasses.md | 95 ++ docs/es/docs/advanced/events.md | 165 ++++ docs/es/docs/advanced/generate-clients.md | 261 ++++++ docs/es/docs/advanced/middleware.md | 96 ++ docs/es/docs/advanced/openapi-callbacks.md | 186 ++++ docs/es/docs/advanced/openapi-webhooks.md | 55 ++ docs/es/docs/advanced/response-cookies.md | 51 ++ .../docs/advanced/security/http-basic-auth.md | 107 +++ .../docs/advanced/security/oauth2-scopes.md | 274 ++++++ docs/es/docs/advanced/settings.md | 346 +++++++ docs/es/docs/advanced/sub-applications.md | 67 ++ docs/es/docs/advanced/templates.md | 126 +++ docs/es/docs/advanced/testing-dependencies.md | 53 ++ docs/es/docs/advanced/testing-events.md | 5 + docs/es/docs/advanced/testing-websockets.md | 13 + .../docs/advanced/using-request-directly.md | 56 ++ docs/es/docs/advanced/websockets.md | 186 ++++ docs/es/docs/advanced/wsgi.md | 35 + docs/es/docs/alternatives.md | 485 ++++++++++ docs/es/docs/async.md | 2 +- docs/es/docs/deployment/cloud.md | 18 + docs/es/docs/deployment/concepts.md | 321 +++++++ docs/es/docs/deployment/docker.md | 620 +++++++++++++ docs/es/docs/deployment/https.md | 199 +++++ docs/es/docs/deployment/manually.md | 169 ++++ docs/es/docs/deployment/server-workers.md | 152 ++++ docs/es/docs/environment-variables.md | 298 +++++++ docs/es/docs/fastapi-cli.md | 75 ++ docs/es/docs/help-fastapi.md | 269 ++++++ docs/es/docs/history-design-future.md | 79 ++ docs/es/docs/how-to/conditional-openapi.md | 56 ++ docs/es/docs/how-to/configure-swagger-ui.md | 70 ++ docs/es/docs/how-to/custom-docs-ui-assets.md | 191 ++++ .../docs/how-to/custom-request-and-route.md | 109 +++ docs/es/docs/how-to/extending-openapi.md | 80 ++ docs/es/docs/how-to/general.md | 39 + docs/es/docs/how-to/index.md | 13 + .../docs/how-to/separate-openapi-schemas.md | 104 +++ docs/es/docs/how-to/testing-database.md | 7 + docs/es/docs/tutorial/background-tasks.md | 84 ++ docs/es/docs/tutorial/bigger-applications.md | 554 ++++++++++++ docs/es/docs/tutorial/body-fields.md | 60 ++ docs/es/docs/tutorial/body-multiple-params.md | 173 ++++ docs/es/docs/tutorial/body-nested-models.md | 247 +++++ docs/es/docs/tutorial/body-updates.md | 116 +++ docs/es/docs/tutorial/body.md | 164 ++++ docs/es/docs/tutorial/cookie-param-models.md | 76 ++ docs/es/docs/tutorial/cors.md | 85 ++ docs/es/docs/tutorial/debugging.md | 113 +++ .../dependencies/classes-as-dependencies.md | 288 ++++++ ...pendencies-in-path-operation-decorators.md | 69 ++ .../dependencies/dependencies-with-yield.md | 275 ++++++ .../dependencies/global-dependencies.md | 15 + docs/es/docs/tutorial/dependencies/index.md | 250 ++++++ .../tutorial/dependencies/sub-dependencies.md | 105 +++ docs/es/docs/tutorial/encoder.md | 35 + docs/es/docs/tutorial/extra-data-types.md | 62 ++ docs/es/docs/tutorial/extra-models.md | 222 +++++ docs/es/docs/tutorial/handling-errors.md | 255 ++++++ docs/es/docs/tutorial/header-param-models.md | 56 ++ docs/es/docs/tutorial/header-params.md | 91 ++ docs/es/docs/tutorial/metadata.md | 120 +++ docs/es/docs/tutorial/middleware.md | 72 ++ .../tutorial/path-operation-configuration.md | 107 +++ .../path-params-numeric-validations.md | 164 ++++ docs/es/docs/tutorial/query-param-models.md | 68 ++ .../tutorial/query-params-str-validations.md | 515 +++++++++++ docs/es/docs/tutorial/request-files.md | 176 ++++ docs/es/docs/tutorial/request-form-models.md | 78 ++ .../docs/tutorial/request-forms-and-files.md | 41 + docs/es/docs/tutorial/request-forms.md | 73 ++ docs/es/docs/tutorial/response-model.md | 357 ++++++++ docs/es/docs/tutorial/response-status-code.md | 101 +++ docs/es/docs/tutorial/schema-extra-example.md | 224 +++++ docs/es/docs/tutorial/security/first-steps.md | 203 +++++ .../tutorial/security/get-current-user.md | 103 +++ docs/es/docs/tutorial/security/index.md | 105 +++ docs/es/docs/tutorial/security/oauth2-jwt.md | 273 ++++++ .../docs/tutorial/security/simple-oauth2.md | 289 ++++++ docs/es/docs/tutorial/sql-databases.md | 360 ++++++++ docs/es/docs/tutorial/static-files.md | 40 + docs/es/docs/tutorial/testing.md | 240 +++++ docs/es/docs/virtual-environments.md | 842 ++++++++++++++++++ 88 files changed, 14562 insertions(+), 1 deletion(-) create mode 100644 docs/es/docs/advanced/additional-responses.md create mode 100644 docs/es/docs/advanced/advanced-dependencies.md create mode 100644 docs/es/docs/advanced/async-tests.md create mode 100644 docs/es/docs/advanced/behind-a-proxy.md create mode 100644 docs/es/docs/advanced/custom-response.md create mode 100644 docs/es/docs/advanced/dataclasses.md create mode 100644 docs/es/docs/advanced/events.md create mode 100644 docs/es/docs/advanced/generate-clients.md create mode 100644 docs/es/docs/advanced/middleware.md create mode 100644 docs/es/docs/advanced/openapi-callbacks.md create mode 100644 docs/es/docs/advanced/openapi-webhooks.md create mode 100644 docs/es/docs/advanced/response-cookies.md create mode 100644 docs/es/docs/advanced/security/http-basic-auth.md create mode 100644 docs/es/docs/advanced/security/oauth2-scopes.md create mode 100644 docs/es/docs/advanced/settings.md create mode 100644 docs/es/docs/advanced/sub-applications.md create mode 100644 docs/es/docs/advanced/templates.md create mode 100644 docs/es/docs/advanced/testing-dependencies.md create mode 100644 docs/es/docs/advanced/testing-events.md create mode 100644 docs/es/docs/advanced/testing-websockets.md create mode 100644 docs/es/docs/advanced/using-request-directly.md create mode 100644 docs/es/docs/advanced/websockets.md create mode 100644 docs/es/docs/advanced/wsgi.md create mode 100644 docs/es/docs/alternatives.md create mode 100644 docs/es/docs/deployment/cloud.md create mode 100644 docs/es/docs/deployment/concepts.md create mode 100644 docs/es/docs/deployment/docker.md create mode 100644 docs/es/docs/deployment/https.md create mode 100644 docs/es/docs/deployment/manually.md create mode 100644 docs/es/docs/deployment/server-workers.md create mode 100644 docs/es/docs/environment-variables.md create mode 100644 docs/es/docs/fastapi-cli.md create mode 100644 docs/es/docs/help-fastapi.md create mode 100644 docs/es/docs/history-design-future.md create mode 100644 docs/es/docs/how-to/conditional-openapi.md create mode 100644 docs/es/docs/how-to/configure-swagger-ui.md create mode 100644 docs/es/docs/how-to/custom-docs-ui-assets.md create mode 100644 docs/es/docs/how-to/custom-request-and-route.md create mode 100644 docs/es/docs/how-to/extending-openapi.md create mode 100644 docs/es/docs/how-to/general.md create mode 100644 docs/es/docs/how-to/index.md create mode 100644 docs/es/docs/how-to/separate-openapi-schemas.md create mode 100644 docs/es/docs/how-to/testing-database.md create mode 100644 docs/es/docs/tutorial/background-tasks.md create mode 100644 docs/es/docs/tutorial/bigger-applications.md create mode 100644 docs/es/docs/tutorial/body-fields.md create mode 100644 docs/es/docs/tutorial/body-multiple-params.md create mode 100644 docs/es/docs/tutorial/body-nested-models.md create mode 100644 docs/es/docs/tutorial/body-updates.md create mode 100644 docs/es/docs/tutorial/body.md create mode 100644 docs/es/docs/tutorial/cookie-param-models.md create mode 100644 docs/es/docs/tutorial/cors.md create mode 100644 docs/es/docs/tutorial/debugging.md create mode 100644 docs/es/docs/tutorial/dependencies/classes-as-dependencies.md create mode 100644 docs/es/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md create mode 100644 docs/es/docs/tutorial/dependencies/dependencies-with-yield.md create mode 100644 docs/es/docs/tutorial/dependencies/global-dependencies.md create mode 100644 docs/es/docs/tutorial/dependencies/index.md create mode 100644 docs/es/docs/tutorial/dependencies/sub-dependencies.md create mode 100644 docs/es/docs/tutorial/encoder.md create mode 100644 docs/es/docs/tutorial/extra-data-types.md create mode 100644 docs/es/docs/tutorial/extra-models.md create mode 100644 docs/es/docs/tutorial/handling-errors.md create mode 100644 docs/es/docs/tutorial/header-param-models.md create mode 100644 docs/es/docs/tutorial/header-params.md create mode 100644 docs/es/docs/tutorial/metadata.md create mode 100644 docs/es/docs/tutorial/middleware.md create mode 100644 docs/es/docs/tutorial/path-operation-configuration.md create mode 100644 docs/es/docs/tutorial/path-params-numeric-validations.md create mode 100644 docs/es/docs/tutorial/query-param-models.md create mode 100644 docs/es/docs/tutorial/query-params-str-validations.md create mode 100644 docs/es/docs/tutorial/request-files.md create mode 100644 docs/es/docs/tutorial/request-form-models.md create mode 100644 docs/es/docs/tutorial/request-forms-and-files.md create mode 100644 docs/es/docs/tutorial/request-forms.md create mode 100644 docs/es/docs/tutorial/response-model.md create mode 100644 docs/es/docs/tutorial/response-status-code.md create mode 100644 docs/es/docs/tutorial/schema-extra-example.md create mode 100644 docs/es/docs/tutorial/security/first-steps.md create mode 100644 docs/es/docs/tutorial/security/get-current-user.md create mode 100644 docs/es/docs/tutorial/security/index.md create mode 100644 docs/es/docs/tutorial/security/oauth2-jwt.md create mode 100644 docs/es/docs/tutorial/security/simple-oauth2.md create mode 100644 docs/es/docs/tutorial/sql-databases.md create mode 100644 docs/es/docs/tutorial/static-files.md create mode 100644 docs/es/docs/tutorial/testing.md create mode 100644 docs/es/docs/virtual-environments.md diff --git a/docs/es/docs/advanced/additional-responses.md b/docs/es/docs/advanced/additional-responses.md new file mode 100644 index 000000000..7788bccd9 --- /dev/null +++ b/docs/es/docs/advanced/additional-responses.md @@ -0,0 +1,247 @@ +# Responses Adicionales en OpenAPI + +/// warning | Advertencia + +Este es un tema bastante avanzado. + +Si estás comenzando con **FastAPI**, puede que no lo necesites. + +/// + +Puedes declarar responses adicionales, con códigos de estado adicionales, media types, descripciones, etc. + +Esos responses adicionales se incluirán en el esquema de OpenAPI, por lo que también aparecerán en la documentación de la API. + +Pero para esos responses adicionales tienes que asegurarte de devolver un `Response` como `JSONResponse` directamente, con tu código de estado y contenido. + +## Response Adicional con `model` + +Puedes pasar a tus *decoradores de path operation* un parámetro `responses`. + +Recibe un `dict`: las claves son los códigos de estado para cada response (como `200`), y los valores son otros `dict`s con la información para cada uno de ellos. + +Cada uno de esos `dict`s de response puede tener una clave `model`, conteniendo un modelo de Pydantic, así como `response_model`. + +**FastAPI** tomará ese modelo, generará su JSON Schema y lo incluirá en el lugar correcto en OpenAPI. + +Por ejemplo, para declarar otro response con un código de estado `404` y un modelo Pydantic `Message`, puedes escribir: + +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} + +/// note | Nota + +Ten en cuenta que debes devolver el `JSONResponse` directamente. + +/// + +/// info | Información + +La clave `model` no es parte de OpenAPI. + +**FastAPI** tomará el modelo de Pydantic de allí, generará el JSON Schema y lo colocará en el lugar correcto. + +El lugar correcto es: + +* En la clave `content`, que tiene como valor otro objeto JSON (`dict`) que contiene: + * Una clave con el media type, por ejemplo, `application/json`, que contiene como valor otro objeto JSON, que contiene: + * Una clave `schema`, que tiene como valor el JSON Schema del modelo, aquí es el lugar correcto. + * **FastAPI** agrega una referencia aquí a los JSON Schemas globales en otro lugar de tu OpenAPI en lugar de incluirlo directamente. De este modo, otras aplicaciones y clientes pueden usar esos JSON Schemas directamente, proporcionar mejores herramientas de generación de código, etc. + +/// + +Los responses generadas en el OpenAPI para esta *path operation* serán: + +```JSON hl_lines="3-12" +{ + "responses": { + "404": { + "description": "Additional Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } +} +``` + +Los esquemas se referencian a otro lugar dentro del esquema de OpenAPI: + +```JSON hl_lines="4-16" +{ + "components": { + "schemas": { + "Message": { + "title": "Message", + "required": [ + "message" + ], + "type": "object", + "properties": { + "message": { + "title": "Message", + "type": "string" + } + } + }, + "Item": { + "title": "Item", + "required": [ + "id", + "value" + ], + "type": "object", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "value": { + "title": "Value", + "type": "string" + } + } + }, + "ValidationError": { + "title": "ValidationError", + "required": [ + "loc", + "msg", + "type" + ], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "type": "string" + } + }, + "msg": { + "title": "Message", + "type": "string" + }, + "type": { + "title": "Error Type", + "type": "string" + } + } + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": { + "$ref": "#/components/schemas/ValidationError" + } + } + } + } + } + } +} +``` + +## Media types adicionales para el response principal + +Puedes usar este mismo parámetro `responses` para agregar diferentes media type para el mismo response principal. + +Por ejemplo, puedes agregar un media type adicional de `image/png`, declarando que tu *path operation* puede devolver un objeto JSON (con media type `application/json`) o una imagen PNG: + +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} + +/// note | Nota + +Nota que debes devolver la imagen usando un `FileResponse` directamente. + +/// + +/// info | Información + +A menos que especifiques un media type diferente explícitamente en tu parámetro `responses`, FastAPI asumirá que el response tiene el mismo media type que la clase de response principal (por defecto `application/json`). + +Pero si has especificado una clase de response personalizada con `None` como su media type, FastAPI usará `application/json` para cualquier response adicional que tenga un modelo asociado. + +/// + +## Combinando información + +También puedes combinar información de response de múltiples lugares, incluyendo los parámetros `response_model`, `status_code`, y `responses`. + +Puedes declarar un `response_model`, usando el código de estado predeterminado `200` (o uno personalizado si lo necesitas), y luego declarar información adicional para ese mismo response en `responses`, directamente en el esquema de OpenAPI. + +**FastAPI** manterá la información adicional de `responses` y la combinará con el JSON Schema de tu modelo. + +Por ejemplo, puedes declarar un response con un código de estado `404` que usa un modelo Pydantic y tiene una `description` personalizada. + +Y un response con un código de estado `200` que usa tu `response_model`, pero incluye un `example` personalizado: + +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} + +Todo se combinará e incluirá en tu OpenAPI, y se mostrará en la documentación de la API: + + + +## Combina responses predefinidos y personalizados + +Es posible que desees tener algunos responses predefinidos que se apliquen a muchas *path operations*, pero que quieras combinarlos con responses personalizados necesarios por cada *path operation*. + +Para esos casos, puedes usar la técnica de Python de "desempaquetar" un `dict` con `**dict_to_unpack`: + +```Python +old_dict = { + "old key": "old value", + "second old key": "second old value", +} +new_dict = {**old_dict, "new key": "new value"} +``` + +Aquí, `new_dict` contendrá todos los pares clave-valor de `old_dict` más el nuevo par clave-valor: + +```Python +{ + "old key": "old value", + "second old key": "second old value", + "new key": "new value", +} +``` + +Puedes usar esa técnica para reutilizar algunos responses predefinidos en tus *path operations* y combinarlos con otros personalizados adicionales. + +Por ejemplo: + +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} + +## Más información sobre responses OpenAPI + +Para ver exactamente qué puedes incluir en los responses, puedes revisar estas secciones en la especificación OpenAPI: + +* Objeto de Responses de OpenAPI, incluye el `Response Object`. +* Objeto de Response de OpenAPI, puedes incluir cualquier cosa de esto directamente en cada response dentro de tu parámetro `responses`. Incluyendo `description`, `headers`, `content` (dentro de este es que declaras diferentes media types y JSON Schemas), y `links`. diff --git a/docs/es/docs/advanced/advanced-dependencies.md b/docs/es/docs/advanced/advanced-dependencies.md new file mode 100644 index 000000000..dd3c63a37 --- /dev/null +++ b/docs/es/docs/advanced/advanced-dependencies.md @@ -0,0 +1,65 @@ +# Dependencias Avanzadas + +## Dependencias con parámetros + +Todas las dependencias que hemos visto son una función o clase fija. + +Pero podría haber casos en los que quieras poder establecer parámetros en la dependencia, sin tener que declarar muchas funciones o clases diferentes. + +Imaginemos que queremos tener una dependencia que revise si el parámetro de query `q` contiene algún contenido fijo. + +Pero queremos poder parametrizar ese contenido fijo. + +## Una *instance* "callable" + +En Python hay una forma de hacer que una instance de una clase sea un "callable". + +No la clase en sí (que ya es un callable), sino una instance de esa clase. + +Para hacer eso, declaramos un método `__call__`: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *} + +En este caso, este `__call__` es lo que **FastAPI** usará para comprobar parámetros adicionales y sub-dependencias, y es lo que llamará para pasar un valor al parámetro en tu *path operation function* más adelante. + +## Parametrizar la instance + +Y ahora, podemos usar `__init__` para declarar los parámetros de la instance que podemos usar para "parametrizar" la dependencia: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *} + +En este caso, **FastAPI** nunca tocará ni se preocupará por `__init__`, lo usaremos directamente en nuestro código. + +## Crear una instance + +Podríamos crear una instance de esta clase con: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *} + +Y de esa manera podemos "parametrizar" nuestra dependencia, que ahora tiene `"bar"` dentro de ella, como el atributo `checker.fixed_content`. + +## Usar la instance como una dependencia + +Luego, podríamos usar este `checker` en un `Depends(checker)`, en lugar de `Depends(FixedContentQueryChecker)`, porque la dependencia es la instance, `checker`, no la clase en sí. + +Y al resolver la dependencia, **FastAPI** llamará a este `checker` así: + +```Python +checker(q="somequery") +``` + +...y pasará lo que eso retorne como el valor de la dependencia en nuestra *path operation function* como el parámetro `fixed_content_included`: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *} + +/// tip | Consejo + +Todo esto podría parecer complicado. Y puede que no esté muy claro cómo es útil aún. + +Estos ejemplos son intencionalmente simples, pero muestran cómo funciona todo. + +En los capítulos sobre seguridad, hay funciones utilitarias que se implementan de esta misma manera. + +Si entendiste todo esto, ya sabes cómo funcionan por debajo esas herramientas de utilidad para seguridad. + +/// diff --git a/docs/es/docs/advanced/async-tests.md b/docs/es/docs/advanced/async-tests.md new file mode 100644 index 000000000..f89db1533 --- /dev/null +++ b/docs/es/docs/advanced/async-tests.md @@ -0,0 +1,99 @@ +# Tests Asíncronos + +Ya has visto cómo probar tus aplicaciones de **FastAPI** usando el `TestClient` proporcionado. Hasta ahora, solo has visto cómo escribir tests sincrónicos, sin usar funciones `async`. + +Poder usar funciones asíncronas en tus tests puede ser útil, por ejemplo, cuando consultas tu base de datos de forma asíncrona. Imagina que quieres probar el envío de requests a tu aplicación FastAPI y luego verificar que tu backend escribió exitosamente los datos correctos en la base de datos, mientras usas un paquete de base de datos asíncrono. + +Veamos cómo podemos hacer que esto funcione. + +## pytest.mark.anyio + +Si queremos llamar funciones asíncronas en nuestros tests, nuestras funciones de test tienen que ser asíncronas. AnyIO proporciona un plugin útil para esto, que nos permite especificar que algunas funciones de test deben ser llamadas de manera asíncrona. + +## HTTPX + +Incluso si tu aplicación de **FastAPI** usa funciones `def` normales en lugar de `async def`, sigue siendo una aplicación `async` por debajo. + +El `TestClient` hace algo de magia interna para llamar a la aplicación FastAPI asíncrona en tus funciones de test `def` normales, usando pytest estándar. Pero esa magia ya no funciona cuando lo usamos dentro de funciones asíncronas. Al ejecutar nuestros tests de manera asíncrona, ya no podemos usar el `TestClient` dentro de nuestras funciones de test. + +El `TestClient` está basado en HTTPX, y afortunadamente, podemos usarlo directamente para probar la API. + +## Ejemplo + +Para un ejemplo simple, consideremos una estructura de archivos similar a la descrita en [Aplicaciones Más Grandes](../tutorial/bigger-applications.md){.internal-link target=_blank} y [Testing](../tutorial/testing.md){.internal-link target=_blank}: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +El archivo `main.py` tendría: + +{* ../../docs_src/async_tests/main.py *} + +El archivo `test_main.py` tendría los tests para `main.py`, podría verse así ahora: + +{* ../../docs_src/async_tests/test_main.py *} + +## Ejecútalo + +Puedes ejecutar tus tests como de costumbre vía: + +
+ +```console +$ pytest + +---> 100% +``` + +
+ +## En Detalle + +El marcador `@pytest.mark.anyio` le dice a pytest que esta función de test debe ser llamada asíncronamente: + +{* ../../docs_src/async_tests/test_main.py hl[7] *} + +/// tip | Consejo + +Note que la función de test ahora es `async def` en lugar de solo `def` como antes al usar el `TestClient`. + +/// + +Luego podemos crear un `AsyncClient` con la app y enviar requests asíncronos a ella, usando `await`. + +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} + +Esto es equivalente a: + +```Python +response = client.get('/') +``` + +...que usábamos para hacer nuestros requests con el `TestClient`. + +/// tip | Consejo + +Nota que estamos usando async/await con el nuevo `AsyncClient`: el request es asíncrono. + +/// + +/// warning | Advertencia + +Si tu aplicación depende de eventos de lifespan, el `AsyncClient` no activará estos eventos. Para asegurarte de que se activen, usa `LifespanManager` de florimondmanca/asgi-lifespan. + +/// + +## Otras Llamadas a Funciones Asíncronas + +Al ser la función de test asíncrona, ahora también puedes llamar (y `await`) otras funciones `async` además de enviar requests a tu aplicación FastAPI en tus tests, exactamente como las llamarías en cualquier otro lugar de tu código. + +/// tip | Consejo + +Si encuentras un `RuntimeError: Task attached to a different loop` al integrar llamadas a funciones asíncronas en tus tests (por ejemplo, cuando usas MotorClient de MongoDB), recuerda crear instances de objetos que necesiten un loop de eventos solo dentro de funciones async, por ejemplo, en un callback `'@app.on_event("startup")`. + +/// diff --git a/docs/es/docs/advanced/behind-a-proxy.md b/docs/es/docs/advanced/behind-a-proxy.md new file mode 100644 index 000000000..8c590cbe8 --- /dev/null +++ b/docs/es/docs/advanced/behind-a-proxy.md @@ -0,0 +1,361 @@ +# Detrás de un Proxy + +En algunas situaciones, podrías necesitar usar un **proxy** como Traefik o Nginx con una configuración que añade un prefijo de path extra que no es visto por tu aplicación. + +En estos casos, puedes usar `root_path` para configurar tu aplicación. + +El `root_path` es un mecanismo proporcionado por la especificación ASGI (en la que está construido FastAPI, a través de Starlette). + +El `root_path` se usa para manejar estos casos específicos. + +Y también se usa internamente al montar subaplicaciones. + +## Proxy con un prefijo de path eliminado + +Tener un proxy con un prefijo de path eliminado, en este caso, significa que podrías declarar un path en `/app` en tu código, pero luego añades una capa encima (el proxy) que situaría tu aplicación **FastAPI** bajo un path como `/api/v1`. + +En este caso, el path original `/app` realmente sería servido en `/api/v1/app`. + +Aunque todo tu código esté escrito asumiendo que solo existe `/app`. + +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[6] *} + +Y el proxy estaría **"eliminando"** el **prefijo del path** sobre la marcha antes de transmitir el request al servidor de aplicaciones (probablemente Uvicorn a través de FastAPI CLI), manteniendo a tu aplicación convencida de que está siendo servida en `/app`, así que no tienes que actualizar todo tu código para incluir el prefijo `/api/v1`. + +Hasta aquí, todo funcionaría normalmente. + +Pero luego, cuando abres la UI integrada de los docs (el frontend), esperaría obtener el esquema de OpenAPI en `/openapi.json`, en lugar de `/api/v1/openapi.json`. + +Entonces, el frontend (que se ejecuta en el navegador) trataría de alcanzar `/openapi.json` y no podría obtener el esquema de OpenAPI. + +Porque tenemos un proxy con un prefijo de path de `/api/v1` para nuestra aplicación, el frontend necesita obtener el esquema de OpenAPI en `/api/v1/openapi.json`. + +```mermaid +graph LR + +browser("Navegador") +proxy["Proxy en http://0.0.0.0:9999/api/v1/app"] +server["Servidor en http://127.0.0.1:8000/app"] + +browser --> proxy +proxy --> server +``` + +/// tip | Consejo + +La IP `0.0.0.0` se usa comúnmente para indicar que el programa escucha en todas las IPs disponibles en esa máquina/servidor. + +/// + +La UI de los docs también necesitaría el esquema de OpenAPI para declarar que este API `servidor` se encuentra en `/api/v1` (detrás del proxy). Por ejemplo: + +```JSON hl_lines="4-8" +{ + "openapi": "3.1.0", + // Más cosas aquí + "servers": [ + { + "url": "/api/v1" + } + ], + "paths": { + // Más cosas aquí + } +} +``` + +En este ejemplo, el "Proxy" podría ser algo como **Traefik**. Y el servidor sería algo como FastAPI CLI con **Uvicorn**, ejecutando tu aplicación de FastAPI. + +### Proporcionando el `root_path` + +Para lograr esto, puedes usar la opción de línea de comandos `--root-path` como: + +
+ +```console +$ fastapi run main.py --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Si usas Hypercorn, también tiene la opción `--root-path`. + +/// note | Detalles Técnicos + +La especificación ASGI define un `root_path` para este caso de uso. + +Y la opción de línea de comandos `--root-path` proporciona ese `root_path`. + +/// + +### Revisar el `root_path` actual + +Puedes obtener el `root_path` actual utilizado por tu aplicación para cada request, es parte del diccionario `scope` (que es parte de la especificación ASGI). + +Aquí lo estamos incluyendo en el mensaje solo con fines de demostración. + +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *} + +Luego, si inicias Uvicorn con: + +
+ +```console +$ fastapi run main.py --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +El response sería algo como: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +### Configurar el `root_path` en la app de FastAPI + +Alternativamente, si no tienes una forma de proporcionar una opción de línea de comandos como `--root-path` o su equivalente, puedes configurar el parámetro `root_path` al crear tu app de FastAPI: + +{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *} + +Pasar el `root_path` a `FastAPI` sería el equivalente a pasar la opción de línea de comandos `--root-path` a Uvicorn o Hypercorn. + +### Acerca de `root_path` + +Ten en cuenta que el servidor (Uvicorn) no usará ese `root_path` para nada, a excepción de pasárselo a la app. + +Pero si vas con tu navegador a http://127.0.0.1:8000/app verás el response normal: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +Así que no se esperará que sea accedido en `http://127.0.0.1:8000/api/v1/app`. + +Uvicorn esperará que el proxy acceda a Uvicorn en `http://127.0.0.1:8000/app`, y luego será responsabilidad del proxy añadir el prefijo extra `/api/v1` encima. + +## Sobre proxies con un prefijo de path eliminado + +Ten en cuenta que un proxy con prefijo de path eliminado es solo una de las formas de configurarlo. + +Probablemente en muchos casos, el valor predeterminado será que el proxy no tenga un prefijo de path eliminado. + +En un caso así (sin un prefijo de path eliminado), el proxy escucharía algo como `https://myawesomeapp.com`, y luego si el navegador va a `https://myawesomeapp.com/api/v1/app` y tu servidor (por ejemplo, Uvicorn) escucha en `http://127.0.0.1:8000`, el proxy (sin un prefijo de path eliminado) accedería a Uvicorn en el mismo path: `http://127.0.0.1:8000/api/v1/app`. + +## Probando localmente con Traefik + +Puedes ejecutar fácilmente el experimento localmente con un prefijo de path eliminado usando Traefik. + +Descarga Traefik, es un archivo binario único, puedes extraer el archivo comprimido y ejecutarlo directamente desde la terminal. + +Luego crea un archivo `traefik.toml` con: + +```TOML hl_lines="3" +[entryPoints] + [entryPoints.http] + address = ":9999" + +[providers] + [providers.file] + filename = "routes.toml" +``` + +Esto le dice a Traefik que escuche en el puerto 9999 y que use otro archivo `routes.toml`. + +/// tip | Consejo + +Estamos utilizando el puerto 9999 en lugar del puerto HTTP estándar 80 para que no tengas que ejecutarlo con privilegios de administrador (`sudo`). + +/// + +Ahora crea ese otro archivo `routes.toml`: + +```TOML hl_lines="5 12 20" +[http] + [http.middlewares] + + [http.middlewares.api-stripprefix.stripPrefix] + prefixes = ["/api/v1"] + + [http.routers] + + [http.routers.app-http] + entryPoints = ["http"] + service = "app" + rule = "PathPrefix(`/api/v1`)" + middlewares = ["api-stripprefix"] + + [http.services] + + [http.services.app] + [http.services.app.loadBalancer] + [[http.services.app.loadBalancer.servers]] + url = "http://127.0.0.1:8000" +``` + +Este archivo configura Traefik para usar el prefijo de path `/api/v1`. + +Y luego Traefik redireccionará sus requests a tu Uvicorn ejecutándose en `http://127.0.0.1:8000`. + +Ahora inicia Traefik: + +
+ +```console +$ ./traefik --configFile=traefik.toml + +INFO[0000] Configuration loaded from file: /home/user/awesomeapi/traefik.toml +``` + +
+ +Y ahora inicia tu app, utilizando la opción `--root-path`: + +
+ +```console +$ fastapi run main.py --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +### Revisa los responses + +Ahora, si vas a la URL con el puerto para Uvicorn: http://127.0.0.1:8000/app, verás el response normal: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +/// tip | Consejo + +Nota que incluso aunque estés accediendo en `http://127.0.0.1:8000/app`, muestra el `root_path` de `/api/v1`, tomado de la opción `--root-path`. + +/// + +Y ahora abre la URL con el puerto para Traefik, incluyendo el prefijo de path: http://127.0.0.1:9999/api/v1/app. + +Obtenemos el mismo response: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +pero esta vez en la URL con el prefijo de path proporcionado por el proxy: `/api/v1`. + +Por supuesto, la idea aquí es que todos accedan a la app a través del proxy, así que la versión con el prefijo de path `/api/v1` es la "correcta". + +Y la versión sin el prefijo de path (`http://127.0.0.1:8000/app`), proporcionada directamente por Uvicorn, sería exclusivamente para que el _proxy_ (Traefik) la acceda. + +Eso demuestra cómo el Proxy (Traefik) usa el prefijo de path y cómo el servidor (Uvicorn) usa el `root_path` de la opción `--root-path`. + +### Revisa la UI de los docs + +Pero aquí está la parte divertida. ✨ + +La forma "oficial" de acceder a la app sería a través del proxy con el prefijo de path que definimos. Así que, como esperaríamos, si intentas usar la UI de los docs servida por Uvicorn directamente, sin el prefijo de path en la URL, no funcionará, porque espera ser accedida a través del proxy. + +Puedes verificarlo en http://127.0.0.1:8000/docs: + + + +Pero si accedemos a la UI de los docs en la URL "oficial" usando el proxy con puerto `9999`, en `/api/v1/docs`, ¡funciona correctamente! 🎉 + +Puedes verificarlo en http://127.0.0.1:9999/api/v1/docs: + + + +Justo como queríamos. ✔️ + +Esto es porque FastAPI usa este `root_path` para crear el `server` por defecto en OpenAPI con la URL proporcionada por `root_path`. + +## Servidores adicionales + +/// warning | Advertencia + +Este es un caso de uso más avanzado. Siéntete libre de omitirlo. + +/// + +Por defecto, **FastAPI** creará un `server` en el esquema de OpenAPI con la URL para el `root_path`. + +Pero también puedes proporcionar otros `servers` alternativos, por ejemplo, si deseas que *la misma* UI de los docs interactúe con un entorno de pruebas y de producción. + +Si pasas una lista personalizada de `servers` y hay un `root_path` (porque tu API existe detrás de un proxy), **FastAPI** insertará un "server" con este `root_path` al comienzo de la lista. + +Por ejemplo: + +{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *} + +Generará un esquema de OpenAPI como: + +```JSON hl_lines="5-7" +{ + "openapi": "3.1.0", + // Más cosas aquí + "servers": [ + { + "url": "/api/v1" + }, + { + "url": "https://stag.example.com", + "description": "Entorno de pruebas" + }, + { + "url": "https://prod.example.com", + "description": "Entorno de producción" + } + ], + "paths": { + // Más cosas aquí + } +} +``` + +/// tip | Consejo + +Observa el server auto-generado con un valor `url` de `/api/v1`, tomado del `root_path`. + +/// + +En la UI de los docs en http://127.0.0.1:9999/api/v1/docs se vería como: + + + +/// tip | Consejo + +La UI de los docs interactuará con el server que selecciones. + +/// + +### Desactivar el server automático de `root_path` + +Si no quieres que **FastAPI** incluya un server automático usando el `root_path`, puedes usar el parámetro `root_path_in_servers=False`: + +{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *} + +y entonces no lo incluirá en el esquema de OpenAPI. + +## Montando una sub-aplicación + +Si necesitas montar una sub-aplicación (como se describe en [Aplicaciones secundarias - Monturas](sub-applications.md){.internal-link target=_blank}) mientras usas un proxy con `root_path`, puedes hacerlo normalmente, como esperarías. + +FastAPI usará internamente el `root_path` de manera inteligente, así que simplemente funcionará. ✨ diff --git a/docs/es/docs/advanced/custom-response.md b/docs/es/docs/advanced/custom-response.md new file mode 100644 index 000000000..f7bd81bcc --- /dev/null +++ b/docs/es/docs/advanced/custom-response.md @@ -0,0 +1,312 @@ +# Response Personalizado - HTML, Stream, Archivo, otros + +Por defecto, **FastAPI** devolverá los responses usando `JSONResponse`. + +Puedes sobrescribirlo devolviendo un `Response` directamente como se ve en [Devolver una Response directamente](response-directly.md){.internal-link target=_blank}. + +Pero si devuelves un `Response` directamente (o cualquier subclase, como `JSONResponse`), los datos no se convertirán automáticamente (incluso si declaras un `response_model`), y la documentación no se generará automáticamente (por ejemplo, incluyendo el "media type" específico, en el HTTP header `Content-Type` como parte del OpenAPI generado). + +Pero también puedes declarar el `Response` que quieres usar (por ejemplo, cualquier subclase de `Response`), en el *path operation decorator* usando el parámetro `response_class`. + +Los contenidos que devuelvas desde tu *path operation function* se colocarán dentro de esa `Response`. + +Y si ese `Response` tiene un media type JSON (`application/json`), como es el caso con `JSONResponse` y `UJSONResponse`, los datos que devuelvas se convertirán automáticamente (y serán filtrados) con cualquier `response_model` de Pydantic que hayas declarado en el *path operation decorator*. + +/// note | Nota + +Si usas una clase de response sin media type, FastAPI esperará que tu response no tenga contenido, por lo que no documentará el formato del response en su OpenAPI generado. + +/// + +## Usa `ORJSONResponse` + +Por ejemplo, si estás exprimendo el rendimiento, puedes instalar y usar `orjson` y establecer el response como `ORJSONResponse`. + +Importa la clase `Response` (sub-clase) que quieras usar y declárala en el *path operation decorator*. + +Para responses grandes, devolver una `Response` directamente es mucho más rápido que devolver un diccionario. + +Esto se debe a que, por defecto, FastAPI inspeccionará cada elemento dentro y se asegurará de que sea serializable como JSON, usando el mismo [Codificador Compatible con JSON](../tutorial/encoder.md){.internal-link target=_blank} explicado en el tutorial. Esto es lo que te permite devolver **objetos arbitrarios**, por ejemplo, modelos de bases de datos. + +Pero si estás seguro de que el contenido que estás devolviendo es **serializable con JSON**, puedes pasarlo directamente a la clase de response y evitar la sobrecarga extra que FastAPI tendría al pasar tu contenido de retorno a través de `jsonable_encoder` antes de pasarlo a la clase de response. + +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} + +/// info | Información + +El parámetro `response_class` también se utilizará para definir el "media type" del response. + +En este caso, el HTTP header `Content-Type` se establecerá en `application/json`. + +Y se documentará así en OpenAPI. + +/// + +/// tip | Consejo + +El `ORJSONResponse` solo está disponible en FastAPI, no en Starlette. + +/// + +## Response HTML + +Para devolver un response con HTML directamente desde **FastAPI**, usa `HTMLResponse`. + +* Importa `HTMLResponse`. +* Pasa `HTMLResponse` como parámetro `response_class` de tu *path operation decorator*. + +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} + +/// info | Información + +El parámetro `response_class` también se utilizará para definir el "media type" del response. + +En este caso, el HTTP header `Content-Type` se establecerá en `text/html`. + +Y se documentará así en OpenAPI. + +/// + +### Devuelve una `Response` + +Como se ve en [Devolver una Response directamente](response-directly.md){.internal-link target=_blank}, también puedes sobrescribir el response directamente en tu *path operation*, devolviéndolo. + +El mismo ejemplo de arriba, devolviendo una `HTMLResponse`, podría verse así: + +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} + +/// warning | Advertencia + +Una `Response` devuelta directamente por tu *path operation function* no se documentará en OpenAPI (por ejemplo, el `Content-Type` no se documentará) y no será visible en la documentación interactiva automática. + +/// + +/// info | Información + +Por supuesto, el `Content-Type` header real, el código de estado, etc., provendrán del objeto `Response` que devolviste. + +/// + +### Documenta en OpenAPI y sobrescribe `Response` + +Si quieres sobrescribir el response desde dentro de la función pero al mismo tiempo documentar el "media type" en OpenAPI, puedes usar el parámetro `response_class` Y devolver un objeto `Response`. + +El `response_class` solo se usará para documentar el OpenAPI *path operation*, pero tu `Response` se usará tal cual. + +#### Devuelve un `HTMLResponse` directamente + +Por ejemplo, podría ser algo así: + +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} + +En este ejemplo, la función `generate_html_response()` ya genera y devuelve una `Response` en lugar de devolver el HTML en un `str`. + +Al devolver el resultado de llamar a `generate_html_response()`, ya estás devolviendo una `Response` que sobrescribirá el comportamiento predeterminado de **FastAPI**. + +Pero como pasaste `HTMLResponse` en el `response_class` también, **FastAPI** sabrá cómo documentarlo en OpenAPI y la documentación interactiva como HTML con `text/html`: + + + +## Responses disponibles + +Aquí hay algunos de los responses disponibles. + +Ten en cuenta que puedes usar `Response` para devolver cualquier otra cosa, o incluso crear una sub-clase personalizada. + +/// note | Nota Técnica + +También podrías usar `from starlette.responses import HTMLResponse`. + +**FastAPI** proporciona los mismos `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette. + +/// + +### `Response` + +La clase principal `Response`, todos los otros responses heredan de ella. + +Puedes devolverla directamente. + +Acepta los siguientes parámetros: + +* `content` - Un `str` o `bytes`. +* `status_code` - Un código de estado HTTP `int`. +* `headers` - Un `dict` de strings. +* `media_type` - Un `str` que da el media type. Por ejemplo, `"text/html"`. + +FastAPI (de hecho Starlette) incluirá automáticamente un header Content-Length. También incluirá un header Content-Type, basado en el `media_type` y añadiendo un conjunto de caracteres para tipos de texto. + +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} + +### `HTMLResponse` + +Toma algún texto o bytes y devuelve un response HTML, como leíste arriba. + +### `PlainTextResponse` + +Toma algún texto o bytes y devuelve un response de texto plano. + +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} + +### `JSONResponse` + +Toma algunos datos y devuelve un response codificado como `application/json`. + +Este es el response predeterminado usado en **FastAPI**, como leíste arriba. + +### `ORJSONResponse` + +Un response JSON rápido alternativo usando `orjson`, como leíste arriba. + +/// info | Información + +Esto requiere instalar `orjson`, por ejemplo, con `pip install orjson`. + +/// + +### `UJSONResponse` + +Un response JSON alternativo usando `ujson`. + +/// info | Información + +Esto requiere instalar `ujson`, por ejemplo, con `pip install ujson`. + +/// + +/// warning | Advertencia + +`ujson` es menos cuidadoso que la implementación integrada de Python en cómo maneja algunos casos extremos. + +/// + +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} + +/// tip | Consejo + +Es posible que `ORJSONResponse` sea una alternativa más rápida. + +/// + +### `RedirectResponse` + +Devuelve una redirección HTTP. Usa un código de estado 307 (Redirección Temporal) por defecto. + +Puedes devolver un `RedirectResponse` directamente: + +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} + +--- + +O puedes usarlo en el parámetro `response_class`: + +{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *} + +Si haces eso, entonces puedes devolver la URL directamente desde tu *path operation function*. + +En este caso, el `status_code` utilizado será el predeterminado para `RedirectResponse`, que es `307`. + +--- + +También puedes usar el parámetro `status_code` combinado con el parámetro `response_class`: + +{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *} + +### `StreamingResponse` + +Toma un generador `async` o un generador/iterador normal y transmite el cuerpo del response. + +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} + +#### Usando `StreamingResponse` con objetos similares a archivos + +Si tienes un objeto similar a un archivo (por ejemplo, el objeto devuelto por `open()`), puedes crear una función generadora para iterar sobre ese objeto similar a un archivo. + +De esa manera, no tienes que leerlo todo primero en memoria, y puedes pasar esa función generadora al `StreamingResponse`, y devolverlo. + +Esto incluye muchos paquetes para interactuar con almacenamiento en la nube, procesamiento de video y otros. + +{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *} + +1. Esta es la función generadora. Es una "función generadora" porque contiene declaraciones `yield` dentro. +2. Al usar un bloque `with`, nos aseguramos de que el objeto similar a un archivo se cierre después de que la función generadora termine. Así, después de que termina de enviar el response. +3. Este `yield from` le dice a la función que itere sobre esa cosa llamada `file_like`. Y luego, para cada parte iterada, yield esa parte como proveniente de esta función generadora (`iterfile`). + + Entonces, es una función generadora que transfiere el trabajo de "generar" a algo más internamente. + + Al hacerlo de esta manera, podemos ponerlo en un bloque `with`, y de esa manera, asegurarnos de que el objeto similar a un archivo se cierre después de finalizar. + +/// tip | Consejo + +Nota que aquí como estamos usando `open()` estándar que no admite `async` y `await`, declaramos el path operation con `def` normal. + +/// + +### `FileResponse` + +Transmite un archivo asincrónicamente como response. + +Toma un conjunto diferente de argumentos para crear un instance que los otros tipos de response: + +* `path` - La path del archivo para el archivo a transmitir. +* `headers` - Cualquier header personalizado para incluir, como un diccionario. +* `media_type` - Un string que da el media type. Si no se establece, se usará el nombre de archivo o la path para inferir un media type. +* `filename` - Si se establece, se incluirá en el response `Content-Disposition`. + +Los responses de archivos incluirán los headers apropiados `Content-Length`, `Last-Modified` y `ETag`. + +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} + +También puedes usar el parámetro `response_class`: + +{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *} + +En este caso, puedes devolver la path del archivo directamente desde tu *path operation* function. + +## Clase de response personalizada + +Puedes crear tu propia clase de response personalizada, heredando de `Response` y usándola. + +Por ejemplo, digamos que quieres usar `orjson`, pero con algunas configuraciones personalizadas no utilizadas en la clase `ORJSONResponse` incluida. + +Digamos que quieres que devuelva JSON con sangría y formato, por lo que quieres usar la opción de orjson `orjson.OPT_INDENT_2`. + +Podrías crear un `CustomORJSONResponse`. Lo principal que tienes que hacer es crear un método `Response.render(content)` que devuelva el contenido como `bytes`: + +{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *} + +Ahora en lugar de devolver: + +```json +{"message": "Hello World"} +``` + +...este response devolverá: + +```json +{ + "message": "Hello World" +} +``` + +Por supuesto, probablemente encontrarás formas mucho mejores de aprovechar esto que formatear JSON. 😉 + +## Clase de response predeterminada + +Al crear una instance de la clase **FastAPI** o un `APIRouter`, puedes especificar qué clase de response usar por defecto. + +El parámetro que define esto es `default_response_class`. + +En el ejemplo a continuación, **FastAPI** usará `ORJSONResponse` por defecto, en todas las *path operations*, en lugar de `JSONResponse`. + +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} + +/// tip | Consejo + +Todavía puedes sobrescribir `response_class` en *path operations* como antes. + +/// + +## Documentación adicional + +También puedes declarar el media type y muchos otros detalles en OpenAPI usando `responses`: [Responses Adicionales en OpenAPI](additional-responses.md){.internal-link target=_blank}. diff --git a/docs/es/docs/advanced/dataclasses.md b/docs/es/docs/advanced/dataclasses.md new file mode 100644 index 000000000..0ca1fd3b6 --- /dev/null +++ b/docs/es/docs/advanced/dataclasses.md @@ -0,0 +1,95 @@ +# Usando Dataclasses + +FastAPI está construido sobre **Pydantic**, y te he estado mostrando cómo usar modelos de Pydantic para declarar requests y responses. + +Pero FastAPI también soporta el uso de `dataclasses` de la misma manera: + +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} + +Esto sigue siendo soportado gracias a **Pydantic**, ya que tiene soporte interno para `dataclasses`. + +Así que, incluso con el código anterior que no usa Pydantic explícitamente, FastAPI está usando Pydantic para convertir esos dataclasses estándar en su propia versión de dataclasses de Pydantic. + +Y por supuesto, soporta lo mismo: + +* validación de datos +* serialización de datos +* documentación de datos, etc. + +Esto funciona de la misma manera que con los modelos de Pydantic. Y en realidad se logra de la misma manera internamente, utilizando Pydantic. + +/// info | Información + +Ten en cuenta que los dataclasses no pueden hacer todo lo que los modelos de Pydantic pueden hacer. + +Así que, podrías necesitar seguir usando modelos de Pydantic. + +Pero si tienes un montón de dataclasses por ahí, este es un buen truco para usarlos para potenciar una API web usando FastAPI. 🤓 + +/// + +## Dataclasses en `response_model` + +También puedes usar `dataclasses` en el parámetro `response_model`: + +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} + +El dataclass será automáticamente convertido a un dataclass de Pydantic. + +De esta manera, su esquema aparecerá en la interfaz de usuario de la documentación de la API: + + + +## Dataclasses en Estructuras de Datos Anidadas + +También puedes combinar `dataclasses` con otras anotaciones de tipos para crear estructuras de datos anidadas. + +En algunos casos, todavía podrías tener que usar la versión de `dataclasses` de Pydantic. Por ejemplo, si tienes errores con la documentación de la API generada automáticamente. + +En ese caso, simplemente puedes intercambiar los `dataclasses` estándar con `pydantic.dataclasses`, que es un reemplazo directo: + +{* ../../docs_src/dataclasses/tutorial003.py hl[1,5,8:11,14:17,23:25,28] *} + +1. Todavía importamos `field` de los `dataclasses` estándar. + +2. `pydantic.dataclasses` es un reemplazo directo para `dataclasses`. + +3. El dataclass `Author` incluye una lista de dataclasses `Item`. + +4. El dataclass `Author` se usa como el parámetro `response_model`. + +5. Puedes usar otras anotaciones de tipos estándar con dataclasses como el request body. + + En este caso, es una lista de dataclasses `Item`. + +6. Aquí estamos regresando un diccionario que contiene `items`, que es una lista de dataclasses. + + FastAPI todavía es capaz de serializar los datos a JSON. + +7. Aquí el `response_model` está usando una anotación de tipo de una lista de dataclasses `Author`. + + Nuevamente, puedes combinar `dataclasses` con anotaciones de tipos estándar. + +8. Nota que esta *path operation function* usa `def` regular en lugar de `async def`. + + Como siempre, en FastAPI puedes combinar `def` y `async def` según sea necesario. + + Si necesitas un repaso sobre cuándo usar cuál, revisa la sección _"¿Con prisa?"_ en la documentación sobre [`async` y `await`](../async.md#in-a-hurry){.internal-link target=_blank}. + +9. Esta *path operation function* no está devolviendo dataclasses (aunque podría), sino una lista de diccionarios con datos internos. + + FastAPI usará el parámetro `response_model` (que incluye dataclasses) para convertir el response. + +Puedes combinar `dataclasses` con otras anotaciones de tipos en muchas combinaciones diferentes para formar estructuras de datos complejas. + +Revisa las anotaciones en el código arriba para ver más detalles específicos. + +## Aprende Más + +También puedes combinar `dataclasses` con otros modelos de Pydantic, heredar de ellos, incluirlos en tus propios modelos, etc. + +Para saber más, revisa la documentación de Pydantic sobre dataclasses. + +## Versión + +Esto está disponible desde la versión `0.67.0` de FastAPI. 🔖 diff --git a/docs/es/docs/advanced/events.md b/docs/es/docs/advanced/events.md new file mode 100644 index 000000000..022fb5a42 --- /dev/null +++ b/docs/es/docs/advanced/events.md @@ -0,0 +1,165 @@ +# Eventos de Lifespan + +Puedes definir lógica (código) que debería ser ejecutada antes de que la aplicación **inicie**. Esto significa que este código será ejecutado **una vez**, **antes** de que la aplicación **comience a recibir requests**. + +De la misma manera, puedes definir lógica (código) que debería ser ejecutada cuando la aplicación esté **cerrándose**. En este caso, este código será ejecutado **una vez**, **después** de haber manejado posiblemente **muchos requests**. + +Debido a que este código se ejecuta antes de que la aplicación **comience** a tomar requests, y justo después de que **termine** de manejarlos, cubre todo el **lifespan** de la aplicación (la palabra "lifespan" será importante en un momento 😉). + +Esto puede ser muy útil para configurar **recursos** que necesitas usar para toda la app, y que son **compartidos** entre requests, y/o que necesitas **limpiar** después. Por ejemplo, un pool de conexiones a una base de datos, o cargando un modelo de machine learning compartido. + +## Caso de Uso + +Empecemos con un ejemplo de **caso de uso** y luego veamos cómo resolverlo con esto. + +Imaginemos que tienes algunos **modelos de machine learning** que quieres usar para manejar requests. 🤖 + +Los mismos modelos son compartidos entre requests, por lo que no es un modelo por request, o uno por usuario o algo similar. + +Imaginemos que cargar el modelo puede **tomar bastante tiempo**, porque tiene que leer muchos **datos del disco**. Entonces no quieres hacerlo para cada request. + +Podrías cargarlo en el nivel superior del módulo/archivo, pero eso también significaría que **cargaría el modelo** incluso si solo estás ejecutando una simple prueba automatizada, entonces esa prueba sería **lenta** porque tendría que esperar a que el modelo se cargue antes de poder ejecutar una parte independiente del código. + +Eso es lo que resolveremos, vamos a cargar el modelo antes de que los requests sean manejados, pero solo justo antes de que la aplicación comience a recibir requests, no mientras el código se está cargando. + +## Lifespan + +Puedes definir esta lógica de *startup* y *shutdown* usando el parámetro `lifespan` de la app de `FastAPI`, y un "context manager" (te mostraré lo que es en un momento). + +Comencemos con un ejemplo y luego veámoslo en detalle. + +Creamos una función asíncrona `lifespan()` con `yield` así: + +{* ../../docs_src/events/tutorial003.py hl[16,19] *} + +Aquí estamos simulando la operación costosa de *startup* de cargar el modelo poniendo la función del (falso) modelo en el diccionario con modelos de machine learning antes del `yield`. Este código será ejecutado **antes** de que la aplicación **comience a tomar requests**, durante el *startup*. + +Y luego, justo después del `yield`, quitaremos el modelo de memoria. Este código será ejecutado **después** de que la aplicación **termine de manejar requests**, justo antes del *shutdown*. Esto podría, por ejemplo, liberar recursos como la memoria o una GPU. + +/// tip | Consejo + +El `shutdown` ocurriría cuando estás **deteniendo** la aplicación. + +Quizás necesites iniciar una nueva versión, o simplemente te cansaste de ejecutarla. 🤷 + +/// + +### Función de Lifespan + +Lo primero que hay que notar es que estamos definiendo una función asíncrona con `yield`. Esto es muy similar a las Dependencias con `yield`. + +{* ../../docs_src/events/tutorial003.py hl[14:19] *} + +La primera parte de la función, antes del `yield`, será ejecutada **antes** de que la aplicación comience. + +Y la parte después del `yield` será ejecutada **después** de que la aplicación haya terminado. + +### Async Context Manager + +Si revisas, la función está decorada con un `@asynccontextmanager`. + +Eso convierte a la función en algo llamado un "**async context manager**". + +{* ../../docs_src/events/tutorial003.py hl[1,13] *} + +Un **context manager** en Python es algo que puedes usar en una declaración `with`, por ejemplo, `open()` puede ser usado como un context manager: + +```Python +with open("file.txt") as file: + file.read() +``` + +En versiones recientes de Python, también hay un **async context manager**. Lo usarías con `async with`: + +```Python +async with lifespan(app): + await do_stuff() +``` + +Cuando creas un context manager o un async context manager como arriba, lo que hace es que, antes de entrar al bloque `with`, ejecutará el código antes del `yield`, y al salir del bloque `with`, ejecutará el código después del `yield`. + +En nuestro ejemplo de código arriba, no lo usamos directamente, pero se lo pasamos a FastAPI para que lo use. + +El parámetro `lifespan` de la app de `FastAPI` toma un **async context manager**, por lo que podemos pasar nuestro nuevo `lifespan` async context manager a él. + +{* ../../docs_src/events/tutorial003.py hl[22] *} + +## Eventos Alternativos (obsoleto) + +/// warning | Advertencia + +La forma recomendada de manejar el *startup* y el *shutdown* es usando el parámetro `lifespan` de la app de `FastAPI` como se describió arriba. Si proporcionas un parámetro `lifespan`, los manejadores de eventos `startup` y `shutdown` ya no serán llamados. Es solo `lifespan` o solo los eventos, no ambos. + +Probablemente puedas saltarte esta parte. + +/// + +Hay una forma alternativa de definir esta lógica para ser ejecutada durante el *startup* y durante el *shutdown*. + +Puedes definir manejadores de eventos (funciones) que necesitan ser ejecutadas antes de que la aplicación se inicie, o cuando la aplicación se está cerrando. + +Estas funciones pueden ser declaradas con `async def` o `def` normal. + +### Evento `startup` + +Para añadir una función que debería ejecutarse antes de que la aplicación inicie, declárala con el evento `"startup"`: + +{* ../../docs_src/events/tutorial001.py hl[8] *} + +En este caso, la función manejadora del evento `startup` inicializará los ítems de la "base de datos" (solo un `dict`) con algunos valores. + +Puedes añadir más de un manejador de eventos. + +Y tu aplicación no comenzará a recibir requests hasta que todos los manejadores de eventos `startup` hayan completado. + +### Evento `shutdown` + +Para añadir una función que debería ejecutarse cuando la aplicación se esté cerrando, declárala con el evento `"shutdown"`: + +{* ../../docs_src/events/tutorial002.py hl[6] *} + +Aquí, la función manejadora del evento `shutdown` escribirá una línea de texto `"Application shutdown"` a un archivo `log.txt`. + +/// info | Información + +En la función `open()`, el `mode="a"` significa "añadir", por lo tanto, la línea será añadida después de lo que sea que esté en ese archivo, sin sobrescribir el contenido anterior. + +/// + +/// tip | Consejo + +Nota que en este caso estamos usando una función estándar de Python `open()` que interactúa con un archivo. + +Entonces, involucra I/O (entrada/salida), que requiere "esperar" para que las cosas se escriban en el disco. + +Pero `open()` no usa `async` y `await`. + +Por eso, declaramos la función manejadora del evento con `def` estándar en vez de `async def`. + +/// + +### `startup` y `shutdown` juntos + +Hay una gran posibilidad de que la lógica para tu *startup* y *shutdown* esté conectada, podrías querer iniciar algo y luego finalizarlo, adquirir un recurso y luego liberarlo, etc. + +Hacer eso en funciones separadas que no comparten lógica o variables juntas es más difícil ya que necesitarías almacenar valores en variables globales o trucos similares. + +Debido a eso, ahora se recomienda en su lugar usar el `lifespan` como se explicó arriba. + +## Detalles Técnicos + +Solo un detalle técnico para los nerds curiosos. 🤓 + +Por debajo, en la especificación técnica ASGI, esto es parte del Protocolo de Lifespan, y define eventos llamados `startup` y `shutdown`. + +/// info | Información + +Puedes leer más sobre los manejadores `lifespan` de Starlette en la documentación de `Lifespan` de Starlette. + +Incluyendo cómo manejar el estado de lifespan que puede ser usado en otras áreas de tu código. + +/// + +## Sub Aplicaciones + +🚨 Ten en cuenta que estos eventos de lifespan (startup y shutdown) solo serán ejecutados para la aplicación principal, no para [Sub Aplicaciones - Mounts](sub-applications.md){.internal-link target=_blank}. diff --git a/docs/es/docs/advanced/generate-clients.md b/docs/es/docs/advanced/generate-clients.md new file mode 100644 index 000000000..bf2e5cb4f --- /dev/null +++ b/docs/es/docs/advanced/generate-clients.md @@ -0,0 +1,261 @@ +# Genera Clientes + +Como **FastAPI** está basado en la especificación OpenAPI, obtienes compatibilidad automática con muchas herramientas, incluyendo la documentación automática de la API (proporcionada por Swagger UI). + +Una ventaja particular que no es necesariamente obvia es que puedes **generar clientes** (a veces llamados **SDKs** ) para tu API, para muchos **lenguajes de programación** diferentes. + +## Generadores de Clientes OpenAPI + +Hay muchas herramientas para generar clientes desde **OpenAPI**. + +Una herramienta común es OpenAPI Generator. + +Si estás construyendo un **frontend**, una alternativa muy interesante es openapi-ts. + +## Generadores de Clientes y SDKs - Sponsor + +También hay algunos generadores de Clientes y SDKs **respaldados por empresas** basados en OpenAPI (FastAPI), en algunos casos pueden ofrecerte **funcionalidades adicionales** además de SDKs/clientes generados de alta calidad. + +Algunos de ellos también ✨ [**sponsorean FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, esto asegura el **desarrollo** continuo y saludable de FastAPI y su **ecosistema**. + +Y muestra su verdadero compromiso con FastAPI y su **comunidad** (tú), ya que no solo quieren proporcionarte un **buen servicio** sino también asegurarse de que tengas un **buen y saludable framework**, FastAPI. 🙇 + +Por ejemplo, podrías querer probar: + +* Speakeasy +* Stainless +* liblab + +También hay varias otras empresas que ofrecen servicios similares que puedes buscar y encontrar en línea. 🤓 + +## Genera un Cliente Frontend en TypeScript + +Empecemos con una aplicación simple de FastAPI: + +{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *} + +Nota que las *path operations* definen los modelos que usan para el payload de la petición y el payload del response, usando los modelos `Item` y `ResponseMessage`. + +### Documentación de la API + +Si vas a la documentación de la API, verás que tiene los **esquemas** para los datos que se enviarán en las peticiones y se recibirán en los responses: + + + +Puedes ver esos esquemas porque fueron declarados con los modelos en la aplicación. + +Esa información está disponible en el **JSON Schema** de OpenAPI de la aplicación, y luego se muestra en la documentación de la API (por Swagger UI). + +Y esa misma información de los modelos que está incluida en OpenAPI es lo que puede usarse para **generar el código del cliente**. + +### Genera un Cliente en TypeScript + +Ahora que tenemos la aplicación con los modelos, podemos generar el código del cliente para el frontend. + +#### Instalar `openapi-ts` + +Puedes instalar `openapi-ts` en tu código de frontend con: + +
+ +```console +$ npm install @hey-api/openapi-ts --save-dev + +---> 100% +``` + +
+ +#### Generar el Código del Cliente + +Para generar el código del cliente puedes usar la aplicación de línea de comandos `openapi-ts` que ahora estaría instalada. + +Como está instalada en el proyecto local, probablemente no podrías llamar a ese comando directamente, pero podrías ponerlo en tu archivo `package.json`. + +Podría verse como esto: + +```JSON hl_lines="7" +{ + "name": "frontend-app", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "generate-client": "openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios" + }, + "author": "", + "license": "", + "devDependencies": { + "@hey-api/openapi-ts": "^0.27.38", + "typescript": "^4.6.2" + } +} +``` + +Después de tener ese script de NPM `generate-client` allí, puedes ejecutarlo con: + +
+ +```console +$ npm run generate-client + +frontend-app@1.0.0 generate-client /home/user/code/frontend-app +> openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios +``` + +
+ +Ese comando generará código en `./src/client` y usará `axios` (el paquete HTTP de frontend) internamente. + +### Prueba el Código del Cliente + +Ahora puedes importar y usar el código del cliente, podría verse así, nota que tienes autocompletado para los métodos: + + + +También obtendrás autocompletado para el payload a enviar: + + + +/// tip | Consejo + +Nota el autocompletado para `name` y `price`, que fue definido en la aplicación de FastAPI, en el modelo `Item`. + +/// + +Tendrás errores en línea para los datos que envíes: + + + +El objeto de response también tendrá autocompletado: + + + +## App de FastAPI con Tags + +En muchos casos tu aplicación de FastAPI será más grande, y probablemente usarás tags para separar diferentes grupos de *path operations*. + +Por ejemplo, podrías tener una sección para **items** y otra sección para **usuarios**, y podrían estar separadas por tags: + +{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *} + +### Genera un Cliente TypeScript con Tags + +Si generas un cliente para una aplicación de FastAPI usando tags, normalmente también separará el código del cliente basándose en los tags. + +De esta manera podrás tener las cosas ordenadas y agrupadas correctamente para el código del cliente: + + + +En este caso tienes: + +* `ItemsService` +* `UsersService` + +### Nombres de los Métodos del Cliente + +Ahora mismo los nombres de los métodos generados como `createItemItemsPost` no se ven muy limpios: + +```TypeScript +ItemsService.createItemItemsPost({name: "Plumbus", price: 5}) +``` + +...eso es porque el generador del cliente usa el **operation ID** interno de OpenAPI para cada *path operation*. + +OpenAPI requiere que cada operation ID sea único a través de todas las *path operations*, por lo que FastAPI usa el **nombre de la función**, el **path**, y el **método/operación HTTP** para generar ese operation ID, porque de esa manera puede asegurarse de que los operation IDs sean únicos. + +Pero te mostraré cómo mejorar eso a continuación. 🤓 + +## Operation IDs Personalizados y Mejores Nombres de Métodos + +Puedes **modificar** la forma en que estos operation IDs son **generados** para hacerlos más simples y tener **nombres de métodos más simples** en los clientes. + +En este caso tendrás que asegurarte de que cada operation ID sea **único** de alguna otra manera. + +Por ejemplo, podrías asegurarte de que cada *path operation* tenga un tag, y luego generar el operation ID basado en el **tag** y el nombre de la *path operation* **name** (el nombre de la función). + +### Función Personalizada para Generar ID Único + +FastAPI usa un **ID único** para cada *path operation*, se usa para el **operation ID** y también para los nombres de cualquier modelo personalizado necesario, para requests o responses. + +Puedes personalizar esa función. Toma un `APIRoute` y retorna un string. + +Por ejemplo, aquí está usando el primer tag (probablemente tendrás solo un tag) y el nombre de la *path operation* (el nombre de la función). + +Puedes entonces pasar esa función personalizada a **FastAPI** como el parámetro `generate_unique_id_function`: + +{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *} + +### Generar un Cliente TypeScript con Operation IDs Personalizados + +Ahora si generas el cliente de nuevo, verás que tiene los nombres de métodos mejorados: + + + +Como ves, los nombres de métodos ahora tienen el tag y luego el nombre de la función, ahora no incluyen información del path de la URL y la operación HTTP. + +### Preprocesa la Especificación OpenAPI para el Generador de Clientes + +El código generado aún tiene algo de **información duplicada**. + +Ya sabemos que este método está relacionado con los **items** porque esa palabra está en el `ItemsService` (tomado del tag), pero aún tenemos el nombre del tag prefijado en el nombre del método también. 😕 + +Probablemente aún querremos mantenerlo para OpenAPI en general, ya que eso asegurará que los operation IDs sean **únicos**. + +Pero para el cliente generado podríamos **modificar** los operation IDs de OpenAPI justo antes de generar los clientes, solo para hacer esos nombres de métodos más bonitos y **limpios**. + +Podríamos descargar el JSON de OpenAPI a un archivo `openapi.json` y luego podríamos **remover ese tag prefijado** con un script como este: + +{* ../../docs_src/generate_clients/tutorial004.py *} + +//// tab | Node.js + +```Javascript +{!> ../../docs_src/generate_clients/tutorial004.js!} +``` + +//// + +Con eso, los operation IDs serían renombrados de cosas como `items-get_items` a solo `get_items`, de esa manera el generador del cliente puede generar nombres de métodos más simples. + +### Generar un Cliente TypeScript con el OpenAPI Preprocesado + +Ahora como el resultado final está en un archivo `openapi.json`, modificarías el `package.json` para usar ese archivo local, por ejemplo: + +```JSON hl_lines="7" +{ + "name": "frontend-app", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios" + }, + "author": "", + "license": "", + "devDependencies": { + "@hey-api/openapi-ts": "^0.27.38", + "typescript": "^4.6.2" + } +} +``` + +Después de generar el nuevo cliente, ahora tendrías nombres de métodos **limpios**, con todo el **autocompletado**, **errores en línea**, etc: + + + +## Beneficios + +Cuando usas los clientes generados automáticamente obtendrás **autocompletado** para: + +* Métodos. +* Payloads de peticiones en el cuerpo, parámetros de query, etc. +* Payloads de responses. + +También tendrás **errores en línea** para todo. + +Y cada vez que actualices el código del backend, y **regeneres** el frontend, tendrás las nuevas *path operations* disponibles como métodos, las antiguas eliminadas, y cualquier otro cambio se reflejará en el código generado. 🤓 + +Esto también significa que si algo cambió será **reflejado** automáticamente en el código del cliente. Y si haces **build** del cliente, te dará error si tienes algún **desajuste** en los datos utilizados. + +Así que, **detectarás muchos errores** muy temprano en el ciclo de desarrollo en lugar de tener que esperar a que los errores se muestren a tus usuarios finales en producción para luego intentar depurar dónde está el problema. ✨ diff --git a/docs/es/docs/advanced/middleware.md b/docs/es/docs/advanced/middleware.md new file mode 100644 index 000000000..b8fd86185 --- /dev/null +++ b/docs/es/docs/advanced/middleware.md @@ -0,0 +1,96 @@ +# Middleware Avanzado + +En el tutorial principal leíste cómo agregar [Middleware Personalizado](../tutorial/middleware.md){.internal-link target=_blank} a tu aplicación. + +Y luego también leíste cómo manejar [CORS con el `CORSMiddleware`](../tutorial/cors.md){.internal-link target=_blank}. + +En esta sección veremos cómo usar otros middlewares. + +## Agregando middlewares ASGI + +Como **FastAPI** está basado en Starlette e implementa la especificación ASGI, puedes usar cualquier middleware ASGI. + +Un middleware no tiene que estar hecho para FastAPI o Starlette para funcionar, siempre que siga la especificación ASGI. + +En general, los middlewares ASGI son clases que esperan recibir una aplicación ASGI como primer argumento. + +Entonces, en la documentación de middlewares ASGI de terceros probablemente te indicarán que hagas algo como: + +```Python +from unicorn import UnicornMiddleware + +app = SomeASGIApp() + +new_app = UnicornMiddleware(app, some_config="rainbow") +``` + +Pero FastAPI (en realidad Starlette) proporciona una forma más simple de hacerlo que asegura que los middlewares internos manejen errores del servidor y los controladores de excepciones personalizadas funcionen correctamente. + +Para eso, usas `app.add_middleware()` (como en el ejemplo para CORS). + +```Python +from fastapi import FastAPI +from unicorn import UnicornMiddleware + +app = FastAPI() + +app.add_middleware(UnicornMiddleware, some_config="rainbow") +``` + +`app.add_middleware()` recibe una clase de middleware como primer argumento y cualquier argumento adicional que se le quiera pasar al middleware. + +## Middlewares integrados + +**FastAPI** incluye varios middlewares para casos de uso común, veremos a continuación cómo usarlos. + +/// note | Detalles Técnicos + +Para los próximos ejemplos, también podrías usar `from starlette.middleware.something import SomethingMiddleware`. + +**FastAPI** proporciona varios middlewares en `fastapi.middleware` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los middlewares disponibles provienen directamente de Starlette. + +/// + +## `HTTPSRedirectMiddleware` + +Impone que todas las requests entrantes deben ser `https` o `wss`. + +Cualquier request entrante a `http` o `ws` será redirigida al esquema seguro. + +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} + +## `TrustedHostMiddleware` + +Impone que todas las requests entrantes tengan correctamente configurado el header `Host`, para proteger contra ataques de HTTP Host Header. + +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} + +Se soportan los siguientes argumentos: + +* `allowed_hosts` - Una list de nombres de dominio que deberían ser permitidos como nombres de host. Se soportan dominios comodín como `*.example.com` para hacer coincidir subdominios. Para permitir cualquier nombre de host, usa `allowed_hosts=["*"]` u omite el middleware. + +Si una request entrante no se valida correctamente, se enviará un response `400`. + +## `GZipMiddleware` + +Maneja responses GZip para cualquier request que incluya `"gzip"` en el header `Accept-Encoding`. + +El middleware manejará tanto responses estándar como en streaming. + +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} + +Se soportan los siguientes argumentos: + +* `minimum_size` - No comprimir con GZip responses que sean más pequeñas que este tamaño mínimo en bytes. Por defecto es `500`. +* `compresslevel` - Usado durante la compresión GZip. Es un entero que varía de 1 a 9. Por defecto es `9`. Un valor más bajo resulta en una compresión más rápida pero archivos más grandes, mientras que un valor más alto resulta en una compresión más lenta pero archivos más pequeños. + +## Otros middlewares + +Hay muchos otros middlewares ASGI. + +Por ejemplo: + +* `ProxyHeadersMiddleware` de Uvicorn +* MessagePack + +Para ver otros middlewares disponibles, revisa la documentación de Middleware de Starlette y la Lista ASGI Awesome. diff --git a/docs/es/docs/advanced/openapi-callbacks.md b/docs/es/docs/advanced/openapi-callbacks.md new file mode 100644 index 000000000..60d5cb3cc --- /dev/null +++ b/docs/es/docs/advanced/openapi-callbacks.md @@ -0,0 +1,186 @@ +# OpenAPI Callbacks + +Podrías crear una API con una *path operation* que podría desencadenar un request a una *API externa* creada por alguien más (probablemente el mismo desarrollador que estaría *usando* tu API). + +El proceso que ocurre cuando tu aplicación API llama a la *API externa* se llama un "callback". Porque el software que escribió el desarrollador externo envía un request a tu API y luego tu API *responde*, enviando un request a una *API externa* (que probablemente fue creada por el mismo desarrollador). + +En este caso, podrías querer documentar cómo esa API externa *debería* verse. Qué *path operation* debería tener, qué cuerpo debería esperar, qué response debería devolver, etc. + +## Una aplicación con callbacks + +Veamos todo esto con un ejemplo. + +Imagina que desarrollas una aplicación que permite crear facturas. + +Estas facturas tendrán un `id`, `title` (opcional), `customer`, y `total`. + +El usuario de tu API (un desarrollador externo) creará una factura en tu API con un request POST. + +Luego tu API (imaginemos): + +* Enviará la factura a algún cliente del desarrollador externo. +* Recogerá el dinero. +* Enviará una notificación de vuelta al usuario de la API (el desarrollador externo). + * Esto se hará enviando un request POST (desde *tu API*) a alguna *API externa* proporcionada por ese desarrollador externo (este es el "callback"). + +## La aplicación normal de **FastAPI** + +Primero veamos cómo sería la aplicación API normal antes de agregar el callback. + +Tendrá una *path operation* que recibirá un cuerpo `Invoice`, y un parámetro de query `callback_url` que contendrá la URL para el callback. + +Esta parte es bastante normal, probablemente ya estés familiarizado con la mayor parte del código: + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *} + +/// tip | Consejo + +El parámetro de query `callback_url` utiliza un tipo Url de Pydantic. + +/// + +Lo único nuevo es el `callbacks=invoices_callback_router.routes` como un argumento para el *decorador de path operation*. Veremos qué es eso a continuación. + +## Documentar el callback + +El código real del callback dependerá mucho de tu propia aplicación API. + +Y probablemente variará mucho de una aplicación a otra. + +Podría ser solo una o dos líneas de código, como: + +```Python +callback_url = "https://example.com/api/v1/invoices/events/" +httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) +``` + +Pero posiblemente la parte más importante del callback es asegurarse de que el usuario de tu API (el desarrollador externo) implemente la *API externa* correctamente, de acuerdo con los datos que *tu API* va a enviar en el request body del callback, etc. + +Entonces, lo que haremos a continuación es agregar el código para documentar cómo debería verse esa *API externa* para recibir el callback de *tu API*. + +Esa documentación aparecerá en la Swagger UI en `/docs` en tu API, y permitirá a los desarrolladores externos saber cómo construir la *API externa*. + +Este ejemplo no implementa el callback en sí (eso podría ser solo una línea de código), solo la parte de documentación. + +/// tip | Consejo + +El callback real es solo un request HTTP. + +Cuando implementes el callback tú mismo, podrías usar algo como HTTPX o Requests. + +/// + +## Escribir el código de documentación del callback + +Este código no se ejecutará en tu aplicación, solo lo necesitamos para *documentar* cómo debería verse esa *API externa*. + +Pero, ya sabes cómo crear fácilmente documentación automática para una API con **FastAPI**. + +Así que vamos a usar ese mismo conocimiento para documentar cómo debería verse la *API externa*... creando la(s) *path operation(s)* que la API externa debería implementar (las que tu API va a llamar). + +/// tip | Consejo + +Cuando escribas el código para documentar un callback, podría ser útil imaginar que eres ese *desarrollador externo*. Y que actualmente estás implementando la *API externa*, no *tu API*. + +Adoptar temporalmente este punto de vista (del *desarrollador externo*) puede ayudarte a sentir que es más obvio dónde poner los parámetros, el modelo de Pydantic para el body, para el response, etc. para esa *API externa*. + +/// + +### Crear un `APIRouter` de callback + +Primero crea un nuevo `APIRouter` que contendrá uno o más callbacks. + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *} + +### Crear la *path operation* del callback + +Para crear la *path operation* del callback utiliza el mismo `APIRouter` que creaste anteriormente. + +Debería verse como una *path operation* normal de FastAPI: + +* Probablemente debería tener una declaración del body que debería recibir, por ejemplo `body: InvoiceEvent`. +* Y también podría tener una declaración del response que debería devolver, por ejemplo `response_model=InvoiceEventReceived`. + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *} + +Hay 2 diferencias principales respecto a una *path operation* normal: + +* No necesita tener ningún código real, porque tu aplicación nunca llamará a este código. Solo se usa para documentar la *API externa*. Así que, la función podría simplemente tener `pass`. +* El *path* puede contener una expresión OpenAPI 3 (ver más abajo) donde puede usar variables con parámetros y partes del request original enviado a *tu API*. + +### La expresión del path del callback + +El *path* del callback puede tener una expresión OpenAPI 3 que puede contener partes del request original enviado a *tu API*. + +En este caso, es el `str`: + +```Python +"{$callback_url}/invoices/{$request.body.id}" +``` + +Entonces, si el usuario de tu API (el desarrollador externo) envía un request a *tu API* a: + +``` +https://yourapi.com/invoices/?callback_url=https://www.external.org/events +``` + +con un JSON body de: + +```JSON +{ + "id": "2expen51ve", + "customer": "Mr. Richie Rich", + "total": "9999" +} +``` + +luego *tu API* procesará la factura, y en algún momento después, enviará un request de callback al `callback_url` (la *API externa*): + +``` +https://www.external.org/events/invoices/2expen51ve +``` + +con un JSON body que contiene algo como: + +```JSON +{ + "description": "Payment celebration", + "paid": true +} +``` + +y esperaría un response de esa *API externa* con un JSON body como: + +```JSON +{ + "ok": true +} +``` + +/// tip | Consejo + +Observa cómo la URL del callback utilizada contiene la URL recibida como parámetro de query en `callback_url` (`https://www.external.org/events`) y también el `id` de la factura desde dentro del JSON body (`2expen51ve`). + +/// + +### Agregar el router de callback + +En este punto tienes las *path operation(s)* del callback necesarias (las que el *desarrollador externo* debería implementar en la *API externa*) en el router de callback que creaste antes. + +Ahora usa el parámetro `callbacks` en el *decorador de path operation de tu API* para pasar el atributo `.routes` (que en realidad es solo un `list` de rutas/*path operations*) de ese router de callback: + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *} + +/// tip | Consejo + +Observa que no estás pasando el router en sí (`invoices_callback_router`) a `callback=`, sino el atributo `.routes`, como en `invoices_callback_router.routes`. + +/// + +### Revisa la documentación + +Ahora puedes iniciar tu aplicación e ir a http://127.0.0.1:8000/docs. + +Verás tu documentación incluyendo una sección de "Callbacks" para tu *path operation* que muestra cómo debería verse la *API externa*: + + diff --git a/docs/es/docs/advanced/openapi-webhooks.md b/docs/es/docs/advanced/openapi-webhooks.md new file mode 100644 index 000000000..01235b3ab --- /dev/null +++ b/docs/es/docs/advanced/openapi-webhooks.md @@ -0,0 +1,55 @@ +# Webhooks de OpenAPI + +Hay casos donde quieres decirle a los **usuarios** de tu API que tu aplicación podría llamar a *su* aplicación (enviando una request) con algunos datos, normalmente para **notificar** de algún tipo de **evento**. + +Esto significa que en lugar del proceso normal de tus usuarios enviando requests a tu API, es **tu API** (o tu aplicación) la que podría **enviar requests a su sistema** (a su API, su aplicación). + +Esto normalmente se llama un **webhook**. + +## Pasos de los webhooks + +El proceso normalmente es que **tú defines** en tu código cuál es el mensaje que enviarás, el **body de la request**. + +También defines de alguna manera en qué **momentos** tu aplicación enviará esas requests o eventos. + +Y **tus usuarios** definen de alguna manera (por ejemplo en un panel web en algún lugar) el **URL** donde tu aplicación debería enviar esas requests. + +Toda la **lógica** sobre cómo registrar los URLs para webhooks y el código para realmente enviar esas requests depende de ti. Lo escribes como quieras en **tu propio código**. + +## Documentando webhooks con **FastAPI** y OpenAPI + +Con **FastAPI**, usando OpenAPI, puedes definir los nombres de estos webhooks, los tipos de operaciones HTTP que tu aplicación puede enviar (por ejemplo, `POST`, `PUT`, etc.) y los **bodies** de las requests que tu aplicación enviaría. + +Esto puede hacer mucho más fácil para tus usuarios **implementar sus APIs** para recibir tus requests de **webhook**, incluso podrían ser capaces de autogenerar algo de su propio código de API. + +/// info | Información + +Los webhooks están disponibles en OpenAPI 3.1.0 y superiores, soportados por FastAPI `0.99.0` y superiores. + +/// + +## Una aplicación con webhooks + +Cuando creas una aplicación de **FastAPI**, hay un atributo `webhooks` que puedes usar para definir *webhooks*, de la misma manera que definirías *path operations*, por ejemplo con `@app.webhooks.post()`. + +{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *} + +Los webhooks que defines terminarán en el esquema de **OpenAPI** y en la interfaz automática de **documentación**. + +/// info | Información + +El objeto `app.webhooks` es en realidad solo un `APIRouter`, el mismo tipo que usarías al estructurar tu aplicación con múltiples archivos. + +/// + +Nota que con los webhooks en realidad no estás declarando un *path* (como `/items/`), el texto que pasas allí es solo un **identificador** del webhook (el nombre del evento), por ejemplo en `@app.webhooks.post("new-subscription")`, el nombre del webhook es `new-subscription`. + +Esto es porque se espera que **tus usuarios** definan el actual **URL path** donde quieren recibir la request del webhook de alguna otra manera (por ejemplo, un panel web). + +### Revisa la documentación + +Ahora puedes iniciar tu app e ir a http://127.0.0.1:8000/docs. + +Verás que tu documentación tiene las *path operations* normales y ahora también algunos **webhooks**: + + diff --git a/docs/es/docs/advanced/response-cookies.md b/docs/es/docs/advanced/response-cookies.md new file mode 100644 index 000000000..c4472eaa1 --- /dev/null +++ b/docs/es/docs/advanced/response-cookies.md @@ -0,0 +1,51 @@ +# Cookies de Response + +## Usar un parámetro `Response` + +Puedes declarar un parámetro de tipo `Response` en tu *path operation function*. + +Y luego puedes establecer cookies en ese objeto de response *temporal*. + +{* ../../docs_src/response_cookies/tutorial002.py hl[1, 8:9] *} + +Y entonces puedes devolver cualquier objeto que necesites, como normalmente lo harías (un `dict`, un modelo de base de datos, etc). + +Y si declaraste un `response_model`, todavía se utilizará para filtrar y convertir el objeto que devolviste. + +**FastAPI** utilizará ese response *temporal* para extraer las cookies (también los headers y el código de estado), y las pondrá en el response final que contiene el valor que devolviste, filtrado por cualquier `response_model`. + +También puedes declarar el parámetro `Response` en las dependencias, y establecer cookies (y headers) en ellas. + +## Devolver una `Response` directamente + +También puedes crear cookies al devolver una `Response` directamente en tu código. + +Para hacer eso, puedes crear un response como se describe en [Devolver un Response Directamente](response-directly.md){.internal-link target=_blank}. + +Luego establece Cookies en ella, y luego devuélvela: + +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} + +/// tip | Consejo + +Ten en cuenta que si devuelves un response directamente en lugar de usar el parámetro `Response`, FastAPI lo devolverá directamente. + +Así que tendrás que asegurarte de que tus datos son del tipo correcto. Por ejemplo, que sea compatible con JSON, si estás devolviendo un `JSONResponse`. + +Y también que no estés enviando ningún dato que debería haber sido filtrado por un `response_model`. + +/// + +### Más información + +/// note | Detalles Técnicos + +También podrías usar `from starlette.responses import Response` o `from starlette.responses import JSONResponse`. + +**FastAPI** proporciona los mismos `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette. + +Y como el `Response` se puede usar frecuentemente para establecer headers y cookies, **FastAPI** también lo proporciona en `fastapi.Response`. + +/// + +Para ver todos los parámetros y opciones disponibles, revisa la documentación en Starlette. diff --git a/docs/es/docs/advanced/security/http-basic-auth.md b/docs/es/docs/advanced/security/http-basic-auth.md new file mode 100644 index 000000000..629e6c50a --- /dev/null +++ b/docs/es/docs/advanced/security/http-basic-auth.md @@ -0,0 +1,107 @@ +# HTTP Basic Auth + +Para los casos más simples, puedes usar HTTP Basic Auth. + +En HTTP Basic Auth, la aplicación espera un header que contiene un nombre de usuario y una contraseña. + +Si no lo recibe, devuelve un error HTTP 401 "Unauthorized". + +Y devuelve un header `WWW-Authenticate` con un valor de `Basic`, y un parámetro `realm` opcional. + +Eso le dice al navegador que muestre el prompt integrado para un nombre de usuario y contraseña. + +Luego, cuando escribes ese nombre de usuario y contraseña, el navegador los envía automáticamente en el header. + +## Simple HTTP Basic Auth + +* Importa `HTTPBasic` y `HTTPBasicCredentials`. +* Crea un "esquema de `security`" usando `HTTPBasic`. +* Usa ese `security` con una dependencia en tu *path operation*. +* Devuelve un objeto de tipo `HTTPBasicCredentials`: + * Contiene el `username` y `password` enviados. + +{* ../../docs_src/security/tutorial006_an_py39.py hl[4,8,12] *} + +Cuando intentas abrir la URL por primera vez (o haces clic en el botón "Execute" en la documentación) el navegador te pedirá tu nombre de usuario y contraseña: + + + +## Revisa el nombre de usuario + +Aquí hay un ejemplo más completo. + +Usa una dependencia para comprobar si el nombre de usuario y la contraseña son correctos. + +Para esto, usa el módulo estándar de Python `secrets` para verificar el nombre de usuario y la contraseña. + +`secrets.compare_digest()` necesita tomar `bytes` o un `str` que solo contenga caracteres ASCII (los carácteres en inglés), esto significa que no funcionaría con caracteres como `á`, como en `Sebastián`. + +Para manejar eso, primero convertimos el `username` y `password` a `bytes` codificándolos con UTF-8. + +Luego podemos usar `secrets.compare_digest()` para asegurar que `credentials.username` es `"stanleyjobson"`, y que `credentials.password` es `"swordfish"`. + +{* ../../docs_src/security/tutorial007_an_py39.py hl[1,12:24] *} + +Esto sería similar a: + +```Python +if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"): + # Return some error + ... +``` + +Pero al usar `secrets.compare_digest()` será seguro contra un tipo de ataques llamados "timing attacks". + +### Timing Attacks + +¿Pero qué es un "timing attack"? + +Imaginemos que algunos atacantes están tratando de adivinar el nombre de usuario y la contraseña. + +Y envían un request con un nombre de usuario `johndoe` y una contraseña `love123`. + +Entonces el código de Python en tu aplicación equivaldría a algo como: + +```Python +if "johndoe" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +Pero justo en el momento en que Python compara la primera `j` en `johndoe` con la primera `s` en `stanleyjobson`, devolverá `False`, porque ya sabe que esas dos strings no son iguales, pensando que "no hay necesidad de gastar más computación comparando el resto de las letras". Y tu aplicación dirá "Nombre de usuario o contraseña incorrectos". + +Pero luego los atacantes prueban con el nombre de usuario `stanleyjobsox` y contraseña `love123`. + +Y el código de tu aplicación hace algo así como: + +```Python +if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +Python tendrá que comparar todo `stanleyjobso` en ambos `stanleyjobsox` y `stanleyjobson` antes de darse cuenta de que ambas strings no son las mismas. Así que tomará algunos microsegundos extra para responder "Nombre de usuario o contraseña incorrectos". + +#### El tiempo de respuesta ayuda a los atacantes + +En ese punto, al notar que el servidor tardó algunos microsegundos más en enviar el response "Nombre de usuario o contraseña incorrectos", los atacantes sabrán que acertaron en _algo_, algunas de las letras iniciales eran correctas. + +Y luego pueden intentar de nuevo sabiendo que probablemente es algo más similar a `stanleyjobsox` que a `johndoe`. + +#### Un ataque "profesional" + +Por supuesto, los atacantes no intentarían todo esto a mano, escribirían un programa para hacerlo, posiblemente con miles o millones de pruebas por segundo. Y obtendrían solo una letra correcta adicional a la vez. + +Pero haciendo eso, en algunos minutos u horas, los atacantes habrían adivinado el nombre de usuario y la contraseña correctos, con la "ayuda" de nuestra aplicación, solo usando el tiempo tomado para responder. + +#### Arréglalo con `secrets.compare_digest()` + +Pero en nuestro código estamos usando realmente `secrets.compare_digest()`. + +En resumen, tomará el mismo tiempo comparar `stanleyjobsox` con `stanleyjobson` que comparar `johndoe` con `stanleyjobson`. Y lo mismo para la contraseña. + +De esa manera, usando `secrets.compare_digest()` en el código de tu aplicación, será seguro contra todo este rango de ataques de seguridad. + +### Devuelve el error + +Después de detectar que las credenciales son incorrectas, regresa un `HTTPException` con un código de estado 401 (el mismo que se devuelve cuando no se proporcionan credenciales) y agrega el header `WWW-Authenticate` para que el navegador muestre el prompt de inicio de sesión nuevamente: + +{* ../../docs_src/security/tutorial007_an_py39.py hl[26:30] *} diff --git a/docs/es/docs/advanced/security/oauth2-scopes.md b/docs/es/docs/advanced/security/oauth2-scopes.md new file mode 100644 index 000000000..17f7b19ca --- /dev/null +++ b/docs/es/docs/advanced/security/oauth2-scopes.md @@ -0,0 +1,274 @@ +# Scopes de OAuth2 + +Puedes usar scopes de OAuth2 directamente con **FastAPI**, están integrados para funcionar de manera fluida. + +Esto te permitiría tener un sistema de permisos más detallado, siguiendo el estándar de OAuth2, integrado en tu aplicación OpenAPI (y la documentación de la API). + +OAuth2 con scopes es el mecanismo usado por muchos grandes proveedores de autenticación, como Facebook, Google, GitHub, Microsoft, Twitter, etc. Lo usan para proporcionar permisos específicos a usuarios y aplicaciones. + +Cada vez que te "logueas con" Facebook, Google, GitHub, Microsoft, Twitter, esa aplicación está usando OAuth2 con scopes. + +En esta sección verás cómo manejar autenticación y autorización con el mismo OAuth2 con scopes en tu aplicación de **FastAPI**. + +/// warning | Advertencia + +Esta es una sección más o menos avanzada. Si estás comenzando, puedes saltarla. + +No necesariamente necesitas scopes de OAuth2, y puedes manejar autenticación y autorización como quieras. + +Pero OAuth2 con scopes se puede integrar muy bien en tu API (con OpenAPI) y en la documentación de tu API. + +No obstante, tú aún impones esos scopes, o cualquier otro requisito de seguridad/autorización, como necesites, en tu código. + +En muchos casos, OAuth2 con scopes puede ser un exceso. + +Pero si sabes que lo necesitas, o tienes curiosidad, sigue leyendo. + +/// + +## Scopes de OAuth2 y OpenAPI + +La especificación de OAuth2 define "scopes" como una lista de strings separados por espacios. + +El contenido de cada uno de estos strings puede tener cualquier formato, pero no debe contener espacios. + +Estos scopes representan "permisos". + +En OpenAPI (por ejemplo, en la documentación de la API), puedes definir "esquemas de seguridad". + +Cuando uno de estos esquemas de seguridad usa OAuth2, también puedes declarar y usar scopes. + +Cada "scope" es solo un string (sin espacios). + +Normalmente se utilizan para declarar permisos de seguridad específicos, por ejemplo: + +* `users:read` o `users:write` son ejemplos comunes. +* `instagram_basic` es usado por Facebook / Instagram. +* `https://www.googleapis.com/auth/drive` es usado por Google. + +/// info | Información + +En OAuth2 un "scope" es solo un string que declara un permiso específico requerido. + +No importa si tiene otros caracteres como `:` o si es una URL. + +Esos detalles son específicos de la implementación. + +Para OAuth2 son solo strings. + +/// + +## Vista global + +Primero, echemos un vistazo rápido a las partes que cambian desde los ejemplos en el **Tutorial - User Guide** principal para [OAuth2 con Password (y hashing), Bearer con tokens JWT](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Ahora usando scopes de OAuth2: + +{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:125,129:135,140,156] *} + +Ahora revisemos esos cambios paso a paso. + +## Esquema de seguridad OAuth2 + +El primer cambio es que ahora estamos declarando el esquema de seguridad OAuth2 con dos scopes disponibles, `me` y `items`. + +El parámetro `scopes` recibe un `dict` con cada scope como clave y la descripción como valor: + +{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *} + +Como ahora estamos declarando esos scopes, aparecerán en la documentación de la API cuando inicies sesión/autorices. + +Y podrás seleccionar cuáles scopes quieres dar de acceso: `me` y `items`. + +Este es el mismo mecanismo utilizado cuando das permisos al iniciar sesión con Facebook, Google, GitHub, etc: + + + +## Token JWT con scopes + +Ahora, modifica la *path operation* del token para devolver los scopes solicitados. + +Todavía estamos usando el mismo `OAuth2PasswordRequestForm`. Incluye una propiedad `scopes` con una `list` de `str`, con cada scope que recibió en el request. + +Y devolvemos los scopes como parte del token JWT. + +/// danger | Peligro + +Para simplificar, aquí solo estamos añadiendo los scopes recibidos directamente al token. + +Pero en tu aplicación, por seguridad, deberías asegurarte de añadir solo los scopes que el usuario realmente puede tener, o los que has predefinido. + +/// + +{* ../../docs_src/security/tutorial005_an_py310.py hl[156] *} + +## Declarar scopes en *path operations* y dependencias + +Ahora declaramos que la *path operation* para `/users/me/items/` requiere el scope `items`. + +Para esto, importamos y usamos `Security` de `fastapi`. + +Puedes usar `Security` para declarar dependencias (igual que `Depends`), pero `Security` también recibe un parámetro `scopes` con una lista de scopes (strings). + +En este caso, pasamos una función de dependencia `get_current_active_user` a `Security` (de la misma manera que haríamos con `Depends`). + +Pero también pasamos una `list` de scopes, en este caso con solo un scope: `items` (podría tener más). + +Y la función de dependencia `get_current_active_user` también puede declarar sub-dependencias, no solo con `Depends` sino también con `Security`. Declarando su propia función de sub-dependencia (`get_current_user`), y más requisitos de scope. + +En este caso, requiere el scope `me` (podría requerir más de un scope). + +/// note | Nota + +No necesariamente necesitas añadir diferentes scopes en diferentes lugares. + +Lo estamos haciendo aquí para demostrar cómo **FastAPI** maneja scopes declarados en diferentes niveles. + +/// + +{* ../../docs_src/security/tutorial005_an_py310.py hl[5,140,171] *} + +/// info | Información Técnica + +`Security` es en realidad una subclase de `Depends`, y tiene solo un parámetro extra que veremos más adelante. + +Pero al usar `Security` en lugar de `Depends`, **FastAPI** sabrá que puede declarar scopes de seguridad, usarlos internamente y documentar la API con OpenAPI. + +Pero cuando importas `Query`, `Path`, `Depends`, `Security` y otros de `fastapi`, en realidad son funciones que devuelven clases especiales. + +/// + +## Usar `SecurityScopes` + +Ahora actualiza la dependencia `get_current_user`. + +Esta es la que usan las dependencias anteriores. + +Aquí es donde estamos usando el mismo esquema de OAuth2 que creamos antes, declarándolo como una dependencia: `oauth2_scheme`. + +Porque esta función de dependencia no tiene ningún requisito de scope en sí, podemos usar `Depends` con `oauth2_scheme`, no tenemos que usar `Security` cuando no necesitamos especificar scopes de seguridad. + +También declaramos un parámetro especial de tipo `SecurityScopes`, importado de `fastapi.security`. + +Esta clase `SecurityScopes` es similar a `Request` (`Request` se usó para obtener el objeto request directamente). + +{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *} + +## Usar los `scopes` + +El parámetro `security_scopes` será del tipo `SecurityScopes`. + +Tendrá una propiedad `scopes` con una lista que contiene todos los scopes requeridos por sí mismo y por todas las dependencias que lo usan como sub-dependencia. Eso significa, todos los "dependientes"... esto podría sonar confuso, se explica de nuevo más abajo. + +El objeto `security_scopes` (de la clase `SecurityScopes`) también proporciona un atributo `scope_str` con un único string, que contiene esos scopes separados por espacios (lo vamos a usar). + +Creamos una `HTTPException` que podemos reutilizar (`raise`) más tarde en varios puntos. + +En esta excepción, incluimos los scopes requeridos (si los hay) como un string separado por espacios (usando `scope_str`). Ponemos ese string que contiene los scopes en el header `WWW-Authenticate` (esto es parte de la especificación). + +{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *} + +## Verificar el `username` y la forma de los datos + +Verificamos que obtenemos un `username`, y extraemos los scopes. + +Y luego validamos esos datos con el modelo de Pydantic (capturando la excepción `ValidationError`), y si obtenemos un error leyendo el token JWT o validando los datos con Pydantic, lanzamos la `HTTPException` que creamos antes. + +Para eso, actualizamos el modelo de Pydantic `TokenData` con una nueva propiedad `scopes`. + +Al validar los datos con Pydantic podemos asegurarnos de que tenemos, por ejemplo, exactamente una `list` de `str` con los scopes y un `str` con el `username`. + +En lugar de, por ejemplo, un `dict`, o algo más, ya que podría romper la aplicación en algún punto posterior, haciéndolo un riesgo de seguridad. + +También verificamos que tenemos un usuario con ese username, y si no, lanzamos esa misma excepción que creamos antes. + +{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:128] *} + +## Verificar los `scopes` + +Ahora verificamos que todos los scopes requeridos, por esta dependencia y todos los dependientes (incluyendo *path operations*), estén incluidos en los scopes proporcionados en el token recibido, de lo contrario, lanzamos una `HTTPException`. + +Para esto, usamos `security_scopes.scopes`, que contiene una `list` con todos estos scopes como `str`. + +{* ../../docs_src/security/tutorial005_an_py310.py hl[129:135] *} + +## Árbol de dependencias y scopes + +Revisemos de nuevo este árbol de dependencias y los scopes. + +Como la dependencia `get_current_active_user` tiene como sub-dependencia a `get_current_user`, el scope `"me"` declarado en `get_current_active_user` se incluirá en la lista de scopes requeridos en el `security_scopes.scopes` pasado a `get_current_user`. + +La *path operation* en sí también declara un scope, `"items"`, por lo que esto también estará en la lista de `security_scopes.scopes` pasado a `get_current_user`. + +Así es como se ve la jerarquía de dependencias y scopes: + +* La *path operation* `read_own_items` tiene: + * Scopes requeridos `["items"]` con la dependencia: + * `get_current_active_user`: + * La función de dependencia `get_current_active_user` tiene: + * Scopes requeridos `["me"]` con la dependencia: + * `get_current_user`: + * La función de dependencia `get_current_user` tiene: + * No requiere scopes por sí misma. + * Una dependencia usando `oauth2_scheme`. + * Un parámetro `security_scopes` de tipo `SecurityScopes`: + * Este parámetro `security_scopes` tiene una propiedad `scopes` con una `list` que contiene todos estos scopes declarados arriba, por lo que: + * `security_scopes.scopes` contendrá `["me", "items"]` para la *path operation* `read_own_items`. + * `security_scopes.scopes` contendrá `["me"]` para la *path operation* `read_users_me`, porque está declarado en la dependencia `get_current_active_user`. + * `security_scopes.scopes` contendrá `[]` (nada) para la *path operation* `read_system_status`, porque no declaró ningún `Security` con `scopes`, y su dependencia, `get_current_user`, tampoco declara ningún `scopes`. + +/// tip | Consejo + +Lo importante y "mágico" aquí es que `get_current_user` tendrá una lista diferente de `scopes` para verificar para cada *path operation*. + +Todo depende de los `scopes` declarados en cada *path operation* y cada dependencia en el árbol de dependencias para esa *path operation* específica. + +/// + +## Más detalles sobre `SecurityScopes` + +Puedes usar `SecurityScopes` en cualquier punto, y en múltiples lugares, no tiene que ser en la dependencia "raíz". + +Siempre tendrá los scopes de seguridad declarados en las dependencias `Security` actuales y todos los dependientes para **esa específica** *path operation* y **ese específico** árbol de dependencias. + +Debido a que `SecurityScopes` tendrá todos los scopes declarados por dependientes, puedes usarlo para verificar que un token tiene los scopes requeridos en una función de dependencia central, y luego declarar diferentes requisitos de scope en diferentes *path operations*. + +Serán verificados independientemente para cada *path operation*. + +## Revisa + +Si abres la documentación de la API, puedes autenticarte y especificar qué scopes deseas autorizar. + + + +Si no seleccionas ningún scope, estarás "autenticado", pero cuando intentes acceder a `/users/me/` o `/users/me/items/` obtendrás un error diciendo que no tienes suficientes permisos. Aún podrás acceder a `/status/`. + +Y si seleccionas el scope `me` pero no el scope `items`, podrás acceder a `/users/me/` pero no a `/users/me/items/`. + +Eso es lo que pasaría a una aplicación de terceros que intentara acceder a una de estas *path operations* con un token proporcionado por un usuario, dependiendo de cuántos permisos el usuario otorgó a la aplicación. + +## Acerca de las integraciones de terceros + +En este ejemplo estamos usando el flujo de OAuth2 "password". + +Esto es apropiado cuando estamos iniciando sesión en nuestra propia aplicación, probablemente con nuestro propio frontend. + +Porque podemos confiar en ella para recibir el `username` y `password`, ya que la controlamos. + +Pero si estás construyendo una aplicación OAuth2 a la que otros se conectarían (es decir, si estás construyendo un proveedor de autenticación equivalente a Facebook, Google, GitHub, etc.) deberías usar uno de los otros flujos. + +El más común es el flujo implícito. + +El más seguro es el flujo de código, pero es más complejo de implementar ya que requiere más pasos. Como es más complejo, muchos proveedores terminan sugiriendo el flujo implícito. + +/// note | Nota + +Es común que cada proveedor de autenticación nombre sus flujos de una manera diferente, para hacerlos parte de su marca. + +Pero al final, están implementando el mismo estándar OAuth2. + +/// + +**FastAPI** incluye utilidades para todos estos flujos de autenticación OAuth2 en `fastapi.security.oauth2`. + +## `Security` en `dependencies` del decorador + +De la misma manera que puedes definir una `list` de `Depends` en el parámetro `dependencies` del decorador (como se explica en [Dependencias en decoradores de path operation](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), también podrías usar `Security` con `scopes` allí. diff --git a/docs/es/docs/advanced/settings.md b/docs/es/docs/advanced/settings.md new file mode 100644 index 000000000..7e591cc01 --- /dev/null +++ b/docs/es/docs/advanced/settings.md @@ -0,0 +1,346 @@ +# Configuraciones y Variables de Entorno + +En muchos casos, tu aplicación podría necesitar algunas configuraciones o ajustes externos, por ejemplo, claves secretas, credenciales de base de datos, credenciales para servicios de correo electrónico, etc. + +La mayoría de estas configuraciones son variables (pueden cambiar), como las URLs de bases de datos. Y muchas podrían ser sensibles, como los secretos. + +Por esta razón, es común proporcionarlas en variables de entorno que son leídas por la aplicación. + +/// tip | Consejo + +Para entender las variables de entorno, puedes leer [Variables de Entorno](../environment-variables.md){.internal-link target=_blank}. + +/// + +## Tipos y validación + +Estas variables de entorno solo pueden manejar strings de texto, ya que son externas a Python y tienen que ser compatibles con otros programas y el resto del sistema (e incluso con diferentes sistemas operativos, como Linux, Windows, macOS). + +Eso significa que cualquier valor leído en Python desde una variable de entorno será un `str`, y cualquier conversión a un tipo diferente o cualquier validación tiene que hacerse en código. + +## Pydantic `Settings` + +Afortunadamente, Pydantic proporciona una gran utilidad para manejar estas configuraciones provenientes de variables de entorno con Pydantic: Settings management. + +### Instalar `pydantic-settings` + +Primero, asegúrate de crear tu [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, actívalo y luego instala el paquete `pydantic-settings`: + +
+ +```console +$ pip install pydantic-settings +---> 100% +``` + +
+ +También viene incluido cuando instalas los extras `all` con: + +
+ +```console +$ pip install "fastapi[all]" +---> 100% +``` + +
+ +/// info | Información + +En Pydantic v1 venía incluido con el paquete principal. Ahora se distribuye como este paquete independiente para que puedas elegir si instalarlo o no si no necesitas esa funcionalidad. + +/// + +### Crear el objeto `Settings` + +Importa `BaseSettings` de Pydantic y crea una sub-clase, muy similar a un modelo de Pydantic. + +De la misma forma que con los modelos de Pydantic, declaras atributos de clase con anotaciones de tipos, y posiblemente, valores por defecto. + +Puedes usar todas las mismas funcionalidades de validación y herramientas que usas para los modelos de Pydantic, como diferentes tipos de datos y validaciones adicionales con `Field()`. + +//// tab | Pydantic v2 + +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} + +//// + +//// tab | Pydantic v1 + +/// info | Información + +En Pydantic v1 importarías `BaseSettings` directamente desde `pydantic` en lugar de desde `pydantic_settings`. + +/// + +{* ../../docs_src/settings/tutorial001_pv1.py hl[2,5:8,11] *} + +//// + +/// tip | Consejo + +Si quieres algo rápido para copiar y pegar, no uses este ejemplo, usa el último más abajo. + +/// + +Luego, cuando creas una instance de esa clase `Settings` (en este caso, en el objeto `settings`), Pydantic leerá las variables de entorno de una manera indiferente a mayúsculas y minúsculas, por lo que una variable en mayúsculas `APP_NAME` aún será leída para el atributo `app_name`. + +Luego convertirá y validará los datos. Así que, cuando uses ese objeto `settings`, tendrás datos de los tipos que declaraste (por ejemplo, `items_per_user` será un `int`). + +### Usar el `settings` + +Luego puedes usar el nuevo objeto `settings` en tu aplicación: + +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} + +### Ejecutar el servidor + +Luego, ejecutarías el servidor pasando las configuraciones como variables de entorno, por ejemplo, podrías establecer un `ADMIN_EMAIL` y `APP_NAME` con: + +
+ +```console +$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +/// tip | Consejo + +Para establecer múltiples variables de entorno para un solo comando, simplemente sepáralas con un espacio y ponlas todas antes del comando. + +/// + +Y luego la configuración `admin_email` se establecería en `"deadpool@example.com"`. + +El `app_name` sería `"ChimichangApp"`. + +Y el `items_per_user` mantendría su valor por defecto de `50`. + +## Configuraciones en otro módulo + +Podrías poner esas configuraciones en otro archivo de módulo como viste en [Aplicaciones Más Grandes - Múltiples Archivos](../tutorial/bigger-applications.md){.internal-link target=_blank}. + +Por ejemplo, podrías tener un archivo `config.py` con: + +{* ../../docs_src/settings/app01/config.py *} + +Y luego usarlo en un archivo `main.py`: + +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} + +/// tip | Consejo + +También necesitarías un archivo `__init__.py` como viste en [Aplicaciones Más Grandes - Múltiples Archivos](../tutorial/bigger-applications.md){.internal-link target=_blank}. + +/// + +## Configuraciones en una dependencia + +En algunas ocasiones podría ser útil proporcionar las configuraciones desde una dependencia, en lugar de tener un objeto global con `settings` que se use en todas partes. + +Esto podría ser especialmente útil durante las pruebas, ya que es muy fácil sobrescribir una dependencia con tus propias configuraciones personalizadas. + +### El archivo de configuración + +Proveniente del ejemplo anterior, tu archivo `config.py` podría verse como: + +{* ../../docs_src/settings/app02/config.py hl[10] *} + +Nota que ahora no creamos una instance por defecto `settings = Settings()`. + +### El archivo principal de la app + +Ahora creamos una dependencia que devuelve un nuevo `config.Settings()`. + +{* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *} + +/// tip | Consejo + +Hablaremos del `@lru_cache` en un momento. + +Por ahora puedes asumir que `get_settings()` es una función normal. + +/// + +Y luego podemos requerirlo desde la *path operation function* como una dependencia y usarlo donde lo necesitemos. + +{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *} + +### Configuraciones y pruebas + +Luego sería muy fácil proporcionar un objeto de configuraciones diferente durante las pruebas al sobrescribir una dependencia para `get_settings`: + +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} + +En la dependencia sobreescrita establecemos un nuevo valor para el `admin_email` al crear el nuevo objeto `Settings`, y luego devolvemos ese nuevo objeto. + +Luego podemos probar que se está usando. + +## Leer un archivo `.env` + +Si tienes muchas configuraciones que posiblemente cambien mucho, tal vez en diferentes entornos, podría ser útil ponerlos en un archivo y luego leerlos desde allí como si fueran variables de entorno. + +Esta práctica es lo suficientemente común que tiene un nombre, estas variables de entorno generalmente se colocan en un archivo `.env`, y el archivo se llama un "dotenv". + +/// tip | Consejo + +Un archivo que comienza con un punto (`.`) es un archivo oculto en sistemas tipo Unix, como Linux y macOS. + +Pero un archivo dotenv realmente no tiene que tener ese nombre exacto. + +/// + +Pydantic tiene soporte para leer desde estos tipos de archivos usando un paquete externo. Puedes leer más en Pydantic Settings: Dotenv (.env) support. + +/// tip | Consejo + +Para que esto funcione, necesitas `pip install python-dotenv`. + +/// + +### El archivo `.env` + +Podrías tener un archivo `.env` con: + +```bash +ADMIN_EMAIL="deadpool@example.com" +APP_NAME="ChimichangApp" +``` + +### Leer configuraciones desde `.env` + +Y luego actualizar tu `config.py` con: + +//// tab | Pydantic v2 + +{* ../../docs_src/settings/app03_an/config.py hl[9] *} + +/// tip | Consejo + +El atributo `model_config` se usa solo para configuración de Pydantic. Puedes leer más en Pydantic: Concepts: Configuration. + +/// + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/settings/app03_an/config_pv1.py hl[9:10] *} + +/// tip | Consejo + +La clase `Config` se usa solo para configuración de Pydantic. Puedes leer más en Pydantic Model Config. + +/// + +//// + +/// info | Información + +En la versión 1 de Pydantic la configuración se hacía en una clase interna `Config`, en la versión 2 de Pydantic se hace en un atributo `model_config`. Este atributo toma un `dict`, y para obtener autocompletado y errores en línea, puedes importar y usar `SettingsConfigDict` para definir ese `dict`. + +/// + +Aquí definimos la configuración `env_file` dentro de tu clase Pydantic `Settings`, y establecemos el valor en el nombre del archivo con el archivo dotenv que queremos usar. + +### Creando el `Settings` solo una vez con `lru_cache` + +Leer un archivo desde el disco es normalmente una operación costosa (lenta), por lo que probablemente quieras hacerlo solo una vez y luego reutilizar el mismo objeto de configuraciones, en lugar de leerlo para cada request. + +Pero cada vez que hacemos: + +```Python +Settings() +``` + +se crearía un nuevo objeto `Settings`, y al crearse leería el archivo `.env` nuevamente. + +Si la función de dependencia fuera simplemente así: + +```Python +def get_settings(): + return Settings() +``` + +crearíamos ese objeto para cada request, y estaríamos leyendo el archivo `.env` para cada request. ⚠️ + +Pero como estamos usando el decorador `@lru_cache` encima, el objeto `Settings` se creará solo una vez, la primera vez que se llame. ✔️ + +{* ../../docs_src/settings/app03_an_py39/main.py hl[1,11] *} + +Entonces, para cualquier llamada subsiguiente de `get_settings()` en las dependencias de los próximos requests, en lugar de ejecutar el código interno de `get_settings()` y crear un nuevo objeto `Settings`, devolverá el mismo objeto que fue devuelto en la primera llamada, una y otra vez. + +#### Detalles Técnicos de `lru_cache` + +`@lru_cache` modifica la función que decora para devolver el mismo valor que se devolvió la primera vez, en lugar de calcularlo nuevamente, ejecutando el código de la función cada vez. + +Así que la función debajo se ejecutará una vez por cada combinación de argumentos. Y luego, los valores devueltos por cada una de esas combinaciones de argumentos se utilizarán una y otra vez cada vez que la función sea llamada con exactamente la misma combinación de argumentos. + +Por ejemplo, si tienes una función: + +```Python +@lru_cache +def say_hi(name: str, salutation: str = "Ms."): + return f"Hello {salutation} {name}" +``` + +tu programa podría ejecutarse así: + +```mermaid +sequenceDiagram + +participant code as Código +participant function as say_hi() +participant execute as Ejecutar función + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Camila") + function ->> execute: ejecutar código de la función + execute ->> code: devolver el resultado + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Camila") + function ->> code: devolver resultado almacenado + end + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Rick") + function ->> execute: ejecutar código de la función + execute ->> code: devolver el resultado + end + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Rick", salutation="Mr.") + function ->> execute: ejecutar código de la función + execute ->> code: devolver el resultado + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Rick") + function ->> code: devolver resultado almacenado + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Camila") + function ->> code: devolver resultado almacenado + end +``` + +En el caso de nuestra dependencia `get_settings()`, la función ni siquiera toma argumentos, por lo que siempre devolverá el mismo valor. + +De esa manera, se comporta casi como si fuera solo una variable global. Pero como usa una función de dependencia, entonces podemos sobrescribirla fácilmente para las pruebas. + +`@lru_cache` es parte de `functools`, que es parte del library estándar de Python, puedes leer más sobre él en las docs de Python para `@lru_cache`. + +## Resumen + +Puedes usar Pydantic Settings para manejar las configuraciones o ajustes de tu aplicación, con todo el poder de los modelos de Pydantic. + +* Al usar una dependencia, puedes simplificar las pruebas. +* Puedes usar archivos `.env` con él. +* Usar `@lru_cache` te permite evitar leer el archivo dotenv una y otra vez para cada request, mientras te permite sobrescribirlo durante las pruebas. diff --git a/docs/es/docs/advanced/sub-applications.md b/docs/es/docs/advanced/sub-applications.md new file mode 100644 index 000000000..ccb31f1ea --- /dev/null +++ b/docs/es/docs/advanced/sub-applications.md @@ -0,0 +1,67 @@ +# Sub Aplicaciones - Mounts + +Si necesitas tener dos aplicaciones de **FastAPI** independientes, cada una con su propio OpenAPI independiente y su propia interfaz de docs, puedes tener una aplicación principal y "montar" una (o más) sub-aplicación(es). + +## Montar una aplicación **FastAPI** + +"Montar" significa añadir una aplicación completamente "independiente" en un path específico, que luego se encarga de manejar todo bajo ese path, con las _path operations_ declaradas en esa sub-aplicación. + +### Aplicación de nivel superior + +Primero, crea la aplicación principal de nivel superior de **FastAPI**, y sus *path operations*: + +{* ../../docs_src/sub_applications/tutorial001.py hl[3, 6:8] *} + +### Sub-aplicación + +Luego, crea tu sub-aplicación, y sus *path operations*. + +Esta sub-aplicación es solo otra aplicación estándar de FastAPI, pero es la que se "montará": + +{* ../../docs_src/sub_applications/tutorial001.py hl[11, 14:16] *} + +### Montar la sub-aplicación + +En tu aplicación de nivel superior, `app`, monta la sub-aplicación, `subapi`. + +En este caso, se montará en el path `/subapi`: + +{* ../../docs_src/sub_applications/tutorial001.py hl[11, 19] *} + +### Revisa la documentación automática de la API + +Ahora, ejecuta el comando `fastapi` con tu archivo: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Y abre la documentación en http://127.0.0.1:8000/docs. + +Verás la documentación automática de la API para la aplicación principal, incluyendo solo sus propias _path operations_: + + + +Y luego, abre la documentación para la sub-aplicación, en http://127.0.0.1:8000/subapi/docs. + +Verás la documentación automática de la API para la sub-aplicación, incluyendo solo sus propias _path operations_, todas bajo el prefijo correcto del sub-path `/subapi`: + + + +Si intentas interactuar con cualquiera de las dos interfaces de usuario, funcionarán correctamente, porque el navegador podrá comunicarse con cada aplicación o sub-aplicación específica. + +### Detalles Técnicos: `root_path` + +Cuando montas una sub-aplicación como se describe arriba, FastAPI se encargará de comunicar el path de montaje para la sub-aplicación usando un mecanismo de la especificación ASGI llamado `root_path`. + +De esa manera, la sub-aplicación sabrá usar ese prefijo de path para la interfaz de documentación. + +Y la sub-aplicación también podría tener sus propias sub-aplicaciones montadas y todo funcionaría correctamente, porque FastAPI maneja todos estos `root_path`s automáticamente. + +Aprenderás más sobre el `root_path` y cómo usarlo explícitamente en la sección sobre [Detrás de un Proxy](behind-a-proxy.md){.internal-link target=_blank}. diff --git a/docs/es/docs/advanced/templates.md b/docs/es/docs/advanced/templates.md new file mode 100644 index 000000000..9de866c2b --- /dev/null +++ b/docs/es/docs/advanced/templates.md @@ -0,0 +1,126 @@ +# Plantillas + +Puedes usar cualquier motor de plantillas que desees con **FastAPI**. + +Una elección común es Jinja2, el mismo que usa Flask y otras herramientas. + +Hay utilidades para configurarlo fácilmente que puedes usar directamente en tu aplicación de **FastAPI** (proporcionadas por Starlette). + +## Instalar dependencias + +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, activarlo e instalar `jinja2`: + +
+ +```console +$ pip install jinja2 + +---> 100% +``` + +
+ +## Usando `Jinja2Templates` + +* Importa `Jinja2Templates`. +* Crea un objeto `templates` que puedas reutilizar más tarde. +* Declara un parámetro `Request` en la *path operation* que devolverá una plantilla. +* Usa los `templates` que creaste para renderizar y devolver un `TemplateResponse`, pasa el nombre de la plantilla, el objeto de request, y un diccionario "context" con pares clave-valor que se usarán dentro de la plantilla Jinja2. + +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *} + +/// note | Nota + +Antes de FastAPI 0.108.0, Starlette 0.29.0, el `name` era el primer parámetro. + +Además, antes de eso, en versiones anteriores, el objeto `request` se pasaba como parte de los pares clave-valor en el contexto para Jinja2. + +/// + +/// tip | Consejo + +Al declarar `response_class=HTMLResponse`, la interfaz de usuario de la documentación podrá saber que el response será HTML. + +/// + +/// note | Nota Técnica + +También podrías usar `from starlette.templating import Jinja2Templates`. + +**FastAPI** proporciona el mismo `starlette.templating` como `fastapi.templating`, solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette. Lo mismo con `Request` y `StaticFiles`. + +/// + +## Escribiendo plantillas + +Luego puedes escribir una plantilla en `templates/item.html` con, por ejemplo: + +```jinja hl_lines="7" +{!../../docs_src/templates/templates/item.html!} +``` + +### Valores de Contexto de la Plantilla + +En el HTML que contiene: + +{% raw %} + +```jinja +Item ID: {{ id }} +``` + +{% endraw %} + +...mostrará el `id` tomado del `dict` de "contexto" que pasaste: + +```Python +{"id": id} +``` + +Por ejemplo, con un ID de `42`, esto se renderizaría como: + +```html +Item ID: 42 +``` + +### Argumentos de la Plantilla `url_for` + +También puedes usar `url_for()` dentro de la plantilla, toma como argumentos los mismos que usaría tu *path operation function*. + +Entonces, la sección con: + +{% raw %} + +```jinja + +``` + +{% endraw %} + +...generará un enlace hacia la misma URL que manejaría la *path operation function* `read_item(id=id)`. + +Por ejemplo, con un ID de `42`, esto se renderizaría como: + +```html + +``` + +## Plantillas y archivos estáticos + +También puedes usar `url_for()` dentro de la plantilla, y usarlo, por ejemplo, con los `StaticFiles` que montaste con el `name="static"`. + +```jinja hl_lines="4" +{!../../docs_src/templates/templates/item.html!} +``` + +En este ejemplo, enlazaría a un archivo CSS en `static/styles.css` con: + +```CSS hl_lines="4" +{!../../docs_src/templates/static/styles.css!} +``` + +Y porque estás usando `StaticFiles`, ese archivo CSS sería servido automáticamente por tu aplicación de **FastAPI** en la URL `/static/styles.css`. + +## Más detalles + +Para más detalles, incluyendo cómo testear plantillas, revisa la documentación de Starlette sobre plantillas. diff --git a/docs/es/docs/advanced/testing-dependencies.md b/docs/es/docs/advanced/testing-dependencies.md new file mode 100644 index 000000000..14b90ea06 --- /dev/null +++ b/docs/es/docs/advanced/testing-dependencies.md @@ -0,0 +1,53 @@ +# Probando Dependencias con Overrides + +## Sobrescribir dependencias durante las pruebas + +Hay algunos escenarios donde podrías querer sobrescribir una dependencia durante las pruebas. + +No quieres que la dependencia original se ejecute (ni ninguna de las sub-dependencias que pueda tener). + +En cambio, quieres proporcionar una dependencia diferente que se usará solo durante las pruebas (posiblemente solo algunas pruebas específicas), y que proporcionará un valor que pueda ser usado donde se usó el valor de la dependencia original. + +### Casos de uso: servicio externo + +Un ejemplo podría ser que tienes un proveedor de autenticación externo al que necesitas llamar. + +Le envías un token y te devuelve un usuario autenticado. + +Este proveedor podría estar cobrándote por cada request, y llamarlo podría tomar más tiempo adicional que si tuvieras un usuario de prueba fijo para los tests. + +Probablemente quieras probar el proveedor externo una vez, pero no necesariamente llamarlo para cada test que se realice. + +En este caso, puedes sobrescribir la dependencia que llama a ese proveedor y usar una dependencia personalizada que devuelva un usuario de prueba, solo para tus tests. + +### Usa el atributo `app.dependency_overrides` + +Para estos casos, tu aplicación **FastAPI** tiene un atributo `app.dependency_overrides`, es un simple `dict`. + +Para sobrescribir una dependencia para las pruebas, colocas como clave la dependencia original (una función), y como valor, tu dependencia para sobreescribir (otra función). + +Y entonces **FastAPI** llamará a esa dependencia para sobreescribir en lugar de la dependencia original. + +{* ../../docs_src/dependency_testing/tutorial001_an_py310.py hl[26:27,30] *} + +/// tip | Consejo + +Puedes sobreescribir una dependencia utilizada en cualquier lugar de tu aplicación **FastAPI**. + +La dependencia original podría ser utilizada en una *path operation function*, un *path operation decorator* (cuando no usas el valor de retorno), una llamada a `.include_router()`, etc. + +FastAPI todavía podrá sobrescribirla. + +/// + +Entonces puedes restablecer las dependencias sobreescritas configurando `app.dependency_overrides` para que sea un `dict` vacío: + +```Python +app.dependency_overrides = {} +``` + +/// tip | Consejo + +Si quieres sobrescribir una dependencia solo durante algunos tests, puedes establecer la sobrescritura al inicio del test (dentro de la función del test) y restablecerla al final (al final de la función del test). + +/// diff --git a/docs/es/docs/advanced/testing-events.md b/docs/es/docs/advanced/testing-events.md new file mode 100644 index 000000000..9c2ec77b9 --- /dev/null +++ b/docs/es/docs/advanced/testing-events.md @@ -0,0 +1,5 @@ +# Testing Events: startup - shutdown + +Cuando necesitas que tus manejadores de eventos (`startup` y `shutdown`) se ejecuten en tus tests, puedes usar el `TestClient` con un statement `with`: + +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/es/docs/advanced/testing-websockets.md b/docs/es/docs/advanced/testing-websockets.md new file mode 100644 index 000000000..6d2eaf94d --- /dev/null +++ b/docs/es/docs/advanced/testing-websockets.md @@ -0,0 +1,13 @@ +# Probando WebSockets + +Puedes usar el mismo `TestClient` para probar WebSockets. + +Para esto, usas el `TestClient` en un statement `with`, conectándote al WebSocket: + +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} + +/// note | Nota + +Para más detalles, revisa la documentación de Starlette sobre probando sesiones WebSocket. + +/// diff --git a/docs/es/docs/advanced/using-request-directly.md b/docs/es/docs/advanced/using-request-directly.md new file mode 100644 index 000000000..be8afffcc --- /dev/null +++ b/docs/es/docs/advanced/using-request-directly.md @@ -0,0 +1,56 @@ +# Usar el Request Directamente + +Hasta ahora, has estado declarando las partes del request que necesitas con sus tipos. + +Tomando datos de: + +* El path como parámetros. +* Headers. +* Cookies. +* etc. + +Y al hacerlo, **FastAPI** está validando esos datos, convirtiéndolos y generando documentación para tu API automáticamente. + +Pero hay situaciones donde podrías necesitar acceder al objeto `Request` directamente. + +## Detalles sobre el objeto `Request` + +Como **FastAPI** es en realidad **Starlette** por debajo, con una capa de varias herramientas encima, puedes usar el objeto `Request` de Starlette directamente cuando lo necesites. + +También significa que si obtienes datos del objeto `Request` directamente (por ejemplo, leyendo el cuerpo) no serán validados, convertidos o documentados (con OpenAPI, para la interfaz automática de usuario de la API) por FastAPI. + +Aunque cualquier otro parámetro declarado normalmente (por ejemplo, el cuerpo con un modelo de Pydantic) seguiría siendo validado, convertido, anotado, etc. + +Pero hay casos específicos donde es útil obtener el objeto `Request`. + +## Usa el objeto `Request` directamente + +Imaginemos que quieres obtener la dirección IP/host del cliente dentro de tu *path operation function*. + +Para eso necesitas acceder al request directamente. + +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} + +Al declarar un parámetro de *path operation function* con el tipo siendo `Request`, **FastAPI** sabrá pasar el `Request` en ese parámetro. + +/// tip | Consejo + +Nota que en este caso, estamos declarando un parámetro de path además del parámetro del request. + +Así que, el parámetro de path será extraído, validado, convertido al tipo especificado y anotado con OpenAPI. + +De la misma manera, puedes declarar cualquier otro parámetro como normalmente, y adicionalmente, obtener también el `Request`. + +/// + +## Documentación de `Request` + +Puedes leer más detalles sobre el objeto `Request` en el sitio de documentación oficial de Starlette. + +/// note | Detalles Técnicos + +Podrías también usar `from starlette.requests import Request`. + +**FastAPI** lo proporciona directamente solo como conveniencia para ti, el desarrollador. Pero viene directamente de Starlette. + +/// diff --git a/docs/es/docs/advanced/websockets.md b/docs/es/docs/advanced/websockets.md new file mode 100644 index 000000000..95141c1ca --- /dev/null +++ b/docs/es/docs/advanced/websockets.md @@ -0,0 +1,186 @@ +# WebSockets + +Puedes usar WebSockets con **FastAPI**. + +## Instalar `WebSockets` + +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, activarlo e instalar `websockets`: + +
+ +```console +$ pip install websockets + +---> 100% +``` + +
+ +## Cliente WebSockets + +### En producción + +En tu sistema de producción, probablemente tengas un frontend creado con un framework moderno como React, Vue.js o Angular. + +Y para comunicarte usando WebSockets con tu backend probablemente usarías las utilidades de tu frontend. + +O podrías tener una aplicación móvil nativa que se comunica con tu backend de WebSocket directamente, en código nativo. + +O podrías tener alguna otra forma de comunicarte con el endpoint de WebSocket. + +--- + +Pero para este ejemplo, usaremos un documento HTML muy simple con algo de JavaScript, todo dentro de un string largo. + +Esto, por supuesto, no es lo ideal y no lo usarías para producción. + +En producción tendrías una de las opciones anteriores. + +Pero es la forma más sencilla de enfocarse en el lado del servidor de WebSockets y tener un ejemplo funcional: + +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} + +## Crear un `websocket` + +En tu aplicación de **FastAPI**, crea un `websocket`: + +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} + +/// note | Detalles Técnicos + +También podrías usar `from starlette.websockets import WebSocket`. + +**FastAPI** proporciona el mismo `WebSocket` directamente solo como una conveniencia para ti, el desarrollador. Pero viene directamente de Starlette. + +/// + +## Esperar mensajes y enviar mensajes + +En tu ruta de WebSocket puedes `await` para recibir mensajes y enviar mensajes. + +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} + +Puedes recibir y enviar datos binarios, de texto y JSON. + +## Pruébalo + +Si tu archivo se llama `main.py`, ejecuta tu aplicación con: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Abre tu navegador en http://127.0.0.1:8000. + +Verás una página simple como: + + + +Puedes escribir mensajes en el cuadro de entrada y enviarlos: + + + +Y tu aplicación **FastAPI** con WebSockets responderá de vuelta: + + + +Puedes enviar (y recibir) muchos mensajes: + + + +Y todos usarán la misma conexión WebSocket. + +## Usando `Depends` y otros + +En endpoints de WebSocket puedes importar desde `fastapi` y usar: + +* `Depends` +* `Security` +* `Cookie` +* `Header` +* `Path` +* `Query` + +Funcionan de la misma manera que para otros endpoints de FastAPI/*path operations*: + +{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *} + +/// info | Información + +Como esto es un WebSocket no tiene mucho sentido lanzar un `HTTPException`, en su lugar lanzamos un `WebSocketException`. + +Puedes usar un código de cierre de los códigos válidos definidos en la especificación. + +/// + +### Prueba los WebSockets con dependencias + +Si tu archivo se llama `main.py`, ejecuta tu aplicación con: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Abre tu navegador en http://127.0.0.1:8000. + +Ahí puedes establecer: + +* El "ID del Ítem", usado en el path. +* El "Token" usado como un parámetro query. + +/// tip | Consejo + +Nota que el query `token` será manejado por una dependencia. + +/// + +Con eso puedes conectar el WebSocket y luego enviar y recibir mensajes: + + + +## Manejar desconexiones y múltiples clientes + +Cuando una conexión de WebSocket se cierra, el `await websocket.receive_text()` lanzará una excepción `WebSocketDisconnect`, que puedes capturar y manejar como en este ejemplo. + +{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *} + +Para probarlo: + +* Abre la aplicación con varias pestañas del navegador. +* Escribe mensajes desde ellas. +* Luego cierra una de las pestañas. + +Eso lanzará la excepción `WebSocketDisconnect`, y todos los otros clientes recibirán un mensaje como: + +``` +Client #1596980209979 left the chat +``` + +/// tip | Consejo + +La aplicación anterior es un ejemplo mínimo y simple para demostrar cómo manejar y transmitir mensajes a varias conexiones WebSocket. + +Pero ten en cuenta que, como todo se maneja en memoria, en una sola lista, solo funcionará mientras el proceso esté en ejecución, y solo funcionará con un solo proceso. + +Si necesitas algo fácil de integrar con FastAPI pero que sea más robusto, soportado por Redis, PostgreSQL u otros, revisa encode/broadcaster. + +/// + +## Más información + +Para aprender más sobre las opciones, revisa la documentación de Starlette para: + +* La clase `WebSocket`. +* Manejo de WebSocket basado en clases. diff --git a/docs/es/docs/advanced/wsgi.md b/docs/es/docs/advanced/wsgi.md new file mode 100644 index 000000000..7df62fc9a --- /dev/null +++ b/docs/es/docs/advanced/wsgi.md @@ -0,0 +1,35 @@ +# Incluyendo WSGI - Flask, Django, otros + +Puedes montar aplicaciones WSGI como viste con [Sub Aplicaciones - Mounts](sub-applications.md){.internal-link target=_blank}, [Detrás de un Proxy](behind-a-proxy.md){.internal-link target=_blank}. + +Para eso, puedes usar `WSGIMiddleware` y usarlo para envolver tu aplicación WSGI, por ejemplo, Flask, Django, etc. + +## Usando `WSGIMiddleware` + +Necesitas importar `WSGIMiddleware`. + +Luego envuelve la aplicación WSGI (p. ej., Flask) con el middleware. + +Y luego móntala bajo un path. + +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,3] *} + +## Revisa + +Ahora, cada request bajo el path `/v1/` será manejado por la aplicación Flask. + +Y el resto será manejado por **FastAPI**. + +Si lo ejecutas y vas a http://localhost:8000/v1/ verás el response de Flask: + +```txt +Hello, World from Flask! +``` + +Y si vas a http://localhost:8000/v2 verás el response de FastAPI: + +```JSON +{ + "message": "Hello World" +} +``` diff --git a/docs/es/docs/alternatives.md b/docs/es/docs/alternatives.md new file mode 100644 index 000000000..753b827c0 --- /dev/null +++ b/docs/es/docs/alternatives.md @@ -0,0 +1,485 @@ +# Alternativas, Inspiración y Comparaciones + +Lo que inspiró a **FastAPI**, cómo se compara con las alternativas y lo que aprendió de ellas. + +## Introducción + +**FastAPI** no existiría si no fuera por el trabajo previo de otros. + +Se han creado muchas herramientas antes que han ayudado a inspirar su creación. + +He estado evitando la creación de un nuevo framework durante varios años. Primero intenté resolver todas las funcionalidades cubiertas por **FastAPI** usando muchos frameworks diferentes, plug-ins y herramientas. + +Pero en algún punto, no hubo otra opción que crear algo que proporcionara todas estas funcionalidades, tomando las mejores ideas de herramientas previas y combinándolas de la mejor manera posible, usando funcionalidades del lenguaje que ni siquiera estaban disponibles antes (anotaciones de tipos de Python 3.6+). + +## Herramientas previas + +### Django + +Es el framework más popular de Python y es ampliamente confiable. Se utiliza para construir sistemas como Instagram. + +Está relativamente acoplado con bases de datos relacionales (como MySQL o PostgreSQL), por lo que tener una base de datos NoSQL (como Couchbase, MongoDB, Cassandra, etc) como motor de almacenamiento principal no es muy fácil. + +Fue creado para generar el HTML en el backend, no para crear APIs utilizadas por un frontend moderno (como React, Vue.js y Angular) o por otros sistemas (como dispositivos del IoT) comunicándose con él. + +### Django REST Framework + +El framework Django REST fue creado para ser un kit de herramientas flexible para construir APIs Web utilizando Django, mejorando sus capacidades API. + +Es utilizado por muchas empresas, incluidas Mozilla, Red Hat y Eventbrite. + +Fue uno de los primeros ejemplos de **documentación automática de APIs**, y esto fue específicamente una de las primeras ideas que inspiraron "la búsqueda de" **FastAPI**. + +/// note | Nota + +Django REST Framework fue creado por Tom Christie. El mismo creador de Starlette y Uvicorn, en los cuales **FastAPI** está basado. + +/// + +/// check | Inspiró a **FastAPI** a + +Tener una interfaz de usuario web de documentación automática de APIs. + +/// + +### Flask + +Flask es un "microframework", no incluye integraciones de bases de datos ni muchas de las cosas que vienen por defecto en Django. + +Esta simplicidad y flexibilidad permiten hacer cosas como usar bases de datos NoSQL como el sistema de almacenamiento de datos principal. + +Como es muy simple, es relativamente intuitivo de aprender, aunque la documentación se vuelve algo técnica en algunos puntos. + +También se utiliza comúnmente para otras aplicaciones que no necesariamente necesitan una base de datos, gestión de usuarios, o cualquiera de las muchas funcionalidades que vienen preconstruidas en Django. Aunque muchas de estas funcionalidades se pueden añadir con plug-ins. + +Esta separación de partes, y ser un "microframework" que podría extenderse para cubrir exactamente lo que se necesita, fue una funcionalidad clave que quise mantener. + +Dada la simplicidad de Flask, parecía una buena opción para construir APIs. Lo siguiente a encontrar era un "Django REST Framework" para Flask. + +/// check | Inspiró a **FastAPI** a + +Ser un micro-framework. Haciendo fácil mezclar y combinar las herramientas y partes necesarias. + +Tener un sistema de routing simple y fácil de usar. + +/// + +### Requests + +**FastAPI** no es en realidad una alternativa a **Requests**. Su ámbito es muy diferente. + +De hecho, sería común usar Requests *dentro* de una aplicación FastAPI. + +Aun así, FastAPI se inspiró bastante en Requests. + +**Requests** es un paquete para *interactuar* con APIs (como cliente), mientras que **FastAPI** es un paquete para *construir* APIs (como servidor). + +Están, más o menos, en extremos opuestos, complementándose entre sí. + +Requests tiene un diseño muy simple e intuitivo, es muy fácil de usar, con valores predeterminados sensatos. Pero al mismo tiempo, es muy poderoso y personalizable. + +Por eso, como se dice en el sitio web oficial: + +> Requests es uno de los paquetes Python más descargados de todos los tiempos + +La forma en que lo usas es muy sencilla. Por ejemplo, para hacer un `GET` request, escribirías: + +```Python +response = requests.get("http://example.com/some/url") +``` + +La operación de path equivalente en FastAPI podría verse como: + +```Python hl_lines="1" +@app.get("/some/url") +def read_url(): + return {"message": "Hello World"} +``` + +Mira las similitudes entre `requests.get(...)` y `@app.get(...)`. + +/// check | Inspiró a **FastAPI** a + +* Tener un API simple e intuitivo. +* Usar nombres de métodos HTTP (operaciones) directamente, de una manera sencilla e intuitiva. +* Tener valores predeterminados sensatos, pero personalizaciones poderosas. + +/// + +### Swagger / OpenAPI + +La principal funcionalidad que quería de Django REST Framework era la documentación automática de la API. + +Luego descubrí que había un estándar para documentar APIs, usando JSON (o YAML, una extensión de JSON) llamado Swagger. + +Y ya existía una interfaz de usuario web para las APIs Swagger. Por lo tanto, ser capaz de generar documentación Swagger para una API permitiría usar esta interfaz de usuario web automáticamente. + +En algún punto, Swagger fue entregado a la Linux Foundation, para ser renombrado OpenAPI. + +Es por eso que cuando se habla de la versión 2.0 es común decir "Swagger", y para la versión 3+ "OpenAPI". + +/// check | Inspiró a **FastAPI** a + +Adoptar y usar un estándar abierto para especificaciones de API, en lugar de usar un esquema personalizado. + +Y a integrar herramientas de interfaz de usuario basadas en estándares: + +* Swagger UI +* ReDoc + +Estas dos fueron elegidas por ser bastante populares y estables, pero haciendo una búsqueda rápida, podrías encontrar docenas de interfaces de usuario alternativas para OpenAPI (que puedes usar con **FastAPI**). + +/// + +### Frameworks REST para Flask + +Existen varios frameworks REST para Flask, pero después de invertir tiempo y trabajo investigándolos, encontré que muchos son descontinuados o abandonados, con varios problemas existentes que los hacían inadecuados. + +### Marshmallow + +Una de las principales funcionalidades necesitadas por los sistemas API es la "serialización" de datos, que consiste en tomar datos del código (Python) y convertirlos en algo que pueda ser enviado a través de la red. Por ejemplo, convertir un objeto que contiene datos de una base de datos en un objeto JSON. Convertir objetos `datetime` en strings, etc. + +Otra gran funcionalidad necesaria por las APIs es la validación de datos, asegurarse de que los datos sean válidos, dados ciertos parámetros. Por ejemplo, que algún campo sea un `int`, y no algún string aleatorio. Esto es especialmente útil para los datos entrantes. + +Sin un sistema de validación de datos, tendrías que hacer todas las comprobaciones a mano, en código. + +Estas funcionalidades son para lo que fue creado Marshmallow. Es un gran paquete, y lo he usado mucho antes. + +Pero fue creado antes de que existieran las anotaciones de tipos en Python. Así que, para definir cada esquema necesitas usar utilidades y clases específicas proporcionadas por Marshmallow. + +/// check | Inspiró a **FastAPI** a + +Usar código para definir "esquemas" que proporcionen tipos de datos y validación automáticamente. + +/// + +### Webargs + +Otra gran funcionalidad requerida por las APIs es el parse de datos de las requests entrantes. + +Webargs es una herramienta que fue creada para proporcionar esa funcionalidad sobre varios frameworks, incluido Flask. + +Usa Marshmallow por debajo para hacer la validación de datos. Y fue creada por los mismos desarrolladores. + +Es una gran herramienta y la he usado mucho también, antes de tener **FastAPI**. + +/// info | Información + +Webargs fue creada por los mismos desarrolladores de Marshmallow. + +/// + +/// check | Inspiró a **FastAPI** a + +Tener validación automática de datos entrantes en una request. + +/// + +### APISpec + +Marshmallow y Webargs proporcionan validación, parse y serialización como plug-ins. + +Pero la documentación todavía falta. Entonces APISpec fue creado. + +Es un plug-in para muchos frameworks (y hay un plug-in para Starlette también). + +La manera en que funciona es que escribes la definición del esquema usando el formato YAML dentro del docstring de cada función que maneja una ruta. + +Y genera esquemas OpenAPI. + +Así es como funciona en Flask, Starlette, Responder, etc. + +Pero luego, tenemos otra vez el problema de tener una micro-sintaxis, dentro de un string de Python (un gran YAML). + +El editor no puede ayudar mucho con eso. Y si modificamos parámetros o esquemas de Marshmallow y olvidamos también modificar ese docstring YAML, el esquema generado estaría obsoleto. + +/// info | Información + +APISpec fue creado por los mismos desarrolladores de Marshmallow. + +/// + +/// check | Inspiró a **FastAPI** a + +Soportar el estándar abierto para APIs, OpenAPI. + +/// + +### Flask-apispec + +Es un plug-in de Flask, que conecta juntos Webargs, Marshmallow y APISpec. + +Usa la información de Webargs y Marshmallow para generar automáticamente esquemas OpenAPI, usando APISpec. + +Es una gran herramienta, muy subestimada. Debería ser mucho más popular que muchos plug-ins de Flask por ahí. Puede que se deba a que su documentación es demasiado concisa y abstracta. + +Esto resolvió tener que escribir YAML (otra sintaxis) dentro de docstrings de Python. + +Esta combinación de Flask, Flask-apispec con Marshmallow y Webargs fue mi stack de backend favorito hasta construir **FastAPI**. + +Usarlo llevó a la creación de varios generadores de full-stack para Flask. Estos son los principales stacks que yo (y varios equipos externos) hemos estado usando hasta ahora: + +* https://github.com/tiangolo/full-stack +* https://github.com/tiangolo/full-stack-flask-couchbase +* https://github.com/tiangolo/full-stack-flask-couchdb + +Y estos mismos generadores de full-stack fueron la base de los [Generadores de Proyectos **FastAPI**](project-generation.md){.internal-link target=_blank}. + +/// info | Información + +Flask-apispec fue creado por los mismos desarrolladores de Marshmallow. + +/// + +/// check | Inspiró a **FastAPI** a + +Generar el esquema OpenAPI automáticamente, desde el mismo código que define la serialización y validación. + +/// + +### NestJS (y Angular) + +Esto ni siquiera es Python, NestJS es un framework de JavaScript (TypeScript) NodeJS inspirado por Angular. + +Logra algo algo similar a lo que se puede hacer con Flask-apispec. + +Tiene un sistema de inyección de dependencias integrado, inspirado por Angular 2. Requiere pre-registrar los "inyectables" (como todos los otros sistemas de inyección de dependencias que conozco), por lo que añade a la verbosidad y repetición de código. + +Como los parámetros se describen con tipos de TypeScript (similar a las anotaciones de tipos en Python), el soporte editorial es bastante bueno. + +Pero como los datos de TypeScript no se preservan después de la compilación a JavaScript, no puede depender de los tipos para definir validación, serialización y documentación al mismo tiempo. Debido a esto y algunas decisiones de diseño, para obtener validación, serialización y generación automática del esquema, es necesario agregar decoradores en muchos lugares. Por lo tanto, se vuelve bastante verboso. + +No puede manejar muy bien modelos anidados. Entonces, si el cuerpo JSON en la request es un objeto JSON que tiene campos internos que a su vez son objetos JSON anidados, no puede ser documentado y validado apropiadamente. + +/// check | Inspiró a **FastAPI** a + +Usar tipos de Python para tener un gran soporte del editor. + +Tener un poderoso sistema de inyección de dependencias. Encontrar una forma de minimizar la repetición de código. + +/// + +### Sanic + +Fue uno de los primeros frameworks de Python extremadamente rápidos basados en `asyncio`. Fue hecho para ser muy similar a Flask. + +/// note | Detalles Técnicos + +Usó `uvloop` en lugar del loop `asyncio` por defecto de Python. Eso fue lo que lo hizo tan rápido. + +Claramente inspiró a Uvicorn y Starlette, que actualmente son más rápidos que Sanic en benchmarks abiertos. + +/// + +/// check | Inspiró a **FastAPI** a + +Encontrar una manera de tener un rendimiento impresionante. + +Por eso **FastAPI** se basa en Starlette, ya que es el framework más rápido disponible (probado por benchmarks de terceros). + +/// + +### Falcon + +Falcon es otro framework de Python de alto rendimiento, está diseñado para ser minimalista y funcionar como la base de otros frameworks como Hug. + +Está diseñado para tener funciones que reciben dos parámetros, un "request" y un "response". Luego "lees" partes del request y "escribes" partes en el response. Debido a este diseño, no es posible declarar parámetros de request y cuerpos con las anotaciones de tipos estándar de Python como parámetros de función. + +Por lo tanto, la validación de datos, la serialización y la documentación, tienen que hacerse en código, no automáticamente. O tienen que implementarse como un framework sobre Falcon, como Hug. Esta misma distinción ocurre en otros frameworks que se inspiran en el diseño de Falcon, de tener un objeto request y un objeto response como parámetros. + +/// check | Inspiró a **FastAPI** a + +Buscar maneras de obtener un gran rendimiento. + +Junto con Hug (ya que Hug se basa en Falcon), inspiraron a **FastAPI** a declarar un parámetro `response` en las funciones. + +Aunque en FastAPI es opcional, y se utiliza principalmente para configurar headers, cookies y códigos de estado alternativos. + +/// + +### Molten + +Descubrí Molten en las primeras etapas de construcción de **FastAPI**. Y tiene ideas bastante similares: + +* Basado en las anotaciones de tipos de Python. +* Validación y documentación a partir de estos tipos. +* Sistema de Inyección de Dependencias. + +No utiliza un paquete de validación de datos, serialización y documentación de terceros como Pydantic, tiene el suyo propio. Por lo tanto, estas definiciones de tipos de datos no serían reutilizables tan fácilmente. + +Requiere configuraciones un poquito más verbosas. Y dado que se basa en WSGI (en lugar de ASGI), no está diseñado para aprovechar el alto rendimiento proporcionado por herramientas como Uvicorn, Starlette y Sanic. + +El sistema de inyección de dependencias requiere pre-registrar las dependencias y las dependencias se resuelven en base a los tipos declarados. Por lo tanto, no es posible declarar más de un "componente" que proporcione cierto tipo. + +Las rutas se declaran en un solo lugar, usando funciones declaradas en otros lugares (en lugar de usar decoradores que pueden colocarse justo encima de la función que maneja el endpoint). Esto se acerca más a cómo lo hace Django que a cómo lo hace Flask (y Starlette). Separa en el código cosas que están relativamente acopladas. + +/// check | Inspiró a **FastAPI** a + +Definir validaciones extra para tipos de datos usando el valor "default" de los atributos del modelo. Esto mejora el soporte del editor y no estaba disponible en Pydantic antes. + +Esto en realidad inspiró la actualización de partes de Pydantic, para soportar el mismo estilo de declaración de validación (toda esta funcionalidad ya está disponible en Pydantic). + +/// + +### Hug + +Hug fue uno de los primeros frameworks en implementar la declaración de tipos de parámetros API usando las anotaciones de tipos de Python. Esta fue una gran idea que inspiró a otras herramientas a hacer lo mismo. + +Usaba tipos personalizados en sus declaraciones en lugar de tipos estándar de Python, pero aún así fue un gran avance. + +También fue uno de los primeros frameworks en generar un esquema personalizado declarando toda la API en JSON. + +No se basaba en un estándar como OpenAPI y JSON Schema. Por lo que no sería sencillo integrarlo con otras herramientas, como Swagger UI. Pero, nuevamente, fue una idea muy innovadora. + +Tiene una funcionalidad interesante e inusual: usando el mismo framework, es posible crear APIs y también CLIs. + +Dado que se basa en el estándar previo para frameworks web Python sincrónicos (WSGI), no puede manejar Websockets y otras cosas, aunque aún así tiene un alto rendimiento también. + +/// info | Información + +Hug fue creado por Timothy Crosley, el mismo creador de `isort`, una gran herramienta para ordenar automáticamente imports en archivos Python. + +/// + +/// check | Ideas que inspiraron a **FastAPI** + +Hug inspiró partes de APIStar, y fue una de las herramientas que encontré más prometedoras, junto a APIStar. + +Hug ayudó a inspirar a **FastAPI** a usar anotaciones de tipos de Python para declarar parámetros, y a generar un esquema definiendo la API automáticamente. + +Hug inspiró a **FastAPI** a declarar un parámetro `response` en funciones para configurar headers y cookies. + +/// + +### APIStar (<= 0.5) + +Justo antes de decidir construir **FastAPI** encontré **APIStar** server. Tenía casi todo lo que estaba buscando y tenía un gran diseño. + +Era una de las primeras implementaciones de un framework utilizando las anotaciones de tipos de Python para declarar parámetros y requests que jamás vi (antes de NestJS y Molten). Lo encontré más o menos al mismo tiempo que Hug. Pero APIStar usaba el estándar OpenAPI. + +Tenía validación de datos automática, serialización de datos y generación del esquema OpenAPI basada en las mismas anotaciones de tipos en varios lugares. + +Las definiciones de esquema de cuerpo no usaban las mismas anotaciones de tipos de Python como Pydantic, era un poco más similar a Marshmallow, por lo que el soporte del editor no sería tan bueno, pero aún así, APIStar era la mejor opción disponible. + +Tenía los mejores benchmarks de rendimiento en ese momento (solo superado por Starlette). + +Al principio, no tenía una interfaz de usuario web de documentación de API automática, pero sabía que podía agregar Swagger UI a él. + +Tenía un sistema de inyección de dependencias. Requería pre-registrar componentes, como otras herramientas discutidas anteriormente. Pero aún así, era una gran funcionalidad. + +Nunca pude usarlo en un proyecto completo, ya que no tenía integración de seguridad, por lo que no podía reemplazar todas las funcionalidades que tenía con los generadores de full-stack basados en Flask-apispec. Tenía en mi lista de tareas pendientes de proyectos crear un pull request agregando esa funcionalidad. + +Pero luego, el enfoque del proyecto cambió. + +Ya no era un framework web API, ya que el creador necesitaba enfocarse en Starlette. + +Ahora APIStar es un conjunto de herramientas para validar especificaciones OpenAPI, no un framework web. + +/// info | Información + +APIStar fue creado por Tom Christie. El mismo que creó: + +* Django REST Framework +* Starlette (en la cual **FastAPI** está basado) +* Uvicorn (usado por Starlette y **FastAPI**) + +/// + +/// check | Inspiró a **FastAPI** a + +Existir. + +La idea de declarar múltiples cosas (validación de datos, serialización y documentación) con los mismos tipos de Python, que al mismo tiempo proporcionaban un gran soporte del editor, era algo que consideré una idea brillante. + +Y después de buscar durante mucho tiempo un framework similar y probar muchas alternativas diferentes, APIStar fue la mejor opción disponible. + +Luego APIStar dejó de existir como servidor y Starlette fue creado, y fue una nueva y mejor base para tal sistema. Esa fue la inspiración final para construir **FastAPI**. + +Considero a **FastAPI** un "sucesor espiritual" de APIStar, mientras mejora y aumenta las funcionalidades, el sistema de tipos y otras partes, basándose en los aprendizajes de todas estas herramientas previas. + +/// + +## Usado por **FastAPI** + +### Pydantic + +Pydantic es un paquete para definir validación de datos, serialización y documentación (usando JSON Schema) basándose en las anotaciones de tipos de Python. + +Eso lo hace extremadamente intuitivo. + +Es comparable a Marshmallow. Aunque es más rápido que Marshmallow en benchmarks. Y como está basado en las mismas anotaciones de tipos de Python, el soporte del editor es estupendo. + +/// check | **FastAPI** lo usa para + +Manejar toda la validación de datos, serialización de datos y documentación automática de modelos (basada en JSON Schema). + +**FastAPI** luego toma esos datos JSON Schema y los coloca en OpenAPI, aparte de todas las otras cosas que hace. + +/// + +### Starlette + +Starlette es un framework/toolkit ASGI liviano, ideal para construir servicios asyncio de alto rendimiento. + +Es muy simple e intuitivo. Está diseñado para ser fácilmente extensible y tener componentes modulares. + +Tiene: + +* Un rendimiento seriamente impresionante. +* Soporte para WebSocket. +* Tareas en segundo plano dentro del proceso. +* Eventos de inicio y apagado. +* Cliente de pruebas basado en HTTPX. +* CORS, GZip, Archivos estáticos, Responses en streaming. +* Soporte para sesiones y cookies. +* Cobertura de tests del 100%. +* Base de código 100% tipada. +* Pocas dependencias obligatorias. + +Starlette es actualmente el framework de Python más rápido probado. Solo superado por Uvicorn, que no es un framework, sino un servidor. + +Starlette proporciona toda la funcionalidad básica de un microframework web. + +Pero no proporciona validación de datos automática, serialización o documentación. + +Esa es una de las principales cosas que **FastAPI** agrega, todo basado en las anotaciones de tipos de Python (usando Pydantic). Eso, además del sistema de inyección de dependencias, utilidades de seguridad, generación de esquemas OpenAPI, etc. + +/// note | Detalles Técnicos + +ASGI es un nuevo "estándar" que está siendo desarrollado por miembros del equipo central de Django. Todavía no es un "estándar de Python" (un PEP), aunque están en proceso de hacerlo. + +No obstante, ya está siendo usado como un "estándar" por varias herramientas. Esto mejora enormemente la interoperabilidad, ya que podrías cambiar Uvicorn por cualquier otro servidor ASGI (como Daphne o Hypercorn), o podrías añadir herramientas compatibles con ASGI, como `python-socketio`. + +/// + +/// check | **FastAPI** lo usa para + +Manejar todas las partes web centrales. Añadiendo funcionalidades encima. + +La clase `FastAPI` en sí misma hereda directamente de la clase `Starlette`. + +Por lo tanto, cualquier cosa que puedas hacer con Starlette, puedes hacerlo directamente con **FastAPI**, ya que es básicamente Starlette potenciado. + +/// + +### Uvicorn + +Uvicorn es un servidor ASGI extremadamente rápido, construido sobre uvloop y httptools. + +No es un framework web, sino un servidor. Por ejemplo, no proporciona herramientas para el enrutamiento por paths. Eso es algo que un framework como Starlette (o **FastAPI**) proporcionaría encima. + +Es el servidor recomendado para Starlette y **FastAPI**. + +/// check | **FastAPI** lo recomienda como + +El servidor web principal para ejecutar aplicaciones **FastAPI**. + +También puedes usar la opción de línea de comandos `--workers` para tener un servidor multiproceso asíncrono. + +Revisa más detalles en la sección [Despliegue](deployment/index.md){.internal-link target=_blank}. + +/// + +## Benchmarks y velocidad + +Para entender, comparar, y ver la diferencia entre Uvicorn, Starlette y FastAPI, revisa la sección sobre [Benchmarks](benchmarks.md){.internal-link target=_blank}. diff --git a/docs/es/docs/async.md b/docs/es/docs/async.md index a5c272fb3..e3fd077c4 100644 --- a/docs/es/docs/async.md +++ b/docs/es/docs/async.md @@ -241,7 +241,7 @@ Este es el caso para la mayoría de las aplicaciones web. Muchos, muchos usuarios, pero tu servidor está esperando 🕙 su conexión no tan buena para enviar sus requests. -Y luego esperar 🕙 nuevamente a que los responses regresen. +Y luego esperar 🕙 nuevamente a que los responses retornen. Esta "espera" 🕙 se mide en microsegundos, pero aún así, sumándolo todo, es mucha espera al final. diff --git a/docs/es/docs/deployment/cloud.md b/docs/es/docs/deployment/cloud.md new file mode 100644 index 000000000..fe47d5dcf --- /dev/null +++ b/docs/es/docs/deployment/cloud.md @@ -0,0 +1,18 @@ +# Despliega FastAPI en Proveedores de Nube + +Puedes usar prácticamente **cualquier proveedor de nube** para desplegar tu aplicación FastAPI. + +En la mayoría de los casos, los principales proveedores de nube tienen guías para desplegar FastAPI con ellos. + +## Proveedores de Nube - Sponsors + +Algunos proveedores de nube ✨ [**son sponsors de FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, esto asegura el desarrollo **continuado** y **saludable** de FastAPI y su **ecosistema**. + +Y muestra su verdadero compromiso con FastAPI y su **comunidad** (tú), ya que no solo quieren proporcionarte un **buen servicio**, sino también asegurarse de que tengas un **framework bueno y saludable**, FastAPI. 🙇 + +Podrías querer probar sus servicios y seguir sus guías: + +* Platform.sh +* Porter +* Coherence +* Render diff --git a/docs/es/docs/deployment/concepts.md b/docs/es/docs/deployment/concepts.md new file mode 100644 index 000000000..f5725c5dc --- /dev/null +++ b/docs/es/docs/deployment/concepts.md @@ -0,0 +1,321 @@ +# Conceptos de Implementación + +Cuando implementas una aplicación **FastAPI**, o en realidad, cualquier tipo de API web, hay varios conceptos que probablemente te importen, y al entenderlos, puedes encontrar la **forma más adecuada** de **implementar tu aplicación**. + +Algunos de los conceptos importantes son: + +* Seguridad - HTTPS +* Ejecución al iniciar +* Reinicios +* Replicación (la cantidad de procesos en ejecución) +* Memoria +* Pasos previos antes de iniciar + +Veremos cómo afectan estas **implementaciones**. + +Al final, el objetivo principal es poder **servir a tus clientes de API** de una manera que sea **segura**, para **evitar interrupciones**, y usar los **recursos de cómputo** (por ejemplo, servidores remotos/máquinas virtuales) de la manera más eficiente posible. 🚀 + +Te contaré un poquito más sobre estos **conceptos** aquí, y eso, con suerte, te dará la **intuición** que necesitarías para decidir cómo implementar tu API en diferentes entornos, posiblemente incluso en aquellos **futuros** que aún no existen. + +Al considerar estos conceptos, podrás **evaluar y diseñar** la mejor manera de implementar **tus propias APIs**. + +En los próximos capítulos, te daré más **recetas concretas** para implementar aplicaciones de FastAPI. + +Pero por ahora, revisemos estas importantes **ideas conceptuales**. Estos conceptos también se aplican a cualquier otro tipo de API web. 💡 + +## Seguridad - HTTPS + +En el [capítulo anterior sobre HTTPS](https.md){.internal-link target=_blank} aprendimos sobre cómo HTTPS proporciona cifrado para tu API. + +También vimos que HTTPS es normalmente proporcionado por un componente **externo** a tu servidor de aplicaciones, un **Proxy de Terminación TLS**. + +Y debe haber algo encargado de **renovar los certificados HTTPS**, podría ser el mismo componente o algo diferente. + +### Herramientas de Ejemplo para HTTPS + +Algunas de las herramientas que podrías usar como Proxy de Terminación TLS son: + +* Traefik + * Maneja automáticamente las renovaciones de certificados ✨ +* Caddy + * Maneja automáticamente las renovaciones de certificados ✨ +* Nginx + * Con un componente externo como Certbot para las renovaciones de certificados +* HAProxy + * Con un componente externo como Certbot para las renovaciones de certificados +* Kubernetes con un Controlador de Ingress como Nginx + * Con un componente externo como cert-manager para las renovaciones de certificados +* Manejado internamente por un proveedor de nube como parte de sus servicios (lee abajo 👇) + +Otra opción es que podrías usar un **servicio de nube** que haga más del trabajo, incluyendo configurar HTTPS. Podría tener algunas restricciones o cobrarte más, etc. Pero en ese caso, no tendrías que configurar un Proxy de Terminación TLS tú mismo. + +Te mostraré algunos ejemplos concretos en los próximos capítulos. + +--- + +Luego, los siguientes conceptos a considerar son todos acerca del programa que ejecuta tu API real (por ejemplo, Uvicorn). + +## Programa y Proceso + +Hablaremos mucho sobre el "**proceso**" en ejecución, así que es útil tener claridad sobre lo que significa y cuál es la diferencia con la palabra "**programa**". + +### Qué es un Programa + +La palabra **programa** se usa comúnmente para describir muchas cosas: + +* El **código** que escribes, los **archivos Python**. +* El **archivo** que puede ser **ejecutado** por el sistema operativo, por ejemplo: `python`, `python.exe` o `uvicorn`. +* Un programa específico mientras está siendo **ejecutado** en el sistema operativo, usando la CPU y almacenando cosas en la memoria. Esto también se llama **proceso**. + +### Qué es un Proceso + +La palabra **proceso** se usa normalmente de una manera más específica, refiriéndose solo a lo que está ejecutándose en el sistema operativo (como en el último punto anterior): + +* Un programa específico mientras está siendo **ejecutado** en el sistema operativo. + * Esto no se refiere al archivo, ni al código, se refiere **específicamente** a lo que está siendo **ejecutado** y gestionado por el sistema operativo. +* Cualquier programa, cualquier código, **solo puede hacer cosas** cuando está siendo **ejecutado**. Así que, cuando hay un **proceso en ejecución**. +* El proceso puede ser **terminado** (o "matado") por ti, o por el sistema operativo. En ese punto, deja de ejecutarse/ser ejecutado, y ya no puede **hacer cosas**. +* Cada aplicación que tienes en ejecución en tu computadora tiene algún proceso detrás, cada programa en ejecución, cada ventana, etc. Y normalmente hay muchos procesos ejecutándose **al mismo tiempo** mientras una computadora está encendida. +* Puede haber **múltiples procesos** del **mismo programa** ejecutándose al mismo tiempo. + +Si revisas el "administrador de tareas" o "monitor del sistema" (o herramientas similares) en tu sistema operativo, podrás ver muchos de esos procesos en ejecución. + +Y, por ejemplo, probablemente verás que hay múltiples procesos ejecutando el mismo programa del navegador (Firefox, Chrome, Edge, etc.). Normalmente ejecutan un proceso por pestaña, además de algunos otros procesos extra. + + + +--- + +Ahora que conocemos la diferencia entre los términos **proceso** y **programa**, sigamos hablando sobre implementaciones. + +## Ejecución al Iniciar + +En la mayoría de los casos, cuando creas una API web, quieres que esté **siempre en ejecución**, ininterrumpida, para que tus clientes puedan acceder a ella en cualquier momento. Esto, por supuesto, a menos que tengas una razón específica para que se ejecute solo en ciertas situaciones, pero la mayoría de las veces quieres que esté constantemente en ejecución y **disponible**. + +### En un Servidor Remoto + +Cuando configuras un servidor remoto (un servidor en la nube, una máquina virtual, etc.) lo más sencillo que puedes hacer es usar `fastapi run` (que utiliza Uvicorn) o algo similar, manualmente, de la misma manera que lo haces al desarrollar localmente. + +Y funcionará y será útil **durante el desarrollo**. + +Pero si pierdes la conexión con el servidor, el **proceso en ejecución** probablemente morirá. + +Y si el servidor se reinicia (por ejemplo, después de actualizaciones o migraciones del proveedor de la nube) probablemente **no lo notarás**. Y debido a eso, ni siquiera sabrás que tienes que reiniciar el proceso manualmente. Así, tu API simplemente quedará muerta. 😱 + +### Ejecutar Automáticamente al Iniciar + +En general, probablemente querrás que el programa del servidor (por ejemplo, Uvicorn) se inicie automáticamente al arrancar el servidor, y sin necesidad de ninguna **intervención humana**, para tener siempre un proceso en ejecución con tu API (por ejemplo, Uvicorn ejecutando tu aplicación FastAPI). + +### Programa Separado + +Para lograr esto, normalmente tendrás un **programa separado** que se asegurará de que tu aplicación se ejecute al iniciarse. Y en muchos casos, también se asegurará de que otros componentes o aplicaciones se ejecuten, por ejemplo, una base de datos. + +### Herramientas de Ejemplo para Ejecutar al Iniciar + +Algunos ejemplos de las herramientas que pueden hacer este trabajo son: + +* Docker +* Kubernetes +* Docker Compose +* Docker en Modo Swarm +* Systemd +* Supervisor +* Manejado internamente por un proveedor de nube como parte de sus servicios +* Otros... + +Te daré más ejemplos concretos en los próximos capítulos. + +## Reinicios + +De manera similar a asegurarte de que tu aplicación se ejecute al iniciar, probablemente también quieras asegurarte de que se **reinicie** después de fallos. + +### Cometemos Errores + +Nosotros, como humanos, cometemos **errores**, todo el tiempo. El software casi *siempre* tiene **bugs** ocultos en diferentes lugares. 🐛 + +Y nosotros, como desarrolladores, seguimos mejorando el código a medida que encontramos esos bugs y a medida que implementamos nuevas funcionalidades (posiblemente agregando nuevos bugs también 😅). + +### Errores Pequeños Manejados Automáticamente + +Al construir APIs web con FastAPI, si hay un error en nuestro código, FastAPI normalmente lo contiene a la solicitud única que desencadenó el error. 🛡 + +El cliente obtendrá un **500 Internal Server Error** para esa solicitud, pero la aplicación continuará funcionando para las siguientes solicitudes en lugar de simplemente colapsar por completo. + +### Errores Mayores - Colapsos + +Sin embargo, puede haber casos en los que escribamos algún código que **colapse toda la aplicación** haciendo que Uvicorn y Python colapsen. 💥 + +Y aún así, probablemente no querrías que la aplicación quede muerta porque hubo un error en un lugar, probablemente querrás que **siga ejecutándose** al menos para las *path operations* que no estén rotas. + +### Reiniciar Después del Colapso + +Pero en esos casos con errores realmente malos que colapsan el **proceso en ejecución**, querrías un componente externo encargado de **reiniciar** el proceso, al menos un par de veces... + +/// tip | Consejo + +...Aunque si la aplicación completa **colapsa inmediatamente**, probablemente no tenga sentido seguir reiniciándola eternamente. Pero en esos casos, probablemente lo notarás durante el desarrollo, o al menos justo después de la implementación. + +Así que enfoquémonos en los casos principales, donde podría colapsar por completo en algunos casos particulares **en el futuro**, y aún así tenga sentido reiniciarla. + +/// + +Probablemente querrías que la cosa encargada de reiniciar tu aplicación sea un **componente externo**, porque para ese punto, la misma aplicación con Uvicorn y Python ya colapsó, así que no hay nada en el mismo código de la misma aplicación que pueda hacer algo al respecto. + +### Herramientas de Ejemplo para Reiniciar Automáticamente + +En la mayoría de los casos, la misma herramienta que se utiliza para **ejecutar el programa al iniciar** también se utiliza para manejar reinicios automáticos. + +Por ejemplo, esto podría ser manejado por: + +* Docker +* Kubernetes +* Docker Compose +* Docker en Modo Swarm +* Systemd +* Supervisor +* Manejado internamente por un proveedor de nube como parte de sus servicios +* Otros... + +## Replicación - Procesos y Memoria + +Con una aplicación FastAPI, usando un programa servidor como el comando `fastapi` que ejecuta Uvicorn, ejecutarlo una vez en **un proceso** puede servir a múltiples clientes concurrentemente. + +Pero en muchos casos, querrás ejecutar varios worker processes al mismo tiempo. + +### Múltiples Procesos - Workers + +Si tienes más clientes de los que un solo proceso puede manejar (por ejemplo, si la máquina virtual no es muy grande) y tienes **múltiples núcleos** en la CPU del servidor, entonces podrías tener **múltiples procesos** ejecutando la misma aplicación al mismo tiempo, y distribuir todas las requests entre ellos. + +Cuando ejecutas **múltiples procesos** del mismo programa de API, comúnmente se les llama **workers**. + +### Worker Processes y Puertos + +Recuerda de la documentación [Sobre HTTPS](https.md){.internal-link target=_blank} que solo un proceso puede estar escuchando en una combinación de puerto y dirección IP en un servidor. + +Esto sigue siendo cierto. + +Así que, para poder tener **múltiples procesos** al mismo tiempo, tiene que haber un **solo proceso escuchando en un puerto** que luego transmita la comunicación a cada worker process de alguna forma. + +### Memoria por Proceso + +Ahora, cuando el programa carga cosas en memoria, por ejemplo, un modelo de machine learning en una variable, o el contenido de un archivo grande en una variable, todo eso **consume un poco de la memoria (RAM)** del servidor. + +Y múltiples procesos normalmente **no comparten ninguna memoria**. Esto significa que cada proceso en ejecución tiene sus propias cosas, variables y memoria. Y si estás consumiendo una gran cantidad de memoria en tu código, **cada proceso** consumirá una cantidad equivalente de memoria. + +### Memoria del Servidor + +Por ejemplo, si tu código carga un modelo de Machine Learning con **1 GB de tamaño**, cuando ejecutas un proceso con tu API, consumirá al menos 1 GB de RAM. Y si inicias **4 procesos** (4 workers), cada uno consumirá 1 GB de RAM. Así que, en total, tu API consumirá **4 GB de RAM**. + +Y si tu servidor remoto o máquina virtual solo tiene 3 GB de RAM, intentar cargar más de 4 GB de RAM causará problemas. 🚨 + +### Múltiples Procesos - Un Ejemplo + +En este ejemplo, hay un **Proceso Administrador** que inicia y controla dos **Worker Processes**. + +Este Proceso Administrador probablemente sería el que escuche en el **puerto** en la IP. Y transmitirá toda la comunicación a los worker processes. + +Esos worker processes serían los que ejecutan tu aplicación, realizarían los cálculos principales para recibir un **request** y devolver un **response**, y cargarían cualquier cosa que pongas en variables en RAM. + + + +Y por supuesto, la misma máquina probablemente tendría **otros procesos** ejecutándose también, aparte de tu aplicación. + +Un detalle interesante es que el porcentaje de **CPU utilizado** por cada proceso puede **variar** mucho con el tiempo, pero la **memoria (RAM)** normalmente permanece más o menos **estable**. + +Si tienes una API que hace una cantidad comparable de cálculos cada vez y tienes muchos clientes, entonces la **utilización de CPU** probablemente *también sea estable* (en lugar de constantemente subir y bajar rápidamente). + +### Ejemplos de Herramientas y Estrategias de Replicación + +Puede haber varios enfoques para lograr esto, y te contaré más sobre estrategias específicas en los próximos capítulos, por ejemplo, al hablar sobre Docker y contenedores. + +La principal restricción a considerar es que tiene que haber un **componente único** manejando el **puerto** en la **IP pública**. Y luego debe tener una forma de **transmitir** la comunicación a los **procesos/workers** replicados. + +Aquí hay algunas combinaciones y estrategias posibles: + +* **Uvicorn** con `--workers` + * Un administrador de procesos de Uvicorn **escucharía** en la **IP** y **puerto**, y iniciaría **múltiples worker processes de Uvicorn**. +* **Kubernetes** y otros sistemas de **contenedor distribuidos** + * Algo en la capa de **Kubernetes** escucharía en la **IP** y **puerto**. La replicación sería al tener **múltiples contenedores**, cada uno con **un proceso de Uvicorn** ejecutándose. +* **Servicios en la Nube** que manejan esto por ti + * El servicio en la nube probablemente **manejará la replicación por ti**. Posiblemente te permitiría definir **un proceso para ejecutar**, o una **imagen de contenedor** para usar, en cualquier caso, lo más probable es que sería **un solo proceso de Uvicorn**, y el servicio en la nube se encargaría de replicarlo. + +/// tip | Consejo + +No te preocupes si algunos de estos elementos sobre **contenedores**, Docker, o Kubernetes no tienen mucho sentido todavía. + +Te contaré más sobre imágenes de contenedores, Docker, Kubernetes, etc. en un capítulo futuro: [FastAPI en Contenedores - Docker](docker.md){.internal-link target=_blank}. + +/// + +## Pasos Previos Antes de Iniciar + +Hay muchos casos en los que quieres realizar algunos pasos **antes de iniciar** tu aplicación. + +Por ejemplo, podrías querer ejecutar **migraciones de base de datos**. + +Pero en la mayoría de los casos, querrás realizar estos pasos solo **una vez**. + +Así que, querrás tener un **único proceso** para realizar esos **pasos previos**, antes de iniciar la aplicación. + +Y tendrás que asegurarte de que sea un único proceso ejecutando esos pasos previos incluso si después, inicias **múltiples procesos** (múltiples workers) para la propia aplicación. Si esos pasos fueran ejecutados por **múltiples procesos**, **duplicarían** el trabajo al ejecutarlo en **paralelo**, y si los pasos fueran algo delicado como una migración de base de datos, podrían causar conflictos entre sí. + +Por supuesto, hay algunos casos en los que no hay problema en ejecutar los pasos previos múltiples veces, en ese caso, es mucho más fácil de manejar. + +/// tip | Consejo + +También, ten en cuenta que dependiendo de tu configuración, en algunos casos **quizás ni siquiera necesites realizar pasos previos** antes de iniciar tu aplicación. + +En ese caso, no tendrías que preocuparte por nada de esto. 🤷 + +/// + +### Ejemplos de Estrategias para Pasos Previos + +Esto **dependerá mucho** de la forma en que **implementarás tu sistema**, y probablemente estará conectado con la forma en que inicias programas, manejas reinicios, etc. + +Aquí hay algunas ideas posibles: + +* Un "Contenedor de Inicio" en Kubernetes que se ejecuta antes de tu contenedor de aplicación +* Un script de bash que ejecuta los pasos previos y luego inicia tu aplicación + * Aún necesitarías una forma de iniciar/reiniciar *ese* script de bash, detectar errores, etc. + +/// tip | Consejo + +Te daré más ejemplos concretos para hacer esto con contenedores en un capítulo futuro: [FastAPI en Contenedores - Docker](docker.md){.internal-link target=_blank}. + +/// + +## Utilización de Recursos + +Tu(s) servidor(es) es(son) un **recurso** que puedes consumir o **utilizar**, con tus programas, el tiempo de cómputo en las CPUs y la memoria RAM disponible. + +¿Cuánto de los recursos del sistema quieres consumir/utilizar? Podría ser fácil pensar "no mucho", pero en realidad, probablemente querrás consumir **lo más posible sin colapsar**. + +Si estás pagando por 3 servidores pero solo estás usando un poquito de su RAM y CPU, probablemente estés **desperdiciando dinero** 💸, y probablemente **desperdiciando la energía eléctrica del servidor** 🌎, etc. + +En ese caso, podría ser mejor tener solo 2 servidores y usar un mayor porcentaje de sus recursos (CPU, memoria, disco, ancho de banda de red, etc.). + +Por otro lado, si tienes 2 servidores y estás usando **100% de su CPU y RAM**, en algún momento un proceso pedirá más memoria y el servidor tendrá que usar el disco como "memoria" (lo cual puede ser miles de veces más lento), o incluso **colapsar**. O un proceso podría necesitar hacer algún cálculo y tendría que esperar hasta que la CPU esté libre de nuevo. + +En este caso, sería mejor obtener **un servidor extra** y ejecutar algunos procesos en él para que todos tengan **suficiente RAM y tiempo de CPU**. + +También existe la posibilidad de que, por alguna razón, tengas un **pico** de uso de tu API. Tal vez se volvió viral, o tal vez otros servicios o bots comienzan a usarla. Y podrías querer tener recursos extra para estar a salvo en esos casos. + +Podrías establecer un **número arbitrario** para alcanzar, por ejemplo, algo **entre 50% a 90%** de utilización de recursos. El punto es que esas son probablemente las principales cosas que querrás medir y usar para ajustar tus implementaciones. + +Puedes usar herramientas simples como `htop` para ver la CPU y RAM utilizadas en tu servidor o la cantidad utilizada por cada proceso. O puedes usar herramientas de monitoreo más complejas, que pueden estar distribuidas a través de servidores, etc. + +## Resumen + +Has estado leyendo aquí algunos de los conceptos principales que probablemente necesitarás tener en mente al decidir cómo implementar tu aplicación: + +* Seguridad - HTTPS +* Ejecución al iniciar +* Reinicios +* Replicación (la cantidad de procesos en ejecución) +* Memoria +* Pasos previos antes de iniciar + +Comprender estas ideas y cómo aplicarlas debería darte la intuición necesaria para tomar decisiones al configurar y ajustar tus implementaciones. 🤓 + +En las próximas secciones, te daré ejemplos más concretos de posibles estrategias que puedes seguir. 🚀 diff --git a/docs/es/docs/deployment/docker.md b/docs/es/docs/deployment/docker.md new file mode 100644 index 000000000..ff204f078 --- /dev/null +++ b/docs/es/docs/deployment/docker.md @@ -0,0 +1,620 @@ +# FastAPI en Contenedores - Docker + +Al desplegar aplicaciones de FastAPI, un enfoque común es construir una **imagen de contenedor de Linux**. Normalmente se realiza usando **Docker**. Luego puedes desplegar esa imagen de contenedor de varias formas. + +Usar contenedores de Linux tiene varias ventajas, incluyendo **seguridad**, **replicabilidad**, **simplicidad**, y otras. + +/// tip | Consejo + +¿Tienes prisa y ya conoces esto? Salta al [`Dockerfile` más abajo 👇](#build-a-docker-image-for-fastapi). + +/// + +
+Vista previa del Dockerfile 👀 + +```Dockerfile +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +COPY ./app /code/app + +CMD ["fastapi", "run", "app/main.py", "--port", "80"] + +# Si estás detrás de un proxy como Nginx o Traefik añade --proxy-headers +# CMD ["fastapi", "run", "app/main.py", "--port", "80", "--proxy-headers"] +``` + +
+ +## Qué es un Contenedor + +Los contenedores (principalmente contenedores de Linux) son una forma muy **ligera** de empaquetar aplicaciones incluyendo todas sus dependencias y archivos necesarios, manteniéndolos aislados de otros contenedores (otras aplicaciones o componentes) en el mismo sistema. + +Los contenedores de Linux se ejecutan utilizando el mismo núcleo de Linux del host (máquina, máquina virtual, servidor en la nube, etc.). Esto significa que son muy ligeros (en comparación con las máquinas virtuales completas que emulan un sistema operativo completo). + +De esta forma, los contenedores consumen **pocos recursos**, una cantidad comparable a ejecutar los procesos directamente (una máquina virtual consumiría mucho más). + +Los contenedores también tienen sus propios procesos de ejecución **aislados** (normalmente solo un proceso), sistema de archivos y red, simplificando el despliegue, la seguridad, el desarrollo, etc. + +## Qué es una Imagen de Contenedor + +Un **contenedor** se ejecuta desde una **imagen de contenedor**. + +Una imagen de contenedor es una versión **estática** de todos los archivos, variables de entorno y el comando/programa por defecto que debería estar presente en un contenedor. **Estático** aquí significa que la imagen de contenedor **no se está ejecutando**, no está siendo ejecutada, son solo los archivos empaquetados y los metadatos. + +En contraste con una "**imagen de contenedor**" que son los contenidos estáticos almacenados, un "**contenedor**" normalmente se refiere a la instance en ejecución, lo que está siendo **ejecutado**. + +Cuando el **contenedor** se inicia y está en funcionamiento (iniciado a partir de una **imagen de contenedor**), puede crear o cambiar archivos, variables de entorno, etc. Esos cambios existirán solo en ese contenedor, pero no persistirán en la imagen de contenedor subyacente (no se guardarán en disco). + +Una imagen de contenedor es comparable al archivo de **programa** y sus contenidos, por ejemplo, `python` y algún archivo `main.py`. + +Y el **contenedor** en sí (en contraste con la **imagen de contenedor**) es la instance real en ejecución de la imagen, comparable a un **proceso**. De hecho, un contenedor solo se está ejecutando cuando tiene un **proceso en ejecución** (y normalmente es solo un proceso). El contenedor se detiene cuando no hay un proceso en ejecución en él. + +## Imágenes de Contenedor + +Docker ha sido una de las herramientas principales para crear y gestionar **imágenes de contenedor** y **contenedores**. + +Y hay un Docker Hub público con **imágenes de contenedores oficiales** pre-hechas para muchas herramientas, entornos, bases de datos y aplicaciones. + +Por ejemplo, hay una Imagen de Python oficial. + +Y hay muchas otras imágenes para diferentes cosas como bases de datos, por ejemplo para: + +* PostgreSQL +* MySQL +* MongoDB +* Redis, etc. + +Usando una imagen de contenedor pre-hecha es muy fácil **combinar** y utilizar diferentes herramientas. Por ejemplo, para probar una nueva base de datos. En la mayoría de los casos, puedes usar las **imágenes oficiales**, y simplemente configurarlas con variables de entorno. + +De esta manera, en muchos casos puedes aprender sobre contenedores y Docker y reutilizar ese conocimiento con muchas herramientas y componentes diferentes. + +Así, ejecutarías **múltiples contenedores** con diferentes cosas, como una base de datos, una aplicación de Python, un servidor web con una aplicación frontend en React, y conectarlos entre sí a través de su red interna. + +Todos los sistemas de gestión de contenedores (como Docker o Kubernetes) tienen estas características de redes integradas en ellos. + +## Contenedores y Procesos + +Una **imagen de contenedor** normalmente incluye en sus metadatos el programa o comando por defecto que debería ser ejecutado cuando el **contenedor** se inicie y los parámetros que deben pasar a ese programa. Muy similar a lo que sería si estuviera en la línea de comandos. + +Cuando un **contenedor** se inicia, ejecutará ese comando/programa (aunque puedes sobrescribirlo y hacer que ejecute un comando/programa diferente). + +Un contenedor está en ejecución mientras el **proceso principal** (comando o programa) esté en ejecución. + +Un contenedor normalmente tiene un **proceso único**, pero también es posible iniciar subprocesos desde el proceso principal, y de esa manera tendrás **múltiples procesos** en el mismo contenedor. + +Pero no es posible tener un contenedor en ejecución sin **al menos un proceso en ejecución**. Si el proceso principal se detiene, el contenedor se detiene. + +## Construir una Imagen de Docker para FastAPI + +¡Bien, construyamos algo ahora! 🚀 + +Te mostraré cómo construir una **imagen de Docker** para FastAPI **desde cero**, basada en la imagen **oficial de Python**. + +Esto es lo que querrías hacer en **la mayoría de los casos**, por ejemplo: + +* Usando **Kubernetes** o herramientas similares +* Al ejecutar en un **Raspberry Pi** +* Usando un servicio en la nube que ejecutaría una imagen de contenedor por ti, etc. + +### Requisitos del Paquete + +Normalmente tendrías los **requisitos del paquete** para tu aplicación en algún archivo. + +Dependería principalmente de la herramienta que uses para **instalar** esos requisitos. + +La forma más común de hacerlo es tener un archivo `requirements.txt` con los nombres de los paquetes y sus versiones, uno por línea. + +Por supuesto, usarías las mismas ideas que leíste en [Acerca de las versiones de FastAPI](versions.md){.internal-link target=_blank} para establecer los rangos de versiones. + +Por ejemplo, tu `requirements.txt` podría verse así: + +``` +fastapi[standard]>=0.113.0,<0.114.0 +pydantic>=2.7.0,<3.0.0 +``` + +Y normalmente instalarías esas dependencias de los paquetes con `pip`, por ejemplo: + +
+ +```console +$ pip install -r requirements.txt +---> 100% +Successfully installed fastapi pydantic +``` + +
+ +/// info | Información + +Existen otros formatos y herramientas para definir e instalar dependencias de paquetes. + +/// + +### Crear el Código de **FastAPI** + +* Crea un directorio `app` y entra en él. +* Crea un archivo vacío `__init__.py`. +* Crea un archivo `main.py` con: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +### Dockerfile + +Ahora, en el mismo directorio del proyecto, crea un archivo `Dockerfile` con: + +```{ .dockerfile .annotate } +# (1)! +FROM python:3.9 + +# (2)! +WORKDIR /code + +# (3)! +COPY ./requirements.txt /code/requirements.txt + +# (4)! +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (5)! +COPY ./app /code/app + +# (6)! +CMD ["fastapi", "run", "app/main.py", "--port", "80"] +``` + +1. Comenzar desde la imagen base oficial de Python. + +2. Establecer el directorio de trabajo actual a `/code`. + + Aquí es donde pondremos el archivo `requirements.txt` y el directorio `app`. + +3. Copiar el archivo con los requisitos al directorio `/code`. + + Copiar **solo** el archivo con los requisitos primero, no el resto del código. + + Como este archivo **no cambia a menudo**, Docker lo detectará y usará la **caché** para este paso, habilitando la caché para el siguiente paso también. + +4. Instalar las dependencias de los paquetes en el archivo de requisitos. + + La opción `--no-cache-dir` le dice a `pip` que no guarde los paquetes descargados localmente, ya que eso solo sería si `pip` fuese a ejecutarse de nuevo para instalar los mismos paquetes, pero ese no es el caso al trabajar con contenedores. + + /// note | Nota + + El `--no-cache-dir` está relacionado solo con `pip`, no tiene nada que ver con Docker o contenedores. + + /// + + La opción `--upgrade` le dice a `pip` que actualice los paquetes si ya están instalados. + + Debido a que el paso anterior de copiar el archivo podría ser detectado por la **caché de Docker**, este paso también **usará la caché de Docker** cuando esté disponible. + + Usar la caché en este paso te **ahorrará** mucho **tiempo** al construir la imagen una y otra vez durante el desarrollo, en lugar de **descargar e instalar** todas las dependencias **cada vez**. + +5. Copiar el directorio `./app` dentro del directorio `/code`. + + Como esto contiene todo el código, que es lo que **cambia con más frecuencia**, la **caché de Docker** no se utilizará para este u otros **pasos siguientes** fácilmente. + + Así que es importante poner esto **cerca del final** del `Dockerfile`, para optimizar los tiempos de construcción de la imagen del contenedor. + +6. Establecer el **comando** para usar `fastapi run`, que utiliza Uvicorn debajo. + + `CMD` toma una lista de cadenas, cada una de estas cadenas es lo que escribirías en la línea de comandos separado por espacios. + + Este comando se ejecutará desde el **directorio de trabajo actual**, el mismo directorio `/code` que estableciste antes con `WORKDIR /code`. + +/// tip | Consejo + +Revisa qué hace cada línea haciendo clic en cada número en la burbuja del código. 👆 + +/// + +/// warning | Advertencia + +Asegúrate de **siempre** usar la **forma exec** de la instrucción `CMD`, como se explica a continuación. + +/// + +#### Usar `CMD` - Forma Exec + +La instrucción Docker `CMD` se puede escribir usando dos formas: + +✅ **Forma Exec**: + +```Dockerfile +# ✅ Haz esto +CMD ["fastapi", "run", "app/main.py", "--port", "80"] +``` + +⛔️ **Forma Shell**: + +```Dockerfile +# ⛔️ No hagas esto +CMD fastapi run app/main.py --port 80 +``` + +Asegúrate de siempre usar la **forma exec** para garantizar que FastAPI pueda cerrarse de manera adecuada y que [los eventos de lifespan](../advanced/events.md){.internal-link target=_blank} sean disparados. + +Puedes leer más sobre esto en las documentación de Docker para formas de shell y exec. + +Esto puede ser bastante notorio al usar `docker compose`. Consulta esta sección de preguntas frecuentes de Docker Compose para más detalles técnicos: ¿Por qué mis servicios tardan 10 segundos en recrearse o detenerse?. + +#### Estructura de Directorios + +Ahora deberías tener una estructura de directorios como: + +``` +. +├── app +│ ├── __init__.py +│ └── main.py +├── Dockerfile +└── requirements.txt +``` + +#### Detrás de un Proxy de Terminación TLS + +Si estás ejecutando tu contenedor detrás de un Proxy de Terminación TLS (load balancer) como Nginx o Traefik, añade la opción `--proxy-headers`, esto le dirá a Uvicorn (a través de la CLI de FastAPI) que confíe en los headers enviados por ese proxy indicando que la aplicación se está ejecutando detrás de HTTPS, etc. + +```Dockerfile +CMD ["fastapi", "run", "app/main.py", "--proxy-headers", "--port", "80"] +``` + +#### Cache de Docker + +Hay un truco importante en este `Dockerfile`, primero copiamos **el archivo con las dependencias solo**, no el resto del código. Déjame decirte por qué es así. + +```Dockerfile +COPY ./requirements.txt /code/requirements.txt +``` + +Docker y otras herramientas **construyen** estas imágenes de contenedor **incrementalmente**, añadiendo **una capa sobre la otra**, empezando desde la parte superior del `Dockerfile` y añadiendo cualquier archivo creado por cada una de las instrucciones del `Dockerfile`. + +Docker y herramientas similares también usan una **caché interna** al construir la imagen, si un archivo no ha cambiado desde la última vez que se construyó la imagen del contenedor, entonces reutilizará la misma capa creada la última vez, en lugar de copiar el archivo de nuevo y crear una nueva capa desde cero. + +Solo evitar copiar archivos no mejora necesariamente las cosas mucho, pero porque se usó la caché para ese paso, puede **usar la caché para el siguiente paso**. Por ejemplo, podría usar la caché para la instrucción que instala las dependencias con: + +```Dockerfile +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt +``` + +El archivo con los requisitos de los paquetes **no cambiará con frecuencia**. Así que, al copiar solo ese archivo, Docker podrá **usar la caché** para ese paso. + +Y luego, Docker podrá **usar la caché para el siguiente paso** que descarga e instala esas dependencias. Y aquí es donde **ahorramos mucho tiempo**. ✨ ...y evitamos el aburrimiento de esperar. 😪😆 + +Descargar e instalar las dependencias de los paquetes **podría llevar minutos**, pero usando la **caché** tomaría **segundos** como máximo. + +Y como estarías construyendo la imagen del contenedor una y otra vez durante el desarrollo para comprobar que los cambios en tu código funcionan, hay una gran cantidad de tiempo acumulado que te ahorrarías. + +Luego, cerca del final del `Dockerfile`, copiamos todo el código. Como esto es lo que **cambia con más frecuencia**, lo ponemos cerca del final, porque casi siempre, cualquier cosa después de este paso no podrá usar la caché. + +```Dockerfile +COPY ./app /code/app +``` + +### Construir la Imagen de Docker + +Ahora que todos los archivos están en su lugar, vamos a construir la imagen del contenedor. + +* Ve al directorio del proyecto (donde está tu `Dockerfile`, conteniendo tu directorio `app`). +* Construye tu imagen de FastAPI: + +
+ +```console +$ docker build -t myimage . + +---> 100% +``` + +
+ +/// tip | Consejo + +Fíjate en el `.` al final, es equivalente a `./`, le indica a Docker el directorio a usar para construir la imagen del contenedor. + +En este caso, es el mismo directorio actual (`.`). + +/// + +### Iniciar el Contenedor Docker + +* Ejecuta un contenedor basado en tu imagen: + +
+ +```console +$ docker run -d --name mycontainer -p 80:80 myimage +``` + +
+ +## Revísalo + +Deberías poder revisarlo en la URL de tu contenedor de Docker, por ejemplo: http://192.168.99.100/items/5?q=somequery o http://127.0.0.1/items/5?q=somequery (o equivalente, usando tu host de Docker). + +Verás algo como: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +## Documentación Interactiva de la API + +Ahora puedes ir a http://192.168.99.100/docs o http://127.0.0.1/docs (o equivalente, usando tu host de Docker). + +Verás la documentación interactiva automática de la API (proporcionada por Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +## Documentación Alternativa de la API + +Y también puedes ir a http://192.168.99.100/redoc o http://127.0.0.1/redoc (o equivalente, usando tu host de Docker). + +Verás la documentación alternativa automática (proporcionada por ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Construir una Imagen de Docker con un FastAPI de Un Solo Archivo + +Si tu FastAPI es un solo archivo, por ejemplo, `main.py` sin un directorio `./app`, tu estructura de archivos podría verse así: + +``` +. +├── Dockerfile +├── main.py +└── requirements.txt +``` + +Entonces solo tendrías que cambiar las rutas correspondientes para copiar el archivo dentro del `Dockerfile`: + +```{ .dockerfile .annotate hl_lines="10 13" } +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (1)! +COPY ./main.py /code/ + +# (2)! +CMD ["fastapi", "run", "main.py", "--port", "80"] +``` + +1. Copia el archivo `main.py` directamente al directorio `/code` (sin ningún directorio `./app`). + +2. Usa `fastapi run` para servir tu aplicación en el archivo único `main.py`. + +Cuando pasas el archivo a `fastapi run`, detectará automáticamente que es un archivo único y no parte de un paquete y sabrá cómo importarlo y servir tu aplicación FastAPI. 😎 + +## Conceptos de Despliegue + +Hablemos nuevamente de algunos de los mismos [Conceptos de Despliegue](concepts.md){.internal-link target=_blank} en términos de contenedores. + +Los contenedores son principalmente una herramienta para simplificar el proceso de **construcción y despliegue** de una aplicación, pero no imponen un enfoque particular para manejar estos **conceptos de despliegue**, y hay varias estrategias posibles. + +La **buena noticia** es que con cada estrategia diferente hay una forma de cubrir todos los conceptos de despliegue. 🎉 + +Revisemos estos **conceptos de despliegue** en términos de contenedores: + +* HTTPS +* Ejecutar en el inicio +* Reinicios +* Replicación (el número de procesos en ejecución) +* Memoria +* Pasos previos antes de comenzar + +## HTTPS + +Si nos enfocamos solo en la **imagen de contenedor** para una aplicación FastAPI (y luego el **contenedor** en ejecución), HTTPS normalmente sería manejado **externamente** por otra herramienta. + +Podría ser otro contenedor, por ejemplo, con Traefik, manejando **HTTPS** y la adquisición **automática** de **certificados**. + +/// tip | Consejo + +Traefik tiene integraciones con Docker, Kubernetes, y otros, por lo que es muy fácil configurar y configurar HTTPS para tus contenedores con él. + +/// + +Alternativamente, HTTPS podría ser manejado por un proveedor de la nube como uno de sus servicios (mientras que la aplicación aún se ejecuta en un contenedor). + +## Ejecutar en el Inicio y Reinicios + +Normalmente hay otra herramienta encargada de **iniciar y ejecutar** tu contenedor. + +Podría ser **Docker** directamente, **Docker Compose**, **Kubernetes**, un **servicio en la nube**, etc. + +En la mayoría (o todas) de las casos, hay una opción sencilla para habilitar la ejecución del contenedor al inicio y habilitar los reinicios en caso de fallos. Por ejemplo, en Docker, es la opción de línea de comandos `--restart`. + +Sin usar contenedores, hacer que las aplicaciones se ejecuten al inicio y con reinicios puede ser engorroso y difícil. Pero al **trabajar con contenedores** en la mayoría de los casos, esa funcionalidad se incluye por defecto. ✨ + +## Replicación - Número de Procesos + +Si tienes un cluster de máquinas con **Kubernetes**, Docker Swarm Mode, Nomad, u otro sistema complejo similar para gestionar contenedores distribuidos en varias máquinas, entonces probablemente querrás manejar la **replicación** a nivel de **cluster** en lugar de usar un **gestor de procesos** (como Uvicorn con workers) en cada contenedor. + +Uno de esos sistemas de gestión de contenedores distribuidos como Kubernetes normalmente tiene alguna forma integrada de manejar la **replicación de contenedores** mientras aún soporta el **load balancing** para las requests entrantes. Todo a nivel de **cluster**. + +En esos casos, probablemente desearías construir una **imagen de Docker desde cero** como se [explica arriba](#dockerfile), instalando tus dependencias, y ejecutando **un solo proceso de Uvicorn** en lugar de usar múltiples workers de Uvicorn. + +### Load Balancer + +Al usar contenedores, normalmente tendrías algún componente **escuchando en el puerto principal**. Podría posiblemente ser otro contenedor que es también un **Proxy de Terminación TLS** para manejar **HTTPS** o alguna herramienta similar. + +Como este componente tomaría la **carga** de las requests y las distribuiría entre los workers de una manera (esperablemente) **balanceada**, también se le llama comúnmente **Load Balancer**. + +/// tip | Consejo + +El mismo componente **Proxy de Terminación TLS** usado para HTTPS probablemente también sería un **Load Balancer**. + +/// + +Y al trabajar con contenedores, el mismo sistema que usas para iniciarlos y gestionarlos ya tendría herramientas internas para transmitir la **comunicación en red** (e.g., requests HTTP) desde ese **load balancer** (que también podría ser un **Proxy de Terminación TLS**) a los contenedores con tu aplicación. + +### Un Load Balancer - Múltiples Contenedores Worker + +Al trabajar con **Kubernetes** u otros sistemas de gestión de contenedores distribuidos similares, usar sus mecanismos de red internos permitiría que el único **load balancer** que está escuchando en el **puerto** principal transmita la comunicación (requests) a posiblemente **múltiples contenedores** ejecutando tu aplicación. + +Cada uno de estos contenedores ejecutando tu aplicación normalmente tendría **solo un proceso** (e.g., un proceso Uvicorn ejecutando tu aplicación FastAPI). Todos serían **contenedores idénticos**, ejecutando lo mismo, pero cada uno con su propio proceso, memoria, etc. De esa forma, aprovecharías la **paralelización** en **diferentes núcleos** de la CPU, o incluso en **diferentes máquinas**. + +Y el sistema de contenedores distribuido con el **load balancer** **distribuiría las requests** a cada uno de los contenedores **replicados** que ejecutan tu aplicación **en turnos**. Así, cada request podría ser manejado por uno de los múltiples **contenedores replicados** ejecutando tu aplicación. + +Y normalmente este **load balancer** podría manejar requests que vayan a *otras* aplicaciones en tu cluster (p. ej., a un dominio diferente, o bajo un prefijo de ruta de URL diferente), y transmitiría esa comunicación a los contenedores correctos para *esa otra* aplicación ejecutándose en tu cluster. + +### Un Proceso por Contenedor + +En este tipo de escenario, probablemente querrías tener **un solo proceso (Uvicorn) por contenedor**, ya que ya estarías manejando la replicación a nivel de cluster. + +Así que, en este caso, **no** querrías tener múltiples workers en el contenedor, por ejemplo, con la opción de línea de comandos `--workers`. Querrías tener solo un **proceso Uvicorn por contenedor** (pero probablemente múltiples contenedores). + +Tener otro gestor de procesos dentro del contenedor (como sería con múltiples workers) solo añadiría **complejidad innecesaria** que probablemente ya estés manejando con tu sistema de cluster. + +### Contenedores con Múltiples Procesos y Casos Especiales + +Por supuesto, hay **casos especiales** donde podrías querer tener **un contenedor** con varios **worker processes de Uvicorn** dentro. + +En esos casos, puedes usar la opción de línea de comandos `--workers` para establecer el número de workers que deseas ejecutar: + +```{ .dockerfile .annotate } +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +COPY ./app /code/app + +# (1)! +CMD ["fastapi", "run", "app/main.py", "--port", "80", "--workers", "4"] +``` + +1. Aquí usamos la opción de línea de comandos `--workers` para establecer el número de workers a 4. + +Aquí hay algunos ejemplos de cuándo eso podría tener sentido: + +#### Una Aplicación Simple + +Podrías querer un gestor de procesos en el contenedor si tu aplicación es **lo suficientemente simple** que pueda ejecutarse en un **servidor único**, no un cluster. + +#### Docker Compose + +Podrías estar desplegando en un **servidor único** (no un cluster) con **Docker Compose**, por lo que no tendrías una forma fácil de gestionar la replicación de contenedores (con Docker Compose) mientras se preserva la red compartida y el **load balancing**. + +Entonces podrías querer tener **un solo contenedor** con un **gestor de procesos** iniciando **varios worker processes** dentro. + +--- + +El punto principal es que, **ninguna** de estas son **reglas escritas en piedra** que debas seguir a ciegas. Puedes usar estas ideas para **evaluar tu propio caso de uso** y decidir cuál es el mejor enfoque para tu sistema, verificando cómo gestionar los conceptos de: + +* Seguridad - HTTPS +* Ejecutar en el inicio +* Reinicios +* Replicación (el número de procesos en ejecución) +* Memoria +* Pasos previos antes de comenzar + +## Memoria + +Si ejecutas **un solo proceso por contenedor**, tendrás una cantidad de memoria más o menos bien definida, estable y limitada consumida por cada uno de esos contenedores (más de uno si están replicados). + +Y luego puedes establecer esos mismos límites de memoria y requisitos en tus configuraciones para tu sistema de gestión de contenedores (por ejemplo, en **Kubernetes**). De esa manera, podrá **replicar los contenedores** en las **máquinas disponibles** teniendo en cuenta la cantidad de memoria necesaria por ellos, y la cantidad disponible en las máquinas en el cluster. + +Si tu aplicación es **simple**, probablemente esto **no será un problema**, y puede que no necesites especificar límites de memoria estrictos. Pero si estás **usando mucha memoria** (por ejemplo, con modelos de **Machine Learning**), deberías verificar cuánta memoria estás consumiendo y ajustar el **número de contenedores** que se ejecutan en **cada máquina** (y tal vez agregar más máquinas a tu cluster). + +Si ejecutas **múltiples procesos por contenedor**, tendrás que asegurarte de que el número de procesos iniciados no **consuma más memoria** de la que está disponible. + +## Pasos Previos Antes de Comenzar y Contenedores + +Si estás usando contenedores (por ejemplo, Docker, Kubernetes), entonces hay dos enfoques principales que puedes usar. + +### Múltiples Contenedores + +Si tienes **múltiples contenedores**, probablemente cada uno ejecutando un **proceso único** (por ejemplo, en un cluster de **Kubernetes**), entonces probablemente querrías tener un **contenedor separado** realizando el trabajo de los **pasos previos** en un solo contenedor, ejecutando un solo proceso, **antes** de ejecutar los contenedores worker replicados. + +/// info | Información + +Si estás usando Kubernetes, probablemente sería un Contenedor de Inicialización. + +/// + +Si en tu caso de uso no hay problema en ejecutar esos pasos previos **múltiples veces en paralelo** (por ejemplo, si no estás ejecutando migraciones de base de datos, sino simplemente verificando si la base de datos está lista), entonces también podrías simplemente ponerlos en cada contenedor justo antes de iniciar el proceso principal. + +### Un Contenedor Único + +Si tienes una configuración simple, con un **contenedor único** que luego inicia múltiples **worker processes** (o también solo un proceso), entonces podrías ejecutar esos pasos previos en el mismo contenedor, justo antes de iniciar el proceso con la aplicación. + +### Imagen Base de Docker + +Solía haber una imagen official de Docker de FastAPI: tiangolo/uvicorn-gunicorn-fastapi. Pero ahora está obsoleta. ⛔️ + +Probablemente **no** deberías usar esta imagen base de Docker (o cualquier otra similar). + +Si estás usando **Kubernetes** (u otros) y ya estás configurando la **replicación** a nivel de cluster, con múltiples **contenedores**. En esos casos, es mejor que **construyas una imagen desde cero** como se describe arriba: [Construir una Imagen de Docker para FastAPI](#build-a-docker-image-for-fastapi). + +Y si necesitas tener múltiples workers, puedes simplemente utilizar la opción de línea de comandos `--workers`. + +/// note | Detalles Técnicos + +La imagen de Docker se creó cuando Uvicorn no soportaba gestionar y reiniciar workers muertos, por lo que era necesario usar Gunicorn con Uvicorn, lo que añadía bastante complejidad, solo para que Gunicorn gestionara y reiniciara los worker processes de Uvicorn. + +Pero ahora que Uvicorn (y el comando `fastapi`) soportan el uso de `--workers`, no hay razón para utilizar una imagen base de Docker en lugar de construir la tuya propia (es prácticamente la misma cantidad de código 😅). + +/// + +## Desplegar la Imagen del Contenedor + +Después de tener una Imagen de Contenedor (Docker) hay varias maneras de desplegarla. + +Por ejemplo: + +* Con **Docker Compose** en un servidor único +* Con un cluster de **Kubernetes** +* Con un cluster de Docker Swarm Mode +* Con otra herramienta como Nomad +* Con un servicio en la nube que tome tu imagen de contenedor y la despliegue + +## Imagen de Docker con `uv` + +Si estás usando uv para instalar y gestionar tu proyecto, puedes seguir su guía de Docker de uv. + +## Resumen + +Usando sistemas de contenedores (por ejemplo, con **Docker** y **Kubernetes**) se vuelve bastante sencillo manejar todos los **conceptos de despliegue**: + +* HTTPS +* Ejecutar en el inicio +* Reinicios +* Replicación (el número de procesos en ejecución) +* Memoria +* Pasos previos antes de comenzar + +En la mayoría de los casos, probablemente no querrás usar ninguna imagen base, y en su lugar **construir una imagen de contenedor desde cero** basada en la imagen oficial de Docker de Python. + +Teniendo en cuenta el **orden** de las instrucciones en el `Dockerfile` y la **caché de Docker** puedes **minimizar los tiempos de construcción**, para maximizar tu productividad (y evitar el aburrimiento). 😎 diff --git a/docs/es/docs/deployment/https.md b/docs/es/docs/deployment/https.md new file mode 100644 index 000000000..f2871ac03 --- /dev/null +++ b/docs/es/docs/deployment/https.md @@ -0,0 +1,199 @@ +# Sobre HTTPS + +Es fácil asumir que HTTPS es algo que simplemente está "activado" o no. + +Pero es mucho más complejo que eso. + +/// tip | Consejo + +Si tienes prisa o no te importa, continúa con las siguientes secciones para ver instrucciones paso a paso para configurar todo con diferentes técnicas. + +/// + +Para **aprender los conceptos básicos de HTTPS**, desde una perspectiva de consumidor, revisa https://howhttps.works/. + +Ahora, desde una **perspectiva de desarrollador**, aquí hay varias cosas a tener en cuenta al pensar en HTTPS: + +* Para HTTPS, **el servidor** necesita **tener "certificados"** generados por un **tercero**. + * Esos certificados en realidad son **adquiridos** del tercero, no "generados". +* Los certificados tienen una **vida útil**. + * Ellos **expiran**. + * Y luego necesitan ser **renovados**, **adquiridos nuevamente** del tercero. +* La encriptación de la conexión ocurre a nivel de **TCP**. + * Esa es una capa **debajo de HTTP**. + * Por lo tanto, el manejo de **certificados y encriptación** se realiza **antes de HTTP**. +* **TCP no sabe acerca de "dominios"**. Solo sobre direcciones IP. + * La información sobre el **dominio específico** solicitado va en los **datos HTTP**. +* Los **certificados HTTPS** "certifican" un **cierto dominio**, pero el protocolo y la encriptación ocurren a nivel de TCP, **antes de saber** con cuál dominio se está tratando. +* **Por defecto**, eso significaría que solo puedes tener **un certificado HTTPS por dirección IP**. + * No importa cuán grande sea tu servidor o qué tan pequeña pueda ser cada aplicación que tengas en él. + * Sin embargo, hay una **solución** para esto. +* Hay una **extensión** para el protocolo **TLS** (el que maneja la encriptación a nivel de TCP, antes de HTTP) llamada **SNI**. + * Esta extensión SNI permite que un solo servidor (con una **sola dirección IP**) tenga **varios certificados HTTPS** y sirva **múltiples dominios/aplicaciones HTTPS**. + * Para que esto funcione, un componente (programa) **único** que se ejecute en el servidor, escuchando en la **dirección IP pública**, debe tener **todos los certificados HTTPS** en el servidor. +* **Después** de obtener una conexión segura, el protocolo de comunicación sigue siendo **HTTP**. + * Los contenidos están **encriptados**, aunque se envién con el **protocolo HTTP**. + +Es una práctica común tener **un programa/servidor HTTP** ejecutándose en el servidor (la máquina, host, etc.) y **gestionando todas las partes de HTTPS**: recibiendo los **requests HTTPS encriptados**, enviando los **requests HTTP desencriptados** a la aplicación HTTP real que se ejecuta en el mismo servidor (la aplicación **FastAPI**, en este caso), tomando el **response HTTP** de la aplicación, **encriptándolo** usando el **certificado HTTPS** adecuado y enviándolo de vuelta al cliente usando **HTTPS**. Este servidor a menudo se llama un **TLS Termination Proxy**. + +Algunas de las opciones que podrías usar como un TLS Termination Proxy son: + +* Traefik (que también puede manejar la renovación de certificados) +* Caddy (que también puede manejar la renovación de certificados) +* Nginx +* HAProxy + +## Let's Encrypt + +Antes de Let's Encrypt, estos **certificados HTTPS** eran vendidos por terceros. + +El proceso para adquirir uno de estos certificados solía ser complicado, requerir bastante papeleo y los certificados eran bastante costosos. + +Pero luego se creó **Let's Encrypt**. + +Es un proyecto de la Linux Foundation. Proporciona **certificados HTTPS de forma gratuita**, de manera automatizada. Estos certificados usan toda la seguridad criptográfica estándar, y tienen una corta duración (aproximadamente 3 meses), por lo que la **seguridad es en realidad mejor** debido a su corta vida útil. + +Los dominios son verificados de manera segura y los certificados se generan automáticamente. Esto también permite automatizar la renovación de estos certificados. + +La idea es automatizar la adquisición y renovación de estos certificados para que puedas tener **HTTPS seguro, gratuito, para siempre**. + +## HTTPS para Desarrolladores + +Aquí tienes un ejemplo de cómo podría ser una API HTTPS, paso a paso, prestando atención principalmente a las ideas importantes para los desarrolladores. + +### Nombre de Dominio + +Probablemente todo comenzaría adquiriendo un **nombre de dominio**. Luego, lo configurarías en un servidor DNS (posiblemente tu mismo proveedor de la nube). + +Probablemente conseguirías un servidor en la nube (una máquina virtual) o algo similar, y tendría una **dirección IP pública** fija. + +En el/los servidor(es) DNS configurarías un registro (un "`A record`") para apuntar **tu dominio** a la **dirección IP pública de tu servidor**. + +Probablemente harías esto solo una vez, la primera vez, al configurar todo. + +/// tip | Consejo + +Esta parte del Nombre de Dominio es mucho antes de HTTPS, pero como todo depende del dominio y la dirección IP, vale la pena mencionarlo aquí. + +/// + +### DNS + +Ahora centrémonos en todas las partes realmente de HTTPS. + +Primero, el navegador consultaría con los **servidores DNS** cuál es la **IP del dominio**, en este caso, `someapp.example.com`. + +Los servidores DNS le dirían al navegador que use una **dirección IP** específica. Esa sería la dirección IP pública utilizada por tu servidor, que configuraste en los servidores DNS. + + + +### Inicio del Handshake TLS + +El navegador luego se comunicaría con esa dirección IP en el **puerto 443** (el puerto HTTPS). + +La primera parte de la comunicación es solo para establecer la conexión entre el cliente y el servidor y decidir las claves criptográficas que usarán, etc. + + + +Esta interacción entre el cliente y el servidor para establecer la conexión TLS se llama **handshake TLS**. + +### TLS con Extensión SNI + +**Solo un proceso** en el servidor puede estar escuchando en un **puerto** específico en una **dirección IP** específica. Podría haber otros procesos escuchando en otros puertos en la misma dirección IP, pero solo uno para cada combinación de dirección IP y puerto. + +TLS (HTTPS) utiliza el puerto específico `443` por defecto. Así que ese es el puerto que necesitaríamos. + +Como solo un proceso puede estar escuchando en este puerto, el proceso que lo haría sería el **TLS Termination Proxy**. + +El TLS Termination Proxy tendría acceso a uno o más **certificados TLS** (certificados HTTPS). + +Usando la **extensión SNI** discutida anteriormente, el TLS Termination Proxy verificaría cuál de los certificados TLS (HTTPS) disponibles debería usar para esta conexión, usando el que coincida con el dominio esperado por el cliente. + +En este caso, usaría el certificado para `someapp.example.com`. + + + +El cliente ya **confía** en la entidad que generó ese certificado TLS (en este caso Let's Encrypt, pero lo veremos más adelante), por lo que puede **verificar** que el certificado sea válido. + +Luego, usando el certificado, el cliente y el TLS Termination Proxy **deciden cómo encriptar** el resto de la **comunicación TCP**. Esto completa la parte de **Handshake TLS**. + +Después de esto, el cliente y el servidor tienen una **conexión TCP encriptada**, esto es lo que proporciona TLS. Y luego pueden usar esa conexión para iniciar la comunicación **HTTP real**. + +Y eso es lo que es **HTTPS**, es simplemente HTTP simple **dentro de una conexión TLS segura** en lugar de una conexión TCP pura (sin encriptar). + +/// tip | Consejo + +Ten en cuenta que la encriptación de la comunicación ocurre a nivel de **TCP**, no a nivel de HTTP. + +/// + +### Request HTTPS + +Ahora que el cliente y el servidor (específicamente el navegador y el TLS Termination Proxy) tienen una **conexión TCP encriptada**, pueden iniciar la **comunicación HTTP**. + +Así que, el cliente envía un **request HTTPS**. Esto es simplemente un request HTTP a través de una conexión TLS encriptada. + + + +### Desencriptar el Request + +El TLS Termination Proxy usaría la encriptación acordada para **desencriptar el request**, y transmitiría el **request HTTP simple (desencriptado)** al proceso que ejecuta la aplicación (por ejemplo, un proceso con Uvicorn ejecutando la aplicación FastAPI). + + + +### Response HTTP + +La aplicación procesaría el request y enviaría un **response HTTP simple (sin encriptar)** al TLS Termination Proxy. + + + +### Response HTTPS + +El TLS Termination Proxy entonces **encriptaría el response** usando la criptografía acordada antes (que comenzó con el certificado para `someapp.example.com`), y lo enviaría de vuelta al navegador. + +Luego, el navegador verificaría que el response sea válido y encriptado con la clave criptográfica correcta, etc. Entonces **desencriptaría el response** y lo procesaría. + + + +El cliente (navegador) sabrá que el response proviene del servidor correcto porque está utilizando la criptografía que acordaron usando el **certificado HTTPS** anteriormente. + +### Múltiples Aplicaciones + +En el mismo servidor (o servidores), podrían haber **múltiples aplicaciones**, por ejemplo, otros programas API o una base de datos. + +Solo un proceso puede estar gestionando la IP y puerto específica (el TLS Termination Proxy en nuestro ejemplo) pero las otras aplicaciones/procesos pueden estar ejecutándose en el/los servidor(es) también, siempre y cuando no intenten usar la misma **combinación de IP pública y puerto**. + + + +De esa manera, el TLS Termination Proxy podría gestionar HTTPS y certificados para **múltiples dominios**, para múltiples aplicaciones, y luego transmitir los requests a la aplicación correcta en cada caso. + +### Renovación de Certificados + +En algún momento en el futuro, cada certificado **expiraría** (alrededor de 3 meses después de haberlo adquirido). + +Y entonces, habría otro programa (en algunos casos es otro programa, en algunos casos podría ser el mismo TLS Termination Proxy) que hablaría con Let's Encrypt y renovaría el/los certificado(s). + + + +Los **certificados TLS** están **asociados con un nombre de dominio**, no con una dirección IP. + +Entonces, para renovar los certificados, el programa de renovación necesita **probar** a la autoridad (Let's Encrypt) que de hecho **"posee" y controla ese dominio**. + +Para hacer eso, y para acomodar diferentes necesidades de aplicaciones, hay varias formas en que puede hacerlo. Algunas formas populares son: + +* **Modificar algunos registros DNS**. + * Para esto, el programa de renovación necesita soportar las API del proveedor de DNS, por lo que, dependiendo del proveedor de DNS que estés utilizando, esto podría o no ser una opción. +* **Ejecutarse como un servidor** (al menos durante el proceso de adquisición del certificado) en la dirección IP pública asociada con el dominio. + * Como dijimos anteriormente, solo un proceso puede estar escuchando en una IP y puerto específicos. + * Esta es una de las razones por las que es muy útil cuando el mismo TLS Termination Proxy también se encarga del proceso de renovación del certificado. + * De lo contrario, podrías tener que detener momentáneamente el TLS Termination Proxy, iniciar el programa de renovación para adquirir los certificados, luego configurarlos con el TLS Termination Proxy, y luego reiniciar el TLS Termination Proxy. Esto no es ideal, ya que tus aplicaciones no estarán disponibles durante el tiempo que el TLS Termination Proxy esté apagado. + +Todo este proceso de renovación, mientras aún se sirve la aplicación, es una de las principales razones por las que querrías tener un **sistema separado para gestionar el HTTPS** con un TLS Termination Proxy en lugar de simplemente usar los certificados TLS con el servidor de aplicaciones directamente (por ejemplo, Uvicorn). + +## Resumen + +Tener **HTTPS** es muy importante y bastante **crítico** en la mayoría de los casos. La mayor parte del esfuerzo que como desarrollador tienes que poner en torno a HTTPS es solo sobre **entender estos conceptos** y cómo funcionan. + +Pero una vez que conoces la información básica de **HTTPS para desarrolladores** puedes combinar y configurar fácilmente diferentes herramientas para ayudarte a gestionar todo de una manera sencilla. + +En algunos de los siguientes capítulos, te mostraré varios ejemplos concretos de cómo configurar **HTTPS** para aplicaciones **FastAPI**. 🔒 diff --git a/docs/es/docs/deployment/manually.md b/docs/es/docs/deployment/manually.md new file mode 100644 index 000000000..509b9ebdb --- /dev/null +++ b/docs/es/docs/deployment/manually.md @@ -0,0 +1,169 @@ +# Ejecutar un Servidor Manualmente + +## Usa el Comando `fastapi run` + +En resumen, usa `fastapi run` para servir tu aplicación FastAPI: + +
+ +```console +$ fastapi run main.py +INFO Usando path main.py +INFO Path absoluto resuelto /home/user/code/awesomeapp/main.py +INFO Buscando una estructura de archivos de paquete desde directorios con archivos __init__.py +INFO Importando desde /home/user/code/awesomeapp + + ╭─ Archivo de módulo de Python ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importando módulo main +INFO Encontrada aplicación FastAPI importable + + ╭─ Aplicación FastAPI importable ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Usando la cadena de import main:app + + ╭─────────── CLI de FastAPI - Modo Producción ───────────╮ + │ │ + │ Sirviendo en: http://0.0.0.0:8000 │ + │ │ + │ Docs de API: http://0.0.0.0:8000/docs │ + │ │ + │ Corriendo en modo producción, para desarrollo usa: │ + │ │ + fastapi dev + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Iniciado el proceso del servidor [2306215] +INFO: Esperando el inicio de la aplicación. +INFO: Inicio de la aplicación completado. +INFO: Uvicorn corriendo en http://0.0.0.0:8000 (Presiona CTRL+C para salir) +``` + +
+ +Eso funcionaría para la mayoría de los casos. 😎 + +Podrías usar ese comando, por ejemplo, para iniciar tu app **FastAPI** en un contenedor, en un servidor, etc. + +## Servidores ASGI + +Vamos a profundizar un poquito en los detalles. + +FastAPI usa un estándar para construir frameworks de web y servidores de Python llamado ASGI. FastAPI es un framework web ASGI. + +Lo principal que necesitas para ejecutar una aplicación **FastAPI** (o cualquier otra aplicación ASGI) en una máquina de servidor remota es un programa de servidor ASGI como **Uvicorn**, que es el que viene por defecto en el comando `fastapi`. + +Hay varias alternativas, incluyendo: + +* Uvicorn: un servidor ASGI de alto rendimiento. +* Hypercorn: un servidor ASGI compatible con HTTP/2 y Trio entre otras funcionalidades. +* Daphne: el servidor ASGI construido para Django Channels. +* Granian: Un servidor HTTP Rust para aplicaciones en Python. +* NGINX Unit: NGINX Unit es un runtime para aplicaciones web ligero y versátil. + +## Máquina Servidor y Programa Servidor + +Hay un pequeño detalle sobre los nombres que hay que tener en cuenta. 💡 + +La palabra "**servidor**" se utiliza comúnmente para referirse tanto al computador remoto/en la nube (la máquina física o virtual) como al programa que se está ejecutando en esa máquina (por ejemplo, Uvicorn). + +Solo ten en cuenta que cuando leas "servidor" en general, podría referirse a una de esas dos cosas. + +Al referirse a la máquina remota, es común llamarla **servidor**, pero también **máquina**, **VM** (máquina virtual), **nodo**. Todos esos se refieren a algún tipo de máquina remota, generalmente con Linux, donde ejecutas programas. + +## Instala el Programa del Servidor + +Cuando instalas FastAPI, viene con un servidor de producción, Uvicorn, y puedes iniciarlo con el comando `fastapi run`. + +Pero también puedes instalar un servidor ASGI manualmente. + +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, actívalo, y luego puedes instalar la aplicación del servidor. + +Por ejemplo, para instalar Uvicorn: + +
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +
+ +Un proceso similar se aplicaría a cualquier otro programa de servidor ASGI. + +/// tip | Consejo + +Al añadir `standard`, Uvicorn instalará y usará algunas dependencias adicionales recomendadas. + +Eso incluye `uvloop`, el reemplazo de alto rendimiento para `asyncio`, que proporciona un gran impulso de rendimiento en concurrencia. + +Cuando instalas FastAPI con algo como `pip install "fastapi[standard]"` ya obtienes `uvicorn[standard]` también. + +/// + +## Ejecuta el Programa del Servidor + +Si instalaste un servidor ASGI manualmente, normalmente necesitarías pasar una cadena de import en un formato especial para que importe tu aplicación FastAPI: + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 + +INFO: Uvicorn corriendo en http://0.0.0.0:80 (Presiona CTRL+C para salir) +``` + +
+ +/// note | Nota + +El comando `uvicorn main:app` se refiere a: + +* `main`: el archivo `main.py` (el "módulo" de Python). +* `app`: el objeto creado dentro de `main.py` con la línea `app = FastAPI()`. + +Es equivalente a: + +```Python +from main import app +``` + +/// + +Cada programa alternativo de servidor ASGI tendría un comando similar, puedes leer más en su respectiva documentación. + +/// warning | Advertencia + +Uvicorn y otros servidores soportan una opción `--reload` que es útil durante el desarrollo. + +La opción `--reload` consume muchos más recursos, es más inestable, etc. + +Ayuda mucho durante el **desarrollo**, pero **no** deberías usarla en **producción**. + +/// + +## Conceptos de Despliegue + +Estos ejemplos ejecutan el programa del servidor (por ejemplo, Uvicorn), iniciando **un solo proceso**, escuchando en todas las IPs (`0.0.0.0`) en un puerto predefinido (por ejemplo, `80`). + +Esta es la idea básica. Pero probablemente querrás encargarte de algunas cosas adicionales, como: + +* Seguridad - HTTPS +* Ejecución en el arranque +* Reinicios +* Replicación (el número de procesos ejecutándose) +* Memoria +* Pasos previos antes de comenzar + +Te contaré más sobre cada uno de estos conceptos, cómo pensarlos, y algunos ejemplos concretos con estrategias para manejarlos en los próximos capítulos. 🚀 diff --git a/docs/es/docs/deployment/server-workers.md b/docs/es/docs/deployment/server-workers.md new file mode 100644 index 000000000..1a1127ca6 --- /dev/null +++ b/docs/es/docs/deployment/server-workers.md @@ -0,0 +1,152 @@ +# Servidores Workers - Uvicorn con Workers + +Vamos a revisar esos conceptos de despliegue de antes: + +* Seguridad - HTTPS +* Ejecución al inicio +* Reinicios +* **Replicación (el número de procesos en ejecución)** +* Memoria +* Pasos previos antes de empezar + +Hasta este punto, con todos los tutoriales en la documentación, probablemente has estado ejecutando un **programa de servidor**, por ejemplo, usando el comando `fastapi`, que ejecuta Uvicorn, corriendo un **solo proceso**. + +Al desplegar aplicaciones probablemente querrás tener algo de **replicación de procesos** para aprovechar **múltiples núcleos** y poder manejar más requests. + +Como viste en el capítulo anterior sobre [Conceptos de Despliegue](concepts.md){.internal-link target=_blank}, hay múltiples estrategias que puedes usar. + +Aquí te mostraré cómo usar **Uvicorn** con **worker processes** usando el comando `fastapi` o el comando `uvicorn` directamente. + +/// info | Información + +Si estás usando contenedores, por ejemplo con Docker o Kubernetes, te contaré más sobre eso en el próximo capítulo: [FastAPI en Contenedores - Docker](docker.md){.internal-link target=_blank}. + +En particular, cuando corras en **Kubernetes** probablemente **no** querrás usar workers y en cambio correr **un solo proceso de Uvicorn por contenedor**, pero te contaré sobre eso más adelante en ese capítulo. + +/// + +## Múltiples Workers + +Puedes iniciar múltiples workers con la opción de línea de comando `--workers`: + +//// tab | `fastapi` + +Si usas el comando `fastapi`: + +
+ +```console +$
 fastapi run --workers 4 main.py
+INFO     Using path main.py
+INFO     Resolved absolute path /home/user/code/awesomeapp/main.py
+INFO     Searching for package file structure from directories with __init__.py files
+INFO     Importing from /home/user/code/awesomeapp
+
+ ╭─ Python module file ─╮
+ │                      │
+ │  🐍 main.py          │
+ │                      │
+ ╰──────────────────────╯
+
+INFO     Importing module main
+INFO     Found importable FastAPI app
+
+ ╭─ Importable FastAPI app ─╮
+ │                          │
+ │  from main import app    │
+ │                          │
+ ╰──────────────────────────╯
+
+INFO     Using import string main:app
+
+ ╭─────────── FastAPI CLI - Production mode ───────────╮
+ │                                                     │
+ │  Serving at: http://0.0.0.0:8000                    │
+ │                                                     │
+ │  API docs: http://0.0.0.0:8000/docs                 │
+ │                                                     │
+ │  Running in production mode, for development use:   │
+ │                                                     │
+ fastapi dev
+ │                                                     │
+ ╰─────────────────────────────────────────────────────╯
+
+INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
+INFO:     Started parent process [27365]
+INFO:     Started server process [27368]
+INFO:     Waiting for application startup.
+INFO:     Application startup complete.
+INFO:     Started server process [27369]
+INFO:     Waiting for application startup.
+INFO:     Application startup complete.
+INFO:     Started server process [27370]
+INFO:     Waiting for application startup.
+INFO:     Application startup complete.
+INFO:     Started server process [27367]
+INFO:     Waiting for application startup.
+INFO:     Application startup complete.
+
+``` + +
+ +//// + +//// tab | `uvicorn` + +Si prefieres usar el comando `uvicorn` directamente: + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 +INFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit) +INFO: Started parent process [27365] +INFO: Started server process [27368] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27369] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27370] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27367] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +//// + +La única opción nueva aquí es `--workers` indicando a Uvicorn que inicie 4 worker processes. + +También puedes ver que muestra el **PID** de cada proceso, `27365` para el proceso padre (este es el **gestor de procesos**) y uno para cada worker process: `27368`, `27369`, `27370`, y `27367`. + +## Conceptos de Despliegue + +Aquí viste cómo usar múltiples **workers** para **paralelizar** la ejecución de la aplicación, aprovechar los **múltiples núcleos** del CPU, y poder servir **más requests**. + +De la lista de conceptos de despliegue de antes, usar workers ayudaría principalmente con la parte de **replicación**, y un poquito con los **reinicios**, pero aún necesitas encargarte de los otros: + +* **Seguridad - HTTPS** +* **Ejecución al inicio** +* ***Reinicios*** +* Replicación (el número de procesos en ejecución) +* **Memoria** +* **Pasos previos antes de empezar** + +## Contenedores y Docker + +En el próximo capítulo sobre [FastAPI en Contenedores - Docker](docker.md){.internal-link target=_blank} te explicaré algunas estrategias que podrías usar para manejar los otros **conceptos de despliegue**. + +Te mostraré cómo **construir tu propia imagen desde cero** para ejecutar un solo proceso de Uvicorn. Es un proceso sencillo y probablemente es lo que querrías hacer al usar un sistema de gestión de contenedores distribuido como **Kubernetes**. + +## Resumen + +Puedes usar múltiples worker processes con la opción CLI `--workers` con los comandos `fastapi` o `uvicorn` para aprovechar los **CPUs de múltiples núcleos**, para ejecutar **múltiples procesos en paralelo**. + +Podrías usar estas herramientas e ideas si estás instalando **tu propio sistema de despliegue** mientras te encargas tú mismo de los otros conceptos de despliegue. + +Revisa el próximo capítulo para aprender sobre **FastAPI** con contenedores (por ejemplo, Docker y Kubernetes). Verás que esas herramientas tienen formas sencillas de resolver los otros **conceptos de despliegue** también. ✨ diff --git a/docs/es/docs/environment-variables.md b/docs/es/docs/environment-variables.md new file mode 100644 index 000000000..8e85b413c --- /dev/null +++ b/docs/es/docs/environment-variables.md @@ -0,0 +1,298 @@ +# Variables de Entorno + +/// tip | Consejo + +Si ya sabes qué son las "variables de entorno" y cómo usarlas, siéntete libre de saltarte esto. + +/// + +Una variable de entorno (también conocida como "**env var**") es una variable que vive **fuera** del código de Python, en el **sistema operativo**, y podría ser leída por tu código de Python (o por otros programas también). + +Las variables de entorno pueden ser útiles para manejar **configuraciones** de aplicaciones, como parte de la **instalación** de Python, etc. + +## Crear y Usar Variables de Entorno + +Puedes **crear** y usar variables de entorno en la **shell (terminal)**, sin necesidad de Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Podrías crear una env var MY_NAME con +$ export MY_NAME="Wade Wilson" + +// Luego podrías usarla con otros programas, como +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Crea una env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Úsala con otros programas, como +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## Leer Variables de Entorno en Python + +También podrías crear variables de entorno **fuera** de Python, en la terminal (o con cualquier otro método), y luego **leerlas en Python**. + +Por ejemplo, podrías tener un archivo `main.py` con: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip | Consejo + +El segundo argumento de `os.getenv()` es el valor por defecto a retornar. + +Si no se proporciona, es `None` por defecto; aquí proporcionamos `"World"` como el valor por defecto para usar. + +/// + +Luego podrías llamar a ese programa Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Aquí todavía no configuramos la env var +$ python main.py + +// Como no configuramos la env var, obtenemos el valor por defecto + +Hello World from Python + +// Pero si creamos una variable de entorno primero +$ export MY_NAME="Wade Wilson" + +// Y luego llamamos al programa nuevamente +$ python main.py + +// Ahora puede leer la variable de entorno + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Aquí todavía no configuramos la env var +$ python main.py + +// Como no configuramos la env var, obtenemos el valor por defecto + +Hello World from Python + +// Pero si creamos una variable de entorno primero +$ $Env:MY_NAME = "Wade Wilson" + +// Y luego llamamos al programa nuevamente +$ python main.py + +// Ahora puede leer la variable de entorno + +Hello Wade Wilson from Python +``` + +
+ +//// + +Dado que las variables de entorno pueden configurarse fuera del código, pero pueden ser leídas por el código, y no tienen que ser almacenadas (committed en `git`) con el resto de los archivos, es común usarlas para configuraciones o **ajustes**. + +También puedes crear una variable de entorno solo para una **invocación específica de un programa**, que está disponible solo para ese programa, y solo durante su duración. + +Para hacer eso, créala justo antes del programa en sí, en la misma línea: + +
+ +```console +// Crea una env var MY_NAME en línea para esta llamada del programa +$ MY_NAME="Wade Wilson" python main.py + +// Ahora puede leer la variable de entorno + +Hello Wade Wilson from Python + +// La env var ya no existe después +$ python main.py + +Hello World from Python +``` + +
+ +/// tip | Consejo + +Puedes leer más al respecto en The Twelve-Factor App: Config. + +/// + +## Tipos y Validación + +Estas variables de entorno solo pueden manejar **strings de texto**, ya que son externas a Python y deben ser compatibles con otros programas y el resto del sistema (e incluso con diferentes sistemas operativos, como Linux, Windows, macOS). + +Esto significa que **cualquier valor** leído en Python desde una variable de entorno **será un `str`**, y cualquier conversión a un tipo diferente o cualquier validación tiene que hacerse en el código. + +Aprenderás más sobre cómo usar variables de entorno para manejar **configuraciones de aplicación** en la [Guía del Usuario Avanzado - Ajustes y Variables de Entorno](./advanced/settings.md){.internal-link target=_blank}. + +## Variable de Entorno `PATH` + +Hay una variable de entorno **especial** llamada **`PATH`** que es utilizada por los sistemas operativos (Linux, macOS, Windows) para encontrar programas a ejecutar. + +El valor de la variable `PATH` es un string largo que consiste en directorios separados por dos puntos `:` en Linux y macOS, y por punto y coma `;` en Windows. + +Por ejemplo, la variable de entorno `PATH` podría verse así: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Esto significa que el sistema debería buscar programas en los directorios: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +Esto significa que el sistema debería buscar programas en los directorios: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +Cuando escribes un **comando** en la terminal, el sistema operativo **busca** el programa en **cada uno de esos directorios** listados en la variable de entorno `PATH`. + +Por ejemplo, cuando escribes `python` en la terminal, el sistema operativo busca un programa llamado `python` en el **primer directorio** de esa lista. + +Si lo encuentra, entonces lo **utilizará**. De lo contrario, continúa buscando en los **otros directorios**. + +### Instalando Python y Actualizando el `PATH` + +Cuando instalas Python, se te podría preguntar si deseas actualizar la variable de entorno `PATH`. + +//// tab | Linux, macOS + +Digamos que instalas Python y termina en un directorio `/opt/custompython/bin`. + +Si dices que sí para actualizar la variable de entorno `PATH`, entonces el instalador añadirá `/opt/custompython/bin` a la variable de entorno `PATH`. + +Podría verse así: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +De esta manera, cuando escribes `python` en la terminal, el sistema encontrará el programa Python en `/opt/custompython/bin` (el último directorio) y usará ese. + +//// + +//// tab | Windows + +Digamos que instalas Python y termina en un directorio `C:\opt\custompython\bin`. + +Si dices que sí para actualizar la variable de entorno `PATH`, entonces el instalador añadirá `C:\opt\custompython\bin` a la variable de entorno `PATH`. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +De esta manera, cuando escribes `python` en la terminal, el sistema encontrará el programa Python en `C:\opt\custompython\bin` (el último directorio) y usará ese. + +//// + +Entonces, si escribes: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +El sistema **encontrará** el programa `python` en `/opt/custompython/bin` y lo ejecutará. + +Esto sería más o menos equivalente a escribir: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +El sistema **encontrará** el programa `python` en `C:\opt\custompython\bin\python` y lo ejecutará. + +Esto sería más o menos equivalente a escribir: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +Esta información será útil al aprender sobre [Entornos Virtuales](virtual-environments.md){.internal-link target=_blank}. + +## Conclusión + +Con esto deberías tener una comprensión básica de qué son las **variables de entorno** y cómo usarlas en Python. + +También puedes leer más sobre ellas en la Wikipedia para Variable de Entorno. + +En muchos casos no es muy obvio cómo las variables de entorno serían útiles y aplicables de inmediato. Pero siguen apareciendo en muchos escenarios diferentes cuando estás desarrollando, así que es bueno conocerlas. + +Por ejemplo, necesitarás esta información en la siguiente sección, sobre [Entornos Virtuales](virtual-environments.md). diff --git a/docs/es/docs/fastapi-cli.md b/docs/es/docs/fastapi-cli.md new file mode 100644 index 000000000..9d7629fdb --- /dev/null +++ b/docs/es/docs/fastapi-cli.md @@ -0,0 +1,75 @@ +# FastAPI CLI + +**FastAPI CLI** es un programa de línea de comandos que puedes usar para servir tu aplicación FastAPI, gestionar tu proyecto FastAPI, y más. + +Cuando instalas FastAPI (por ejemplo, con `pip install "fastapi[standard]"`), incluye un paquete llamado `fastapi-cli`, este paquete proporciona el comando `fastapi` en la terminal. + +Para ejecutar tu aplicación FastAPI en modo de desarrollo, puedes usar el comando `fastapi dev`: + +
+ +```console +$ fastapi dev main.py + + FastAPI Starting development server 🚀 + + Searching for package file structure from directories with + __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with the + following code: + + from main import app + + app Using import string: main:app + + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: + + 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 [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. +``` + +
+ +El programa de línea de comandos llamado `fastapi` es **FastAPI CLI**. + +FastAPI CLI toma el path de tu programa Python (por ejemplo, `main.py`), detecta automáticamente la `FastAPI` instance (comúnmente llamada `app`), determina el proceso de import correcto, y luego la sirve. + +Para producción usarías `fastapi run` en su lugar. 🚀 + +Internamente, **FastAPI CLI** usa Uvicorn, un servidor ASGI de alto rendimiento y listo para producción. 😎 + +## `fastapi dev` + +Ejecutar `fastapi dev` inicia el modo de desarrollo. + +Por defecto, **auto-reload** está habilitado, recargando automáticamente el servidor cuando realizas cambios en tu código. Esto consume muchos recursos y podría ser menos estable que cuando está deshabilitado. Deberías usarlo solo para desarrollo. También escucha en la dirección IP `127.0.0.1`, que es la IP para que tu máquina se comunique solo consigo misma (`localhost`). + +## `fastapi run` + +Ejecutar `fastapi run` inicia FastAPI en modo de producción por defecto. + +Por defecto, **auto-reload** está deshabilitado. También escucha en la dirección IP `0.0.0.0`, lo que significa todas las direcciones IP disponibles, de esta manera será accesible públicamente por cualquiera que pueda comunicarse con la máquina. Esta es la manera en la que normalmente lo ejecutarías en producción, por ejemplo, en un contenedor. + +En la mayoría de los casos tendrías (y deberías) tener un "proxy de terminación" manejando HTTPS por ti, esto dependerá de cómo despliegues tu aplicación, tu proveedor podría hacer esto por ti, o podrías necesitar configurarlo tú mismo. + +/// tip | Consejo + +Puedes aprender más al respecto en la [documentación de despliegue](deployment/index.md){.internal-link target=_blank}. + +/// diff --git a/docs/es/docs/help-fastapi.md b/docs/es/docs/help-fastapi.md new file mode 100644 index 000000000..37f6b927d --- /dev/null +++ b/docs/es/docs/help-fastapi.md @@ -0,0 +1,269 @@ +# Ayuda a FastAPI - Consigue Ayuda + +¿Te gusta **FastAPI**? + +¿Te gustaría ayudar a FastAPI, a otros usuarios y al autor? + +¿O te gustaría conseguir ayuda con **FastAPI**? + +Hay formas muy sencillas de ayudar (varias implican solo uno o dos clics). + +Y también hay varias formas de conseguir ayuda. + +## Suscríbete al boletín + +Puedes suscribirte al (esporádico) boletín [**FastAPI and friends**](newsletter.md){.internal-link target=_blank} para mantenerte al día sobre: + +* Noticias sobre FastAPI y amigos 🚀 +* Guías 📝 +* Funcionalidades ✨ +* Cambios importantes 🚨 +* Consejos y trucos ✅ + +## Sigue a FastAPI en Twitter + +Sigue a @fastapi en **Twitter** para obtener las últimas noticias sobre **FastAPI**. 🐦 + +## Dale una estrella a **FastAPI** en GitHub + +Puedes "darle una estrella" a FastAPI en GitHub (haciendo clic en el botón de estrella en la parte superior derecha): https://github.com/fastapi/fastapi. ⭐️ + +Al agregar una estrella, otros usuarios podrán encontrarlo más fácilmente y ver que ya ha sido útil para otros. + +## Observa el repositorio de GitHub para lanzamientos + +Puedes "observar" FastAPI en GitHub (haciendo clic en el botón "watch" en la parte superior derecha): https://github.com/fastapi/fastapi. 👀 + +Allí puedes seleccionar "Releases only". + +Al hacerlo, recibirás notificaciones (en tu email) cada vez que haya un nuevo lanzamiento (una nueva versión) de **FastAPI** con correcciones de bugs y nuevas funcionalidades. + +## Conéctate con el autor + +Puedes conectar conmigo (Sebastián Ramírez / `tiangolo`), el autor. + +Puedes: + +* Seguirme en **GitHub**. + * Ver otros proyectos de Código Abierto que he creado y que podrían ayudarte. + * Seguirme para ver cuándo creo un nuevo proyecto de Código Abierto. +* Seguirme en **Twitter** o Mastodon. + * Contarme cómo usas FastAPI (me encanta oír eso). + * Enterarte cuando hago anuncios o lanzo nuevas herramientas. + * También puedes seguir @fastapi en Twitter (una cuenta aparte). +* Seguirme en **LinkedIn**. + * Enterarte cuando hago anuncios o lanzo nuevas herramientas (aunque uso Twitter más a menudo 🤷‍♂). +* Leer lo que escribo (o seguirme) en **Dev.to** o **Medium**. + * Leer otras ideas, artículos, y leer sobre las herramientas que he creado. + * Seguirme para leer lo que publico nuevo. + +## Twittea sobre **FastAPI** + +Twittea sobre **FastAPI** y dime a mí y a otros por qué te gusta. 🎉 + +Me encanta escuchar cómo se está utilizando **FastAPI**, qué te ha gustado, en qué proyecto/empresa lo estás usando, etc. + +## Vota por FastAPI + +* Vota por **FastAPI** en Slant. +* Vota por **FastAPI** en AlternativeTo. +* Di que usas **FastAPI** en StackShare. + +## Ayuda a otros con preguntas en GitHub + +Puedes intentar ayudar a otros con sus preguntas en: + +* GitHub Discussions +* GitHub Issues + +En muchos casos, probablemente ya conozcas la respuesta a esas preguntas. 🤓 + +Si estás ayudando mucho a la gente con sus preguntas, te convertirás en un [FastAPI Expert](fastapi-people.md#fastapi-experts){.internal-link target=_blank} oficial. 🎉 + +Solo recuerda, el punto más importante es: trata de ser amable. La gente llega con sus frustraciones y, en muchos casos, no pregunta de la mejor manera, pero haz todo lo posible por ser amable. 🤗 + +La idea es que la comunidad de **FastAPI** sea amable y acogedora. Al mismo tiempo, no aceptes acoso o comportamiento irrespetuoso hacia los demás. Tenemos que cuidarnos unos a otros. + +--- + +Aquí te explico cómo ayudar a otros con preguntas (en discusiones o issues): + +### Entiende la pregunta + +* Revisa si puedes entender cuál es el **propósito** y el caso de uso de la persona que pregunta. + +* Luego revisa si la pregunta (la gran mayoría son preguntas) es **clara**. + +* En muchos casos, la pregunta planteada es sobre una solución imaginaria del usuario, pero podría haber una **mejor**. Si puedes entender mejor el problema y el caso de uso, podrías sugerir una mejor **solución alternativa**. + +* Si no puedes entender la pregunta, pide más **detalles**. + +### Reproduce el problema + +En la mayoría de los casos y preguntas hay algo relacionado con el **código original** de la persona. + +En muchos casos solo copiarán un fragmento del código, pero eso no es suficiente para **reproducir el problema**. + +* Puedes pedirles que proporcionen un ejemplo mínimo, reproducible, que puedas **copiar-pegar** y ejecutar localmente para ver el mismo error o comportamiento que están viendo, o para entender mejor su caso de uso. + +* Si te sientes muy generoso, puedes intentar **crear un ejemplo** así tú mismo, solo basado en la descripción del problema. Solo ten en cuenta que esto podría llevar mucho tiempo y podría ser mejor pedirles que aclaren el problema primero. + +### Sugerir soluciones + +* Después de poder entender la pregunta, puedes darles un posible **respuesta**. + +* En muchos casos, es mejor entender su **problema subyacente o caso de uso**, porque podría haber una mejor manera de resolverlo que lo que están intentando hacer. + +### Pide cerrar + +Si responden, hay una alta probabilidad de que hayas resuelto su problema, felicidades, ¡**eres un héroe**! 🦸 + +* Ahora, si eso resolvió su problema, puedes pedirles que: + + * En GitHub Discussions: marquen el comentario como la **respuesta**. + * En GitHub Issues: **cierren** el issue. + +## Observa el repositorio de GitHub + +Puedes "observar" FastAPI en GitHub (haciendo clic en el botón "watch" en la parte superior derecha): https://github.com/fastapi/fastapi. 👀 + +Si seleccionas "Watching" en lugar de "Releases only", recibirás notificaciones cuando alguien cree un nuevo issue o pregunta. También puedes especificar que solo deseas que te notifiquen sobre nuevos issues, discusiones, PRs, etc. + +Luego puedes intentar ayudarlos a resolver esas preguntas. + +## Haz preguntas + +Puedes crear una nueva pregunta en el repositorio de GitHub, por ejemplo, para: + +* Hacer una **pregunta** o preguntar sobre un **problema**. +* Sugerir una nueva **funcionalidad**. + +**Nota**: si lo haces, entonces te voy a pedir que también ayudes a otros. 😉 + +## Revisa Pull Requests + +Puedes ayudarme a revisar pull requests de otros. + +De nuevo, por favor, haz tu mejor esfuerzo por ser amable. 🤗 + +--- + +Aquí está lo que debes tener en cuenta y cómo revisar un pull request: + +### Entiende el problema + +* Primero, asegúrate de **entender el problema** que el pull request está intentando resolver. Podría tener una discusión más larga en una GitHub Discussion o issue. + +* También hay una buena posibilidad de que el pull request no sea realmente necesario porque el problema se puede resolver de una manera **diferente**. Entonces puedes sugerir o preguntar sobre eso. + +### No te preocupes por el estilo + +* No te preocupes demasiado por cosas como los estilos de los mensajes de commit, yo haré squash y merge personalizando el commit manualmente. + +* Tampoco te preocupes por las reglas de estilo, hay herramientas automatizadas verificando eso. + +Y si hay alguna otra necesidad de estilo o consistencia, pediré directamente eso, o agregaré commits encima con los cambios necesarios. + +### Revisa el código + +* Revisa y lee el código, ve si tiene sentido, **ejecútalo localmente** y ve si realmente resuelve el problema. + +* Luego **comenta** diciendo que hiciste eso, así sabré que realmente lo revisaste. + +/// info | Información + +Desafortunadamente, no puedo simplemente confiar en PRs que solo tienen varias aprobaciones. + +Varias veces ha sucedido que hay PRs con 3, 5 o más aprobaciones, probablemente porque la descripción es atractiva, pero cuando reviso los PRs, en realidad están rotos, tienen un bug, o no resuelven el problema que dicen resolver. 😅 + +Así que, es realmente importante que realmente leas y ejecutes el código, y me hagas saber en los comentarios que lo hiciste. 🤓 + +/// + +* Si el PR se puede simplificar de alguna manera, puedes pedir eso, pero no hay necesidad de ser demasiado exigente, podría haber muchos puntos de vista subjetivos (y yo tendré el mío también 🙈), así que es mejor si puedes centrarte en las cosas fundamentales. + +### Tests + +* Ayúdame a verificar que el PR tenga **tests**. + +* Verifica que los tests **fallen** antes del PR. 🚨 + +* Luego verifica que los tests **pasen** después del PR. ✅ + +* Muchos PRs no tienen tests, puedes **recordarles** que agreguen tests, o incluso puedes **sugerir** algunos tests tú mismo. Eso es una de las cosas que consume más tiempo y puedes ayudar mucho con eso. + +* Luego también comenta lo que intentaste, de esa manera sabré que lo revisaste. 🤓 + +## Crea un Pull Request + +Puedes [contribuir](contributing.md){.internal-link target=_blank} al código fuente con Pull Requests, por ejemplo: + +* Para corregir un error tipográfico que encontraste en la documentación. +* Para compartir un artículo, video o podcast que creaste o encontraste sobre FastAPI editando este archivo. + * Asegúrate de agregar tu enlace al inicio de la sección correspondiente. +* Para ayudar a [traducir la documentación](contributing.md#translations){.internal-link target=_blank} a tu idioma. + * También puedes ayudar a revisar las traducciones creadas por otros. +* Para proponer nuevas secciones de documentación. +* Para corregir un issue/bug existente. + * Asegúrate de agregar tests. +* Para agregar una nueva funcionalidad. + * Asegúrate de agregar tests. + * Asegúrate de agregar documentación si es relevante. + +## Ayuda a Mantener FastAPI + +¡Ayúdame a mantener **FastAPI**! 🤓 + +Hay mucho trabajo por hacer, y para la mayoría de ello, **TÚ** puedes hacerlo. + +Las tareas principales que puedes hacer ahora son: + +* [Ayudar a otros con preguntas en GitHub](#help-others-with-questions-in-github){.internal-link target=_blank} (ver la sección arriba). +* [Revisar Pull Requests](#review-pull-requests){.internal-link target=_blank} (ver la sección arriba). + +Esas dos tareas son las que **consumen más tiempo**. Ese es el trabajo principal de mantener FastAPI. + +Si puedes ayudarme con eso, **me estás ayudando a mantener FastAPI** y asegurando que siga **avanzando más rápido y mejor**. 🚀 + +## Únete al chat + +Únete al servidor de chat 👥 Discord 👥 y charla con otros en la comunidad de FastAPI. + +/// tip | Consejo + +Para preguntas, házlas en GitHub Discussions, hay muchas más probabilidades de que recibas ayuda de parte de los [FastAPI Experts](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. + +Usa el chat solo para otras conversaciones generales. + +/// + +### No uses el chat para preguntas + +Ten en cuenta que dado que los chats permiten una "conversación más libre", es fácil hacer preguntas que son demasiado generales y más difíciles de responder, por lo que es posible que no recibas respuestas. + +En GitHub, la plantilla te guiará para escribir la pregunta correcta para que puedas obtener más fácilmente una buena respuesta, o incluso resolver el problema por ti mismo antes de preguntar. Y en GitHub puedo asegurarme de responder siempre todo, incluso si lleva tiempo. No puedo hacer eso personalmente con los sistemas de chat. 😅 + +Las conversaciones en los sistemas de chat tampoco son tan fácilmente buscables como en GitHub, por lo que las preguntas y respuestas podrían perderse en la conversación. Y solo las que están en GitHub cuentan para convertirse en un [FastAPI Expert](fastapi-people.md#fastapi-experts){.internal-link target=_blank}, por lo que probablemente recibirás más atención en GitHub. + +Por otro lado, hay miles de usuarios en los sistemas de chat, por lo que hay muchas posibilidades de que encuentres a alguien con quien hablar allí, casi todo el tiempo. 😄 + +## Patrocina al autor + +También puedes apoyar financieramente al autor (a mí) a través de GitHub sponsors. + +Allí podrías comprarme un café ☕️ para decir gracias. 😄 + +Y también puedes convertirte en un sponsor de Plata o de Oro para FastAPI. 🏅🎉 + +## Patrocina las herramientas que impulsan FastAPI + +Como habrás visto en la documentación, FastAPI se apoya en los hombros de gigantes, Starlette y Pydantic. + +También puedes patrocinar: + +* Samuel Colvin (Pydantic) +* Encode (Starlette, Uvicorn) + +--- + +¡Gracias! 🚀 diff --git a/docs/es/docs/history-design-future.md b/docs/es/docs/history-design-future.md new file mode 100644 index 000000000..8beb4f400 --- /dev/null +++ b/docs/es/docs/history-design-future.md @@ -0,0 +1,79 @@ +# Historia, Diseño y Futuro + +Hace algún tiempo, un usuario de **FastAPI** preguntó: + +> ¿Cuál es la historia de este proyecto? Parece haber surgido de la nada y ser increíble en pocas semanas [...] + +Aquí hay un poquito de esa historia. + +## Alternativas + +He estado creando APIs con requisitos complejos durante varios años (Machine Learning, sistemas distribuidos, trabajos asíncronos, bases de datos NoSQL, etc.), liderando varios equipos de desarrolladores. + +Como parte de eso, necesitaba investigar, probar y usar muchas alternativas. + +La historia de **FastAPI** es en gran parte la historia de sus predecesores. + +Como se dice en la sección [Alternativas](alternatives.md){.internal-link target=_blank}: + +
+ +**FastAPI** no existiría si no fuera por el trabajo previo de otros. + +Ha habido muchas herramientas creadas antes que han ayudado a inspirar su creación. + +He estado evitando la creación de un nuevo framework durante varios años. Primero traté de resolver todas las funcionalidades cubiertas por **FastAPI** usando varios frameworks, complementos y herramientas diferentes. + +Pero en algún momento, no había otra opción que crear algo que proporcionara todas estas funcionalidades, tomando las mejores ideas de herramientas anteriores y combinándolas de la mejor manera posible, usando funcionalidades del lenguaje que ni siquiera estaban disponibles antes (anotaciones de tipos de Python 3.6+). + +
+ +## Investigación + +Al usar todas las alternativas anteriores, tuve la oportunidad de aprender de todas ellas, tomar ideas y combinarlas de la mejor manera que pude encontrar para mí y los equipos de desarrolladores con los que he trabajado. + +Por ejemplo, estaba claro que idealmente debería estar basado en las anotaciones de tipos estándar de Python. + +También, el mejor enfoque era usar estándares ya existentes. + +Entonces, antes de siquiera empezar a programar **FastAPI**, pasé varios meses estudiando las especificaciones de OpenAPI, JSON Schema, OAuth2, etc. Entendiendo su relación, superposición y diferencias. + +## Diseño + +Luego pasé algún tiempo diseñando la "API" de desarrollador que quería tener como usuario (como desarrollador usando FastAPI). + +Probé varias ideas en los editores de Python más populares: PyCharm, VS Code, editores basados en Jedi. + +Según la última Encuesta de Desarrolladores de Python, estos editores cubren alrededor del 80% de los usuarios. + +Esto significa que **FastAPI** fue específicamente probado con los editores usados por el 80% de los desarrolladores de Python. Y como la mayoría de los otros editores tienden a funcionar de manera similar, todos sus beneficios deberían funcionar prácticamente para todos los editores. + +De esa manera, pude encontrar las mejores maneras de reducir la duplicación de código tanto como fuera posible, para tener autocompletado en todas partes, chequeos de tipos y errores, etc. + +Todo de una manera que proporcionara la mejor experiencia de desarrollo para todos los desarrolladores. + +## Requisitos + +Después de probar varias alternativas, decidí que iba a usar **Pydantic** por sus ventajas. + +Luego contribuí a este, para hacerlo totalmente compatible con JSON Schema, para soportar diferentes maneras de definir declaraciones de restricciones, y para mejorar el soporte de los editores (chequeo de tipos, autocompletado) basado en las pruebas en varios editores. + +Durante el desarrollo, también contribuí a **Starlette**, el otro requisito clave. + +## Desarrollo + +Para cuando comencé a crear el propio **FastAPI**, la mayoría de las piezas ya estaban en su lugar, el diseño estaba definido, los requisitos y herramientas estaban listos, y el conocimiento sobre los estándares y especificaciones estaba claro y fresco. + +## Futuro + +A este punto, ya está claro que **FastAPI** con sus ideas está siendo útil para muchas personas. + +Está siendo elegido sobre alternativas anteriores por adaptarse mejor a muchos casos de uso. + +Muchos desarrolladores y equipos ya dependen de **FastAPI** para sus proyectos (incluyéndome a mí y a mi equipo). + +Pero aún así, hay muchas mejoras y funcionalidades por venir. + +**FastAPI** tiene un gran futuro por delante. + +Y [tu ayuda](help-fastapi.md){.internal-link target=_blank} es muy apreciada. diff --git a/docs/es/docs/how-to/conditional-openapi.md b/docs/es/docs/how-to/conditional-openapi.md new file mode 100644 index 000000000..4f806ef6c --- /dev/null +++ b/docs/es/docs/how-to/conditional-openapi.md @@ -0,0 +1,56 @@ +# OpenAPI Condicional + +Si lo necesitaras, podrías usar configuraciones y variables de entorno para configurar OpenAPI condicionalmente según el entorno, e incluso desactivarlo por completo. + +## Sobre seguridad, APIs y documentación + +Ocultar las interfaces de usuario de la documentación en producción *no debería* ser la forma de proteger tu API. + +Eso no añade ninguna seguridad extra a tu API, las *path operations* seguirán estando disponibles donde están. + +Si hay una falla de seguridad en tu código, seguirá existiendo. + +Ocultar la documentación solo hace que sea más difícil entender cómo interactuar con tu API y podría dificultar más depurarla en producción. Podría considerarse simplemente una forma de Seguridad mediante oscuridad. + +Si quieres asegurar tu API, hay varias cosas mejores que puedes hacer, por ejemplo: + +* Asegúrate de tener modelos Pydantic bien definidos para tus request bodies y responses. +* Configura los permisos y roles necesarios usando dependencias. +* Nunca guardes contraseñas en texto plano, solo hashes de contraseñas. +* Implementa y utiliza herramientas criptográficas bien conocidas, como Passlib y JWT tokens, etc. +* Añade controles de permisos más detallados con OAuth2 scopes donde sea necesario. +* ...etc. + +No obstante, podrías tener un caso de uso muy específico donde realmente necesites desactivar la documentación de la API para algún entorno (por ejemplo, para producción) o dependiendo de configuraciones de variables de entorno. + +## OpenAPI condicional desde configuraciones y variables de entorno + +Puedes usar fácilmente las mismas configuraciones de Pydantic para configurar tu OpenAPI generado y las interfaces de usuario de la documentación. + +Por ejemplo: + +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} + +Aquí declaramos la configuración `openapi_url` con el mismo valor predeterminado de `"/openapi.json"`. + +Y luego la usamos al crear la app de `FastAPI`. + +Entonces podrías desactivar OpenAPI (incluyendo las UI de documentación) configurando la variable de entorno `OPENAPI_URL` a una string vacía, así: + +
+ +```console +$ OPENAPI_URL= uvicorn main:app + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Luego, si vas a las URLs en `/openapi.json`, `/docs`, o `/redoc`, solo obtendrás un error `404 Not Found` como: + +```JSON +{ + "detail": "Not Found" +} +``` diff --git a/docs/es/docs/how-to/configure-swagger-ui.md b/docs/es/docs/how-to/configure-swagger-ui.md new file mode 100644 index 000000000..4243c191c --- /dev/null +++ b/docs/es/docs/how-to/configure-swagger-ui.md @@ -0,0 +1,70 @@ +# Configurar Swagger UI + +Puedes configurar algunos parámetros adicionales de Swagger UI. + +Para configurarlos, pasa el argumento `swagger_ui_parameters` al crear el objeto de la app `FastAPI()` o a la función `get_swagger_ui_html()`. + +`swagger_ui_parameters` recibe un diccionario con las configuraciones pasadas directamente a Swagger UI. + +FastAPI convierte las configuraciones a **JSON** para hacerlas compatibles con JavaScript, ya que eso es lo que Swagger UI necesita. + +## Desactivar el resaltado de sintaxis + +Por ejemplo, podrías desactivar el resaltado de sintaxis en Swagger UI. + +Sin cambiar la configuración, el resaltado de sintaxis está activado por defecto: + + + +Pero puedes desactivarlo estableciendo `syntaxHighlight` en `False`: + +{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *} + +...y entonces Swagger UI ya no mostrará el resaltado de sintaxis: + + + +## Cambiar el tema + +De la misma manera, podrías configurar el tema del resaltado de sintaxis con la clave `"syntaxHighlight.theme"` (ten en cuenta que tiene un punto en el medio): + +{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *} + +Esa configuración cambiaría el tema de color del resaltado de sintaxis: + + + +## Cambiar los parámetros predeterminados de Swagger UI + +FastAPI incluye algunos parámetros de configuración predeterminados apropiados para la mayoría de los casos de uso. + +Incluye estas configuraciones predeterminadas: + +{* ../../fastapi/openapi/docs.py ln[8:23] hl[17:23] *} + +Puedes sobrescribir cualquiera de ellos estableciendo un valor diferente en el argumento `swagger_ui_parameters`. + +Por ejemplo, para desactivar `deepLinking` podrías pasar estas configuraciones a `swagger_ui_parameters`: + +{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *} + +## Otros parámetros de Swagger UI + +Para ver todas las demás configuraciones posibles que puedes usar, lee la documentación oficial de los parámetros de Swagger UI. + +## Configuraciones solo de JavaScript + +Swagger UI también permite otras configuraciones que son objetos **solo de JavaScript** (por ejemplo, funciones de JavaScript). + +FastAPI también incluye estas configuraciones `presets` solo de JavaScript: + +```JavaScript +presets: [ + SwaggerUIBundle.presets.apis, + SwaggerUIBundle.SwaggerUIStandalonePreset +] +``` + +Estos son objetos de **JavaScript**, no strings, por lo que no puedes pasarlos directamente desde código de Python. + +Si necesitas usar configuraciones solo de JavaScript como esas, puedes usar uno de los métodos anteriores. Sobrescribe toda la *path operation* de Swagger UI y escribe manualmente cualquier JavaScript que necesites. diff --git a/docs/es/docs/how-to/custom-docs-ui-assets.md b/docs/es/docs/how-to/custom-docs-ui-assets.md new file mode 100644 index 000000000..444cf167e --- /dev/null +++ b/docs/es/docs/how-to/custom-docs-ui-assets.md @@ -0,0 +1,191 @@ +# Recursos Estáticos Personalizados para la Docs UI (Self-Hosting) + +La documentación de la API utiliza **Swagger UI** y **ReDoc**, y cada uno de estos necesita algunos archivos JavaScript y CSS. + +Por defecto, esos archivos se sirven desde un CDN. + +Pero es posible personalizarlo, puedes establecer un CDN específico, o servir los archivos tú mismo. + +## CDN Personalizado para JavaScript y CSS + +Digamos que quieres usar un CDN diferente, por ejemplo, quieres usar `https://unpkg.com/`. + +Esto podría ser útil si, por ejemplo, vives en un país que restringe algunas URLs. + +### Desactiva la documentación automática + +El primer paso es desactivar la documentación automática, ya que por defecto, esos usan el CDN predeterminado. + +Para desactivarlos, establece sus URLs en `None` cuando crees tu aplicación de `FastAPI`: + +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} + +### Incluye la documentación personalizada + +Ahora puedes crear las *path operations* para la documentación personalizada. + +Puedes reutilizar las funciones internas de FastAPI para crear las páginas HTML para la documentación, y pasarles los argumentos necesarios: + +* `openapi_url`: la URL donde la página HTML para la documentación puede obtener el OpenAPI esquema de tu API. Puedes usar aquí el atributo `app.openapi_url`. +* `title`: el título de tu API. +* `oauth2_redirect_url`: puedes usar `app.swagger_ui_oauth2_redirect_url` aquí para usar el valor predeterminado. +* `swagger_js_url`: la URL donde el HTML para tu documentación de Swagger UI puede obtener el archivo **JavaScript**. Esta es la URL personalizada del CDN. +* `swagger_css_url`: la URL donde el HTML para tu documentación de Swagger UI puede obtener el archivo **CSS**. Esta es la URL personalizada del CDN. + +Y de manera similar para ReDoc... + +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} + +/// tip | Consejo + +La *path operation* para `swagger_ui_redirect` es una herramienta cuando utilizas OAuth2. + +Si integras tu API con un proveedor OAuth2, podrás autenticarte y regresar a la documentación de la API con las credenciales adquiridas. E interactuar con ella usando la autenticación real de OAuth2. + +Swagger UI lo manejará detrás de escena para ti, pero necesita este auxiliar de "redirección". + +/// + +### Crea una *path operation* para probarlo + +Ahora, para poder probar que todo funciona, crea una *path operation*: + +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} + +### Pruébalo + +Ahora, deberías poder ir a tu documentación en http://127.0.0.1:8000/docs, y recargar la página, cargará esos recursos desde el nuevo CDN. + +## Self-hosting de JavaScript y CSS para la documentación + +El self-hosting de JavaScript y CSS podría ser útil si, por ejemplo, necesitas que tu aplicación siga funcionando incluso offline, sin acceso a Internet, o en una red local. + +Aquí verás cómo servir esos archivos tú mismo, en la misma aplicación de FastAPI, y configurar la documentación para usarla. + +### Estructura de archivos del proyecto + +Supongamos que la estructura de archivos de tu proyecto se ve así: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +``` + +Ahora crea un directorio para almacenar esos archivos estáticos. + +Tu nueva estructura de archivos podría verse así: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +└── static/ +``` + +### Descarga los archivos + +Descarga los archivos estáticos necesarios para la documentación y ponlos en ese directorio `static/`. + +Probablemente puedas hacer clic derecho en cada enlace y seleccionar una opción similar a `Guardar enlace como...`. + +**Swagger UI** utiliza los archivos: + +* `swagger-ui-bundle.js` +* `swagger-ui.css` + +Y **ReDoc** utiliza el archivo: + +* `redoc.standalone.js` + +Después de eso, tu estructura de archivos podría verse así: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +└── static + ├── redoc.standalone.js + ├── swagger-ui-bundle.js + └── swagger-ui.css +``` + +### Sirve los archivos estáticos + +* Importa `StaticFiles`. +* "Monta" una instance de `StaticFiles()` en un path específico. + +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} + +### Prueba los archivos estáticos + +Inicia tu aplicación y ve a http://127.0.0.1:8000/static/redoc.standalone.js. + +Deberías ver un archivo JavaScript muy largo de **ReDoc**. + +Podría comenzar con algo como: + +```JavaScript +/*! + * ReDoc - OpenAPI/Swagger-generated API Reference Documentation + * ------------------------------------------------------------- + * Version: "2.0.0-rc.18" + * Repo: https://github.com/Redocly/redoc + */ +!function(e,t){"object"==typeof exports&&"object"==typeof m + +... +``` + +Eso confirma que puedes servir archivos estáticos desde tu aplicación, y que colocaste los archivos estáticos para la documentación en el lugar correcto. + +Ahora podemos configurar la aplicación para usar esos archivos estáticos para la documentación. + +### Desactiva la documentación automática para archivos estáticos + +Igual que cuando usas un CDN personalizado, el primer paso es desactivar la documentación automática, ya que esos usan el CDN por defecto. + +Para desactivarlos, establece sus URLs en `None` cuando crees tu aplicación de `FastAPI`: + +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} + +### Incluye la documentación personalizada para archivos estáticos + +Y de la misma manera que con un CDN personalizado, ahora puedes crear las *path operations* para la documentación personalizada. + +Nuevamente, puedes reutilizar las funciones internas de FastAPI para crear las páginas HTML para la documentación, y pasarles los argumentos necesarios: + +* `openapi_url`: la URL donde la página HTML para la documentación puede obtener el OpenAPI esquema de tu API. Puedes usar aquí el atributo `app.openapi_url`. +* `title`: el título de tu API. +* `oauth2_redirect_url`: puedes usar `app.swagger_ui_oauth2_redirect_url` aquí para usar el valor predeterminado. +* `swagger_js_url`: la URL donde el HTML para tu documentación de Swagger UI puede obtener el archivo **JavaScript**. **Este es el que tu propia aplicación está sirviendo ahora**. +* `swagger_css_url`: la URL donde el HTML para tu documentación de Swagger UI puede obtener el archivo **CSS**. **Este es el que tu propia aplicación está sirviendo ahora**. + +Y de manera similar para ReDoc... + +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} + +/// tip | Consejo + +La *path operation* para `swagger_ui_redirect` es una herramienta cuando utilizas OAuth2. + +Si integras tu API con un proveedor OAuth2, podrás autenticarte y regresar a la documentación de la API con las credenciales adquiridas. Y interactuar con ella usando la autenticación real de OAuth2. + +Swagger UI lo manejará detrás de escena para ti, pero necesita este auxiliar de "redirección". + +/// + +### Crea una *path operation* para probar archivos estáticos + +Ahora, para poder probar que todo funciona, crea una *path operation*: + +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} + +### Prueba la UI de Archivos Estáticos + +Ahora, deberías poder desconectar tu WiFi, ir a tu documentación en http://127.0.0.1:8000/docs, y recargar la página. + +E incluso sin Internet, podrás ver la documentación de tu API e interactuar con ella. diff --git a/docs/es/docs/how-to/custom-request-and-route.md b/docs/es/docs/how-to/custom-request-and-route.md new file mode 100644 index 000000000..0b479bf00 --- /dev/null +++ b/docs/es/docs/how-to/custom-request-and-route.md @@ -0,0 +1,109 @@ +# Clase personalizada de Request y APIRoute + +En algunos casos, puede que quieras sobrescribir la lógica utilizada por las clases `Request` y `APIRoute`. + +En particular, esta puede ser una buena alternativa a la lógica en un middleware. + +Por ejemplo, si quieres leer o manipular el request body antes de que sea procesado por tu aplicación. + +/// danger | Advertencia + +Esta es una funcionalidad "avanzada". + +Si apenas estás comenzando con **FastAPI**, quizás quieras saltar esta sección. + +/// + +## Casos de uso + +Algunos casos de uso incluyen: + +* Convertir cuerpos de requests no-JSON a JSON (por ejemplo, `msgpack`). +* Descomprimir cuerpos de requests comprimidos con gzip. +* Registrar automáticamente todos los request bodies. + +## Manejo de codificaciones personalizadas de request body + +Veamos cómo hacer uso de una subclase personalizada de `Request` para descomprimir requests gzip. + +Y una subclase de `APIRoute` para usar esa clase de request personalizada. + +### Crear una clase personalizada `GzipRequest` + +/// tip | Consejo + +Este es un ejemplo sencillo para demostrar cómo funciona. Si necesitas soporte para Gzip, puedes usar el [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} proporcionado. + +/// + +Primero, creamos una clase `GzipRequest`, que sobrescribirá el método `Request.body()` para descomprimir el cuerpo si hay un header apropiado. + +Si no hay `gzip` en el header, no intentará descomprimir el cuerpo. + +De esa manera, la misma clase de ruta puede manejar requests comprimidos con gzip o no comprimidos. + +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[8:15] *} + +### Crear una clase personalizada `GzipRoute` + +A continuación, creamos una subclase personalizada de `fastapi.routing.APIRoute` que hará uso de `GzipRequest`. + +Esta vez, sobrescribirá el método `APIRoute.get_route_handler()`. + +Este método devuelve una función. Y esa función es la que recibirá un request y devolverá un response. + +Aquí lo usamos para crear un `GzipRequest` a partir del request original. + +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[18:26] *} + +/// note | Detalles técnicos + +Un `Request` tiene un atributo `request.scope`, que es simplemente un `dict` de Python que contiene los metadatos relacionados con el request. + +Un `Request` también tiene un `request.receive`, que es una función para "recibir" el cuerpo del request. + +El `dict` `scope` y la función `receive` son ambos parte de la especificación ASGI. + +Y esas dos cosas, `scope` y `receive`, son lo que se necesita para crear una nueva *Request instance*. + +Para aprender más sobre el `Request`, revisa la documentación de Starlette sobre Requests. + +/// + +La única cosa que la función devuelta por `GzipRequest.get_route_handler` hace diferente es convertir el `Request` en un `GzipRequest`. + +Haciendo esto, nuestro `GzipRequest` se encargará de descomprimir los datos (si es necesario) antes de pasarlos a nuestras *path operations*. + +Después de eso, toda la lógica de procesamiento es la misma. + +Pero debido a nuestros cambios en `GzipRequest.body`, el request body se descomprimirá automáticamente cuando sea cargado por **FastAPI** si es necesario. + +## Accediendo al request body en un manejador de excepciones + +/// tip | Consejo + +Para resolver este mismo problema, probablemente sea mucho más fácil usar el `body` en un manejador personalizado para `RequestValidationError` ([Manejo de Errores](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}). + +Pero este ejemplo sigue siendo válido y muestra cómo interactuar con los componentes internos. + +/// + +También podemos usar este mismo enfoque para acceder al request body en un manejador de excepciones. + +Todo lo que necesitamos hacer es manejar el request dentro de un bloque `try`/`except`: + +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[13,15] *} + +Si ocurre una excepción, la `Request instance` aún estará en el alcance, así que podemos leer y hacer uso del request body cuando manejamos el error: + +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[16:18] *} + +## Clase personalizada `APIRoute` en un router + +También puedes establecer el parámetro `route_class` de un `APIRouter`: + +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[26] *} + +En este ejemplo, las *path operations* bajo el `router` usarán la clase personalizada `TimedRoute`, y tendrán un header `X-Response-Time` extra en el response con el tiempo que tomó generar el response: + +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[13:20] *} diff --git a/docs/es/docs/how-to/extending-openapi.md b/docs/es/docs/how-to/extending-openapi.md new file mode 100644 index 000000000..3dbdd666b --- /dev/null +++ b/docs/es/docs/how-to/extending-openapi.md @@ -0,0 +1,80 @@ +# Extender OpenAPI + +Hay algunos casos en los que podrías necesitar modificar el esquema de OpenAPI generado. + +En esta sección verás cómo hacerlo. + +## El proceso normal + +El proceso normal (por defecto) es el siguiente. + +Una aplicación (instance) de `FastAPI` tiene un método `.openapi()` que se espera que devuelva el esquema de OpenAPI. + +Como parte de la creación del objeto de la aplicación, se registra una *path operation* para `/openapi.json` (o para lo que sea que configures tu `openapi_url`). + +Simplemente devuelve un response JSON con el resultado del método `.openapi()` de la aplicación. + +Por defecto, lo que hace el método `.openapi()` es revisar la propiedad `.openapi_schema` para ver si tiene contenido y devolverlo. + +Si no lo tiene, lo genera usando la función de utilidad en `fastapi.openapi.utils.get_openapi`. + +Y esa función `get_openapi()` recibe como parámetros: + +* `title`: El título de OpenAPI, mostrado en la documentación. +* `version`: La versión de tu API, por ejemplo `2.5.0`. +* `openapi_version`: La versión de la especificación OpenAPI utilizada. Por defecto, la más reciente: `3.1.0`. +* `summary`: Un breve resumen de la API. +* `description`: La descripción de tu API, esta puede incluir markdown y se mostrará en la documentación. +* `routes`: Una list de rutas, estas son cada una de las *path operations* registradas. Se toman de `app.routes`. + +/// info | Información + +El parámetro `summary` está disponible en OpenAPI 3.1.0 y versiones superiores, soportado por FastAPI 0.99.0 y superiores. + +/// + +## Sobrescribir los valores por defecto + +Usando la información anterior, puedes usar la misma función de utilidad para generar el esquema de OpenAPI y sobrescribir cada parte que necesites. + +Por ejemplo, vamos a añadir la extensión OpenAPI de ReDoc para incluir un logo personalizado. + +### **FastAPI** normal + +Primero, escribe toda tu aplicación **FastAPI** como normalmente: + +{* ../../docs_src/extending_openapi/tutorial001.py hl[1,4,7:9] *} + +### Generar el esquema de OpenAPI + +Luego, usa la misma función de utilidad para generar el esquema de OpenAPI, dentro de una función `custom_openapi()`: + +{* ../../docs_src/extending_openapi/tutorial001.py hl[2,15:21] *} + +### Modificar el esquema de OpenAPI + +Ahora puedes añadir la extensión de ReDoc, agregando un `x-logo` personalizado al "objeto" `info` en el esquema de OpenAPI: + +{* ../../docs_src/extending_openapi/tutorial001.py hl[22:24] *} + +### Cachear el esquema de OpenAPI + +Puedes usar la propiedad `.openapi_schema` como un "cache", para almacenar tu esquema generado. + +De esa forma, tu aplicación no tendrá que generar el esquema cada vez que un usuario abra la documentación de tu API. + +Se generará solo una vez, y luego se usará el mismo esquema cacheado para las siguientes requests. + +{* ../../docs_src/extending_openapi/tutorial001.py hl[13:14,25:26] *} + +### Sobrescribir el método + +Ahora puedes reemplazar el método `.openapi()` por tu nueva función. + +{* ../../docs_src/extending_openapi/tutorial001.py hl[29] *} + +### Revisa + +Una vez que vayas a http://127.0.0.1:8000/redoc verás que estás usando tu logo personalizado (en este ejemplo, el logo de **FastAPI**): + + diff --git a/docs/es/docs/how-to/general.md b/docs/es/docs/how-to/general.md new file mode 100644 index 000000000..e10621ce5 --- /dev/null +++ b/docs/es/docs/how-to/general.md @@ -0,0 +1,39 @@ +# General - Cómo Hacer - Recetas + +Aquí tienes varias indicaciones hacia otros lugares en la documentación, para preguntas generales o frecuentes. + +## Filtrar Datos - Seguridad + +Para asegurarte de que no devuelves más datos de los que deberías, lee la documentación para [Tutorial - Modelo de Response - Tipo de Retorno](../tutorial/response-model.md){.internal-link target=_blank}. + +## Etiquetas de Documentación - OpenAPI + +Para agregar etiquetas a tus *path operations*, y agruparlas en la interfaz de usuario de la documentación, lee la documentación para [Tutorial - Configuraciones de Path Operation - Etiquetas](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank}. + +## Resumen y Descripción de Documentación - OpenAPI + +Para agregar un resumen y descripción a tus *path operations*, y mostrarlos en la interfaz de usuario de la documentación, lee la documentación para [Tutorial - Configuraciones de Path Operation - Resumen y Descripción](../tutorial/path-operation-configuration.md#summary-and-description){.internal-link target=_blank}. + +## Documentación de Descripción de Response - OpenAPI + +Para definir la descripción del response, mostrada en la interfaz de usuario de la documentación, lee la documentación para [Tutorial - Configuraciones de Path Operation - Descripción del Response](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank}. + +## Documentar la Deprecación de una *Path Operation* - OpenAPI + +Para deprecar una *path operation*, y mostrarla en la interfaz de usuario de la documentación, lee la documentación para [Tutorial - Configuraciones de Path Operation - Deprecación](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank}. + +## Convertir cualquier Dato a Compatible con JSON + +Para convertir cualquier dato a compatible con JSON, lee la documentación para [Tutorial - Codificador Compatible con JSON](../tutorial/encoder.md){.internal-link target=_blank}. + +## Metadatos OpenAPI - Documentación + +Para agregar metadatos a tu esquema de OpenAPI, incluyendo una licencia, versión, contacto, etc, lee la documentación para [Tutorial - Metadatos y URLs de Documentación](../tutorial/metadata.md){.internal-link target=_blank}. + +## URL Personalizada de OpenAPI + +Para personalizar la URL de OpenAPI (o eliminarla), lee la documentación para [Tutorial - Metadatos y URLs de Documentación](../tutorial/metadata.md#openapi-url){.internal-link target=_blank}. + +## URLs de Documentación de OpenAPI + +Para actualizar las URLs usadas para las interfaces de usuario de documentación generadas automáticamente, lee la documentación para [Tutorial - Metadatos y URLs de Documentación](../tutorial/metadata.md#docs-urls){.internal-link target=_blank}. diff --git a/docs/es/docs/how-to/index.md b/docs/es/docs/how-to/index.md new file mode 100644 index 000000000..152499af8 --- /dev/null +++ b/docs/es/docs/how-to/index.md @@ -0,0 +1,13 @@ +# How To - Recetas + +Aquí verás diferentes recetas o guías de "cómo hacer" para **varios temas**. + +La mayoría de estas ideas serían más o menos **independientes**, y en la mayoría de los casos solo deberías estudiarlas si aplican directamente a **tu proyecto**. + +Si algo parece interesante y útil para tu proyecto, adelante y revísalo, pero de lo contrario, probablemente puedas simplemente omitirlas. + +/// tip | Consejo + +Si quieres **aprender FastAPI** de una manera estructurada (recomendado), ve y lee el [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} capítulo por capítulo. + +/// diff --git a/docs/es/docs/how-to/separate-openapi-schemas.md b/docs/es/docs/how-to/separate-openapi-schemas.md new file mode 100644 index 000000000..b77915851 --- /dev/null +++ b/docs/es/docs/how-to/separate-openapi-schemas.md @@ -0,0 +1,104 @@ +# Separación de Esquemas OpenAPI para Entrada y Salida o No + +Al usar **Pydantic v2**, el OpenAPI generado es un poco más exacto y **correcto** que antes. 😎 + +De hecho, en algunos casos, incluso tendrá **dos JSON Schemas** en OpenAPI para el mismo modelo Pydantic, para entrada y salida, dependiendo de si tienen **valores por defecto**. + +Veamos cómo funciona eso y cómo cambiarlo si necesitas hacerlo. + +## Modelos Pydantic para Entrada y Salida + +Digamos que tienes un modelo Pydantic con valores por defecto, como este: + +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *} + +### Modelo para Entrada + +Si usas este modelo como entrada, como aquí: + +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *} + +...entonces el campo `description` **no será requerido**. Porque tiene un valor por defecto de `None`. + +### Modelo de Entrada en la Documentación + +Puedes confirmar eso en la documentación, el campo `description` no tiene un **asterisco rojo**, no está marcado como requerido: + +
+ +
+ +### Modelo para Salida + +Pero si usas el mismo modelo como salida, como aquí: + +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py hl[19] *} + +...entonces, porque `description` tiene un valor por defecto, si **no devuelves nada** para ese campo, aún tendrá ese **valor por defecto**. + +### Modelo para Datos de Response de Salida + +Si interactúas con la documentación y revisas el response, aunque el código no agregó nada en uno de los campos `description`, el response JSON contiene el valor por defecto (`null`): + +
+ +
+ +Esto significa que **siempre tendrá un valor**, solo que a veces el valor podría ser `None` (o `null` en JSON). + +Eso significa que, los clientes que usan tu API no tienen que comprobar si el valor existe o no, pueden **asumir que el campo siempre estará allí**, pero solo que en algunos casos tendrá el valor por defecto de `None`. + +La forma de describir esto en OpenAPI es marcar ese campo como **requerido**, porque siempre estará allí. + +Debido a eso, el JSON Schema para un modelo puede ser diferente dependiendo de si se usa para **entrada o salida**: + +* para **entrada** el `description` **no será requerido** +* para **salida** será **requerido** (y posiblemente `None`, o en términos de JSON, `null`) + +### Modelo para Salida en la Documentación + +También puedes revisar el modelo de salida en la documentación, **ambos** `name` y `description` están marcados como **requeridos** con un **asterisco rojo**: + +
+ +
+ +### Modelo para Entrada y Salida en la Documentación + +Y si revisas todos los esquemas disponibles (JSON Schemas) en OpenAPI, verás que hay dos, uno `Item-Input` y uno `Item-Output`. + +Para `Item-Input`, `description` **no es requerido**, no tiene un asterisco rojo. + +Pero para `Item-Output`, `description` **es requerido**, tiene un asterisco rojo. + +
+ +
+ +Con esta funcionalidad de **Pydantic v2**, la documentación de tu API es más **precisa**, y si tienes clientes y SDKs autogenerados, también serán más precisos, con una mejor **experiencia para desarrolladores** y consistencia. 🎉 + +## No Separar Esquemas + +Ahora, hay algunos casos donde podrías querer tener el **mismo esquema para entrada y salida**. + +Probablemente el caso principal para esto es si ya tienes algún código cliente/SDKs autogenerado y no quieres actualizar todo el código cliente/SDKs autogenerado aún, probablemente querrás hacerlo en algún momento, pero tal vez no ahora. + +En ese caso, puedes desactivar esta funcionalidad en **FastAPI**, con el parámetro `separate_input_output_schemas=False`. + +/// info | Información + +El soporte para `separate_input_output_schemas` fue agregado en FastAPI `0.102.0`. 🤓 + +/// + +{* ../../docs_src/separate_openapi_schemas/tutorial002_py310.py hl[10] *} + +### Mismo Esquema para Modelos de Entrada y Salida en la Documentación + +Y ahora habrá un único esquema para entrada y salida para el modelo, solo `Item`, y tendrá `description` como **no requerido**: + +
+ +
+ +Este es el mismo comportamiento que en Pydantic v1. 🤓 diff --git a/docs/es/docs/how-to/testing-database.md b/docs/es/docs/how-to/testing-database.md new file mode 100644 index 000000000..b76f4c33a --- /dev/null +++ b/docs/es/docs/how-to/testing-database.md @@ -0,0 +1,7 @@ +# Probando una Base de Datos + +Puedes estudiar sobre bases de datos, SQL y SQLModel en la documentación de SQLModel. 🤓 + +Hay un mini tutorial sobre el uso de SQLModel con FastAPI. ✨ + +Ese tutorial incluye una sección sobre cómo probar bases de datos SQL. 😎 diff --git a/docs/es/docs/tutorial/background-tasks.md b/docs/es/docs/tutorial/background-tasks.md new file mode 100644 index 000000000..3fe961e41 --- /dev/null +++ b/docs/es/docs/tutorial/background-tasks.md @@ -0,0 +1,84 @@ +# Tareas en Segundo Plano + +Puedes definir tareas en segundo plano para que se ejecuten *después* de devolver un response. + +Esto es útil para operaciones que necesitan ocurrir después de un request, pero para las que el cliente realmente no necesita esperar a que la operación termine antes de recibir el response. + +Esto incluye, por ejemplo: + +* Notificaciones por email enviadas después de realizar una acción: + * Como conectarse a un servidor de email y enviar un email tiende a ser "lento" (varios segundos), puedes devolver el response de inmediato y enviar la notificación por email en segundo plano. +* Procesamiento de datos: + * Por ejemplo, supongamos que recibes un archivo que debe pasar por un proceso lento, puedes devolver un response de "Accepted" (HTTP 202) y procesar el archivo en segundo plano. + +## Usando `BackgroundTasks` + +Primero, importa `BackgroundTasks` y define un parámetro en tu *path operation function* con una declaración de tipo de `BackgroundTasks`: + +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} + +**FastAPI** creará el objeto de tipo `BackgroundTasks` por ti y lo pasará como ese parámetro. + +## Crear una función de tarea + +Crea una función para que se ejecute como la tarea en segundo plano. + +Es solo una función estándar que puede recibir parámetros. + +Puede ser una función `async def` o una función normal `def`, **FastAPI** sabrá cómo manejarla correctamente. + +En este caso, la función de tarea escribirá en un archivo (simulando el envío de un email). + +Y como la operación de escritura no usa `async` y `await`, definimos la función con un `def` normal: + +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} + +## Agregar la tarea en segundo plano + +Dentro de tu *path operation function*, pasa tu función de tarea al objeto de *background tasks* con el método `.add_task()`: + +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} + +`.add_task()` recibe como argumentos: + +* Una función de tarea para ejecutar en segundo plano (`write_notification`). +* Cualquier secuencia de argumentos que deba pasarse a la función de tarea en orden (`email`). +* Cualquier argumento de palabras clave que deba pasarse a la función de tarea (`message="some notification"`). + +## Inyección de Dependencias + +Usar `BackgroundTasks` también funciona con el sistema de inyección de dependencias, puedes declarar un parámetro de tipo `BackgroundTasks` en varios niveles: en una *path operation function*, en una dependencia (dependable), en una sub-dependencia, etc. + +**FastAPI** sabe qué hacer en cada caso y cómo reutilizar el mismo objeto, de modo que todas las tareas en segundo plano se combinan y ejecutan en segundo plano después: + +{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *} + +En este ejemplo, los mensajes se escribirán en el archivo `log.txt` *después* de que se envíe el response. + +Si hay un query en el request, se escribirá en el log en una tarea en segundo plano. + +Y luego otra tarea en segundo plano generada en la *path operation function* escribirá un mensaje usando el parámetro de path `email`. + +## Detalles Técnicos + +La clase `BackgroundTasks` proviene directamente de `starlette.background`. + +Se importa/incluye directamente en FastAPI para que puedas importarla desde `fastapi` y evitar importar accidentalmente la alternativa `BackgroundTask` (sin la `s` al final) de `starlette.background`. + +Al usar solo `BackgroundTasks` (y no `BackgroundTask`), es posible usarla como un parámetro de *path operation function* y dejar que **FastAPI** maneje el resto por ti, tal como cuando usas el objeto `Request` directamente. + +Todavía es posible usar `BackgroundTask` solo en FastAPI, pero debes crear el objeto en tu código y devolver una `Response` de Starlette incluyéndolo. + +Puedes ver más detalles en la documentación oficial de Starlette sobre Background Tasks. + +## Advertencia + +Si necesitas realizar una computación intensa en segundo plano y no necesariamente necesitas que se ejecute por el mismo proceso (por ejemplo, no necesitas compartir memoria, variables, etc.), podrías beneficiarte del uso de otras herramientas más grandes como Celery. + +Tienden a requerir configuraciones más complejas, un gestor de cola de mensajes/trabajos, como RabbitMQ o Redis, pero te permiten ejecutar tareas en segundo plano en múltiples procesos, y especialmente, en múltiples servidores. + +Pero si necesitas acceder a variables y objetos de la misma app de **FastAPI**, o necesitas realizar pequeñas tareas en segundo plano (como enviar una notificación por email), simplemente puedes usar `BackgroundTasks`. + +## Resumen + +Importa y usa `BackgroundTasks` con parámetros en *path operation functions* y dependencias para agregar tareas en segundo plano. diff --git a/docs/es/docs/tutorial/bigger-applications.md b/docs/es/docs/tutorial/bigger-applications.md new file mode 100644 index 000000000..78165ef05 --- /dev/null +++ b/docs/es/docs/tutorial/bigger-applications.md @@ -0,0 +1,554 @@ +# Aplicaciones más grandes - Múltiples archivos + +Si estás construyendo una aplicación o una API web, rara vez podrás poner todo en un solo archivo. + +**FastAPI** proporciona una herramienta conveniente para estructurar tu aplicación manteniendo toda la flexibilidad. + +/// info | Información + +Si vienes de Flask, esto sería el equivalente a los Blueprints de Flask. + +/// + +## Un ejemplo de estructura de archivos + +Digamos que tienes una estructura de archivos como esta: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   ├── dependencies.py +│   └── routers +│   │ ├── __init__.py +│   │ ├── items.py +│   │ └── users.py +│   └── internal +│   ├── __init__.py +│   └── admin.py +``` + +/// tip | Consejo + +Hay varios archivos `__init__.py`: uno en cada directorio o subdirectorio. + +Esto es lo que permite importar código de un archivo a otro. + +Por ejemplo, en `app/main.py` podrías tener una línea como: + +``` +from app.routers import items +``` + +/// + +* El directorio `app` contiene todo. Y tiene un archivo vacío `app/__init__.py`, por lo que es un "paquete de Python" (una colección de "módulos de Python"): `app`. +* Contiene un archivo `app/main.py`. Como está dentro de un paquete de Python (un directorio con un archivo `__init__.py`), es un "módulo" de ese paquete: `app.main`. +* También hay un archivo `app/dependencies.py`, al igual que `app/main.py`, es un "módulo": `app.dependencies`. +* Hay un subdirectorio `app/routers/` con otro archivo `__init__.py`, por lo que es un "subpaquete de Python": `app.routers`. +* El archivo `app/routers/items.py` está dentro de un paquete, `app/routers/`, por lo que es un submódulo: `app.routers.items`. +* Lo mismo con `app/routers/users.py`, es otro submódulo: `app.routers.users`. +* También hay un subdirectorio `app/internal/` con otro archivo `__init__.py`, por lo que es otro "subpaquete de Python": `app.internal`. +* Y el archivo `app/internal/admin.py` es otro submódulo: `app.internal.admin`. + + + +La misma estructura de archivos con comentarios: + +``` +. +├── app # "app" es un paquete de Python +│   ├── __init__.py # este archivo hace que "app" sea un "paquete de Python" +│   ├── main.py # módulo "main", por ejemplo import app.main +│   ├── dependencies.py # módulo "dependencies", por ejemplo import app.dependencies +│   └── routers # "routers" es un "subpaquete de Python" +│   │ ├── __init__.py # hace que "routers" sea un "subpaquete de Python" +│   │ ├── items.py # submódulo "items", por ejemplo import app.routers.items +│   │ └── users.py # submódulo "users", por ejemplo import app.routers.users +│   └── internal # "internal" es un "subpaquete de Python" +│   ├── __init__.py # hace que "internal" sea un "subpaquete de Python" +│   └── admin.py # submódulo "admin", por ejemplo import app.internal.admin +``` + +## `APIRouter` + +Digamos que el archivo dedicado solo a manejar usuarios es el submódulo en `/app/routers/users.py`. + +Quieres tener las *path operations* relacionadas con tus usuarios separadas del resto del código, para mantenerlo organizado. + +Pero todavía es parte de la misma aplicación/web API de **FastAPI** (es parte del mismo "paquete de Python"). + +Puedes crear las *path operations* para ese módulo usando `APIRouter`. + +### Importar `APIRouter` + +Lo importas y creas una "instance" de la misma manera que lo harías con la clase `FastAPI`: + +```Python hl_lines="1 3" title="app/routers/users.py" +{!../../docs_src/bigger_applications/app/routers/users.py!} +``` + +### *Path operations* con `APIRouter` + +Y luego lo usas para declarar tus *path operations*. + +Úsalo de la misma manera que usarías la clase `FastAPI`: + +```Python hl_lines="6 11 16" title="app/routers/users.py" +{!../../docs_src/bigger_applications/app/routers/users.py!} +``` + +Puedes pensar en `APIRouter` como una clase "mini `FastAPI`". + +Se soportan todas las mismas opciones. + +Todos los mismos `parameters`, `responses`, `dependencies`, `tags`, etc. + +/// tip | Consejo + +En este ejemplo, la variable se llama `router`, pero puedes nombrarla como quieras. + +/// + +Vamos a incluir este `APIRouter` en la aplicación principal de `FastAPI`, pero primero, revisemos las dependencias y otro `APIRouter`. + +## Dependencias + +Vemos que vamos a necesitar algunas dependencias usadas en varios lugares de la aplicación. + +Así que las ponemos en su propio módulo `dependencies` (`app/dependencies.py`). + +Ahora utilizaremos una dependencia simple para leer un encabezado `X-Token` personalizado: + +//// tab | Python 3.9+ + +```Python hl_lines="3 6-8" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 5-7" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app_an/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Consejo + +Preferiblemente usa la versión `Annotated` si es posible. + +/// + +```Python hl_lines="1 4-6" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app/dependencies.py!} +``` + +//// + +/// tip | Consejo + +Estamos usando un encabezado inventado para simplificar este ejemplo. + +Pero en casos reales obtendrás mejores resultados usando las [utilidades de Seguridad](security/index.md){.internal-link target=_blank} integradas. + +/// + +## Otro módulo con `APIRouter` + +Digamos que también tienes los endpoints dedicados a manejar "items" de tu aplicación en el módulo `app/routers/items.py`. + +Tienes *path operations* para: + +* `/items/` +* `/items/{item_id}` + +Es toda la misma estructura que con `app/routers/users.py`. + +Pero queremos ser más inteligentes y simplificar un poco el código. + +Sabemos que todas las *path operations* en este módulo tienen el mismo: + +* Prefijo de path: `/items`. +* `tags`: (solo una etiqueta: `items`). +* `responses` extra. +* `dependencies`: todas necesitan esa dependencia `X-Token` que creamos. + +Entonces, en lugar de agregar todo eso a cada *path operation*, podemos agregarlo al `APIRouter`. + +```Python hl_lines="5-10 16 21" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +Como el path de cada *path operation* tiene que empezar con `/`, como en: + +```Python hl_lines="1" +@router.get("/{item_id}") +async def read_item(item_id: str): + ... +``` + +...el prefijo no debe incluir un `/` final. + +Así que, el prefijo en este caso es `/items`. + +También podemos agregar una lista de `tags` y `responses` extra que se aplicarán a todas las *path operations* incluidas en este router. + +Y podemos agregar una lista de `dependencies` que se añadirá a todas las *path operations* en el router y se ejecutarán/solucionarán por cada request que les haga. + +/// tip | Consejo + +Nota que, al igual que [dependencias en decoradores de *path operations*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, ningún valor será pasado a tu *path operation function*. + +/// + +El resultado final es que los paths de item son ahora: + +* `/items/` +* `/items/{item_id}` + +...como pretendíamos. + +* Serán marcados con una lista de tags que contiene un solo string `"items"`. + * Estos "tags" son especialmente útiles para los sistemas de documentación interactiva automática (usando OpenAPI). +* Todos incluirán las `responses` predefinidas. +* Todas estas *path operations* tendrán la lista de `dependencies` evaluadas/ejecutadas antes de ellas. + * Si también declaras dependencias en una *path operation* específica, **también se ejecutarán**. + * Las dependencias del router se ejecutan primero, luego las [dependencias en el decorador](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, y luego las dependencias de parámetros normales. + * También puedes agregar [dependencias de `Security` con `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}. + +/// tip | Consejo + +Tener `dependencies` en el `APIRouter` puede ser usado, por ejemplo, para requerir autenticación para un grupo completo de *path operations*. Incluso si las dependencias no son añadidas individualmente a cada una de ellas. + +/// + +/// check | Revisa + +Los parámetros `prefix`, `tags`, `responses`, y `dependencies` son (como en muchos otros casos) solo una funcionalidad de **FastAPI** para ayudarte a evitar la duplicación de código. + +/// + +### Importar las dependencias + +Este código vive en el módulo `app.routers.items`, el archivo `app/routers/items.py`. + +Y necesitamos obtener la función de dependencia del módulo `app.dependencies`, el archivo `app/dependencies.py`. + +Así que usamos un import relativo con `..` para las dependencias: + +```Python hl_lines="3" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +#### Cómo funcionan los imports relativos + +/// tip | Consejo + +Si sabes perfectamente cómo funcionan los imports, continúa a la siguiente sección. + +/// + +Un solo punto `.`, como en: + +```Python +from .dependencies import get_token_header +``` + +significaría: + +* Partiendo en el mismo paquete en el que este módulo (el archivo `app/routers/items.py`) habita (el directorio `app/routers/`)... +* busca el módulo `dependencies` (un archivo imaginario en `app/routers/dependencies.py`)... +* y de él, importa la función `get_token_header`. + +Pero ese archivo no existe, nuestras dependencias están en un archivo en `app/dependencies.py`. + +Recuerda cómo se ve nuestra estructura de aplicación/archivo: + + + +--- + +Los dos puntos `..`, como en: + +```Python +from ..dependencies import get_token_header +``` + +significan: + +* Partiendo en el mismo paquete en el que este módulo (el archivo `app/routers/items.py`) habita (el directorio `app/routers/`)... +* ve al paquete padre (el directorio `app/`)... +* y allí, busca el módulo `dependencies` (el archivo en `app/dependencies.py`)... +* y de él, importa la función `get_token_header`. + +¡Eso funciona correctamente! 🎉 + +--- + +De la misma manera, si hubiéramos usado tres puntos `...`, como en: + +```Python +from ...dependencies import get_token_header +``` + +eso significaría: + +* Partiendo en el mismo paquete en el que este módulo (el archivo `app/routers/items.py`) habita (el directorio `app/routers/`)... +* ve al paquete padre (el directorio `app/`)... +* luego ve al paquete padre de ese paquete (no hay paquete padre, `app` es el nivel superior 😱)... +* y allí, busca el módulo `dependencies` (el archivo en `app/dependencies.py`)... +* y de él, importa la función `get_token_header`. + +Eso se referiría a algún paquete arriba de `app/`, con su propio archivo `__init__.py`, etc. Pero no tenemos eso. Así que, eso lanzaría un error en nuestro ejemplo. 🚨 + +Pero ahora sabes cómo funciona, para que puedas usar imports relativos en tus propias aplicaciones sin importar cuán complejas sean. 🤓 + +### Agregar algunos `tags`, `responses`, y `dependencies` personalizados + +No estamos agregando el prefijo `/items` ni los `tags=["items"]` a cada *path operation* porque los hemos añadido al `APIRouter`. + +Pero aún podemos agregar _más_ `tags` que se aplicarán a una *path operation* específica, y también algunas `responses` extra específicas para esa *path operation*: + +```Python hl_lines="30-31" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +/// tip | Consejo + +Esta última *path operation* tendrá la combinación de tags: `["items", "custom"]`. + +Y también tendrá ambas responses en la documentación, una para `404` y otra para `403`. + +/// + +## El `FastAPI` principal + +Ahora, veamos el módulo en `app/main.py`. + +Aquí es donde importas y usas la clase `FastAPI`. + +Este será el archivo principal en tu aplicación que conecta todo. + +### Importar `FastAPI` + +Importas y creas una clase `FastAPI` como de costumbre. + +Y podemos incluso declarar [dependencias globales](dependencies/global-dependencies.md){.internal-link target=_blank} que se combinarán con las dependencias para cada `APIRouter`: + +```Python hl_lines="1 3 7" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +### Importar el `APIRouter` + +Ahora importamos los otros submódulos que tienen `APIRouter`s: + +```Python hl_lines="4-5" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +Como los archivos `app/routers/users.py` y `app/routers/items.py` son submódulos que son parte del mismo paquete de Python `app`, podemos usar un solo punto `.` para importarlos usando "imports relativos". + +### Cómo funciona la importación + +La sección: + +```Python +from .routers import items, users +``` + +significa: + +* Partiendo en el mismo paquete en el que este módulo (el archivo `app/main.py`) habita (el directorio `app/`)... +* busca el subpaquete `routers` (el directorio en `app/routers/`)... +* y de él, importa el submódulo `items` (el archivo en `app/routers/items.py`) y `users` (el archivo en `app/routers/users.py`)... + +El módulo `items` tendrá una variable `router` (`items.router`). Este es el mismo que creamos en el archivo `app/routers/items.py`, es un objeto `APIRouter`. + +Y luego hacemos lo mismo para el módulo `users`. + +También podríamos importarlos así: + +```Python +from app.routers import items, users +``` + +/// info | Información + +La primera versión es un "import relativo": + +```Python +from .routers import items, users +``` + +La segunda versión es un "import absoluto": + +```Python +from app.routers import items, users +``` + +Para aprender más sobre Paquetes y Módulos de Python, lee la documentación oficial de Python sobre Módulos. + +/// + +### Evitar colisiones de nombres + +Estamos importando el submódulo `items` directamente, en lugar de importar solo su variable `router`. + +Esto se debe a que también tenemos otra variable llamada `router` en el submódulo `users`. + +Si hubiéramos importado uno después del otro, como: + +```Python +from .routers.items import router +from .routers.users import router +``` + +el `router` de `users` sobrescribiría el de `items` y no podríamos usarlos al mismo tiempo. + +Así que, para poder usar ambos en el mismo archivo, importamos los submódulos directamente: + +```Python hl_lines="5" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +### Incluir los `APIRouter`s para `users` y `items` + +Ahora, incluyamos los `router`s de los submódulos `users` y `items`: + +```Python hl_lines="10-11" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +/// info | Información + +`users.router` contiene el `APIRouter` dentro del archivo `app/routers/users.py`. + +Y `items.router` contiene el `APIRouter` dentro del archivo `app/routers/items.py`. + +/// + +Con `app.include_router()` podemos agregar cada `APIRouter` a la aplicación principal de `FastAPI`. + +Incluirá todas las rutas de ese router como parte de ella. + +/// note | Detalles Técnicos + +En realidad creará internamente una *path operation* para cada *path operation* que fue declarada en el `APIRouter`. + +Así, detrás de escena, funcionará como si todo fuera la misma única aplicación. + +/// + +/// check | Revisa + +No tienes que preocuparte por el rendimiento al incluir routers. + +Esto tomará microsegundos y solo sucederá al inicio. + +Así que no afectará el rendimiento. ⚡ + +/// + +### Incluir un `APIRouter` con un `prefix`, `tags`, `responses`, y `dependencies` personalizados + +Ahora, imaginemos que tu organización te dio el archivo `app/internal/admin.py`. + +Contiene un `APIRouter` con algunas *path operations* de administración que tu organización comparte entre varios proyectos. + +Para este ejemplo será súper simple. Pero digamos que porque está compartido con otros proyectos en la organización, no podemos modificarlo y agregar un `prefix`, `dependencies`, `tags`, etc. directamente al `APIRouter`: + +```Python hl_lines="3" title="app/internal/admin.py" +{!../../docs_src/bigger_applications/app/internal/admin.py!} +``` + +Pero aún queremos configurar un `prefix` personalizado al incluir el `APIRouter` para que todas sus *path operations* comiencen con `/admin`, queremos asegurarlo con las `dependencies` que ya tenemos para este proyecto, y queremos incluir `tags` y `responses`. + +Podemos declarar todo eso sin tener que modificar el `APIRouter` original pasando esos parámetros a `app.include_router()`: + +```Python hl_lines="14-17" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +De esa manera, el `APIRouter` original permanecerá sin modificar, por lo que aún podemos compartir ese mismo archivo `app/internal/admin.py` con otros proyectos en la organización. + +El resultado es que, en nuestra aplicación, cada una de las *path operations* del módulo `admin` tendrá: + +* El prefix `/admin`. +* El tag `admin`. +* La dependencia `get_token_header`. +* La response `418`. 🍵 + +Pero eso solo afectará a ese `APIRouter` en nuestra aplicación, no en ningún otro código que lo utilice. + +Así, por ejemplo, otros proyectos podrían usar el mismo `APIRouter` con un método de autenticación diferente. + +### Incluir una *path operation* + +También podemos agregar *path operations* directamente a la aplicación de `FastAPI`. + +Aquí lo hacemos... solo para mostrar que podemos 🤷: + +```Python hl_lines="21-23" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +y funcionará correctamente, junto con todas las otras *path operations* añadidas con `app.include_router()`. + +/// info | Detalles Muy Técnicos + +**Nota**: este es un detalle muy técnico que probablemente puedes **simplemente omitir**. + +--- + +Los `APIRouter`s no están "montados", no están aislados del resto de la aplicación. + +Esto se debe a que queremos incluir sus *path operations* en el esquema de OpenAPI y las interfaces de usuario. + +Como no podemos simplemente aislarlos y "montarlos" independientemente del resto, se "clonan" las *path operations* (se vuelven a crear), no se incluyen directamente. + +/// + +## Revisa la documentación automática de la API + +Ahora, ejecuta tu aplicación: + +
+ +```console +$ fastapi dev app/main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Y abre la documentación en http://127.0.0.1:8000/docs. + +Verás la documentación automática de la API, incluyendo los paths de todos los submódulos, usando los paths correctos (y prefijos) y las tags correctas: + + + +## Incluir el mismo router múltiples veces con diferentes `prefix` + +También puedes usar `.include_router()` múltiples veces con el *mismo* router usando diferentes prefijos. + +Esto podría ser útil, por ejemplo, para exponer la misma API bajo diferentes prefijos, por ejemplo, `/api/v1` y `/api/latest`. + +Este es un uso avanzado que quizás no necesites realmente, pero está allí en caso de que lo necesites. + +## Incluir un `APIRouter` en otro + +De la misma manera que puedes incluir un `APIRouter` en una aplicación `FastAPI`, puedes incluir un `APIRouter` en otro `APIRouter` usando: + +```Python +router.include_router(other_router) +``` + +Asegúrate de hacerlo antes de incluir `router` en la aplicación de `FastAPI`, para que las *path operations* de `other_router` también se incluyan. diff --git a/docs/es/docs/tutorial/body-fields.md b/docs/es/docs/tutorial/body-fields.md new file mode 100644 index 000000000..d07d214ec --- /dev/null +++ b/docs/es/docs/tutorial/body-fields.md @@ -0,0 +1,60 @@ +# Body - Campos + +De la misma manera que puedes declarar validaciones adicionales y metadatos en los parámetros de las *path operation function* con `Query`, `Path` y `Body`, puedes declarar validaciones y metadatos dentro de los modelos de Pydantic usando `Field` de Pydantic. + +## Importar `Field` + +Primero, tienes que importarlo: + +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} + +/// warning | Advertencia + +Fíjate que `Field` se importa directamente desde `pydantic`, no desde `fastapi` como el resto (`Query`, `Path`, `Body`, etc). + +/// + +## Declarar atributos del modelo + +Después puedes utilizar `Field` con los atributos del modelo: + +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} + +`Field` funciona de la misma manera que `Query`, `Path` y `Body`, tiene todos los mismos parámetros, etc. + +/// note | Detalles técnicos + +En realidad, `Query`, `Path` y otros que verás a continuación crean objetos de subclases de una clase común `Param`, que es a su vez una subclase de la clase `FieldInfo` de Pydantic. + +Y `Field` de Pydantic también regresa una instance de `FieldInfo`. + +`Body` también devuelve objetos de una subclase de `FieldInfo` directamente. Y hay otros que verás más adelante que son subclases de la clase `Body`. + +Recuerda que cuando importas `Query`, `Path`, y otros desde `fastapi`, en realidad son funciones que devuelven clases especiales. + +/// + +/// tip | Consejo + +Observa cómo cada atributo del modelo con un tipo, un valor por defecto y `Field` tiene la misma estructura que un parámetro de una *path operation function*, con `Field` en lugar de `Path`, `Query` y `Body`. + +/// + +## Agregar información extra + +Puedes declarar información extra en `Field`, `Query`, `Body`, etc. Y será incluida en el JSON Schema generado. + +Aprenderás más sobre cómo agregar información extra más adelante en la documentación, cuando aprendamos a declarar ejemplos. + +/// warning | Advertencia + +Las claves extra pasadas a `Field` también estarán presentes en el esquema de OpenAPI resultante para tu aplicación. +Como estas claves no necesariamente tienen que ser parte de la especificación de OpenAPI, algunas herramientas de OpenAPI, por ejemplo [el validador de OpenAPI](https://validator.swagger.io/), podrían no funcionar con tu esquema generado. + +/// + +## Resumen + +Puedes utilizar `Field` de Pydantic para declarar validaciones adicionales y metadatos para los atributos del modelo. + +También puedes usar los argumentos de palabra clave extra para pasar metadatos adicionales del JSON Schema. diff --git a/docs/es/docs/tutorial/body-multiple-params.md b/docs/es/docs/tutorial/body-multiple-params.md new file mode 100644 index 000000000..df6560b62 --- /dev/null +++ b/docs/es/docs/tutorial/body-multiple-params.md @@ -0,0 +1,173 @@ +# Cuerpo - Múltiples Parámetros + +Ahora que hemos visto cómo usar `Path` y `Query`, veamos usos más avanzados de las declaraciones del request body. + +## Mezclar `Path`, `Query` y parámetros del cuerpo + +Primero, por supuesto, puedes mezclar las declaraciones de parámetros de `Path`, `Query` y del request body libremente y **FastAPI** sabrá qué hacer. + +Y también puedes declarar parámetros del cuerpo como opcionales, estableciendo el valor predeterminado a `None`: + +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} + +## Múltiples parámetros del cuerpo + +/// note | Nota + +Ten en cuenta que, en este caso, el `item` que se tomaría del cuerpo es opcional. Ya que tiene un valor por defecto de `None`. + +/// + +## Múltiples parámetros del cuerpo + +En el ejemplo anterior, las *path operations* esperarían un cuerpo JSON con los atributos de un `Item`, como: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +Pero también puedes declarar múltiples parámetros del cuerpo, por ejemplo `item` y `user`: + +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} + +En este caso, **FastAPI** notará que hay más de un parámetro del cuerpo en la función (hay dos parámetros que son modelos de Pydantic). + +Entonces, usará los nombres de los parámetros como claves (nombres de campo) en el cuerpo, y esperará un cuerpo como: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +/// note | Nota + +Ten en cuenta que aunque el `item` se declaró de la misma manera que antes, ahora se espera que esté dentro del cuerpo con una clave `item`. + +/// + +**FastAPI** hará la conversión automática del request, de modo que el parámetro `item` reciba su contenido específico y lo mismo para `user`. + +Realizará la validación de los datos compuestos, y los documentará así para el esquema de OpenAPI y la documentación automática. + +## Valores singulares en el cuerpo + +De la misma manera que hay un `Query` y `Path` para definir datos extra para parámetros de query y path, **FastAPI** proporciona un equivalente `Body`. + +Por ejemplo, ampliando el modelo anterior, podrías decidir que deseas tener otra clave `importance` en el mismo cuerpo, además de `item` y `user`. + +Si lo declaras tal cual, debido a que es un valor singular, **FastAPI** asumirá que es un parámetro de query. + +Pero puedes instruir a **FastAPI** para que lo trate como otra clave del cuerpo usando `Body`: + +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} + +En este caso, **FastAPI** esperará un cuerpo como: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` + +Nuevamente, convertirá los tipos de datos, validará, documentará, etc. + +## Múltiples parámetros de cuerpo y query + +Por supuesto, también puedes declarar parámetros adicionales de query siempre que lo necesites, además de cualquier parámetro del cuerpo. + +Como, por defecto, los valores singulares se interpretan como parámetros de query, no tienes que añadir explícitamente un `Query`, solo puedes hacer: + +```Python +q: Union[str, None] = None +``` + +O en Python 3.10 y superior: + +```Python +q: str | None = None +``` + +Por ejemplo: + +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *} + +/// info | Información + +`Body` también tiene todos los mismos parámetros de validación y metadatos extras que `Query`, `Path` y otros que verás luego. + +/// + +## Embeber un solo parámetro de cuerpo + +Supongamos que solo tienes un único parámetro de cuerpo `item` de un modelo Pydantic `Item`. + +Por defecto, **FastAPI** esperará su cuerpo directamente. + +Pero si deseas que espere un JSON con una clave `item` y dentro de ella los contenidos del modelo, como lo hace cuando declaras parámetros de cuerpo extra, puedes usar el parámetro especial `Body` `embed`: + +```Python +item: Item = Body(embed=True) +``` + +como en: + +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} + +En este caso, **FastAPI** esperará un cuerpo como: + +```JSON hl_lines="2" +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +en lugar de: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +## Resumen + +Puedes añadir múltiples parámetros de cuerpo a tu *path operation function*, aunque un request solo puede tener un único cuerpo. + +Pero **FastAPI** lo manejará, te dará los datos correctos en tu función, y validará y documentará el esquema correcto en la *path operation*. + +También puedes declarar valores singulares para ser recibidos como parte del cuerpo. + +Y puedes instruir a **FastAPI** para embeber el cuerpo en una clave incluso cuando solo hay un único parámetro declarado. diff --git a/docs/es/docs/tutorial/body-nested-models.md b/docs/es/docs/tutorial/body-nested-models.md new file mode 100644 index 000000000..5b4cfc14c --- /dev/null +++ b/docs/es/docs/tutorial/body-nested-models.md @@ -0,0 +1,247 @@ +# Cuerpo - Modelos Anidados + +Con **FastAPI**, puedes definir, validar, documentar y usar modelos anidados de manera arbitraria (gracias a Pydantic). + +## Campos de lista + +Puedes definir un atributo como un subtipo. Por ejemplo, una `list` en Python: + +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} + +Esto hará que `tags` sea una lista, aunque no declare el tipo de los elementos de la lista. + +## Campos de lista con parámetro de tipo + +Pero Python tiene una forma específica de declarar listas con tipos internos, o "parámetros de tipo": + +### Importar `List` de typing + +En Python 3.9 y superior, puedes usar el `list` estándar para declarar estas anotaciones de tipo como veremos a continuación. 💡 + +Pero en versiones de Python anteriores a 3.9 (desde 3.6 en adelante), primero necesitas importar `List` del módulo `typing` estándar de Python: + +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} + +### Declarar una `list` con un parámetro de tipo + +Para declarar tipos que tienen parámetros de tipo (tipos internos), como `list`, `dict`, `tuple`: + +* Si estás en una versión de Python inferior a 3.9, importa su versión equivalente del módulo `typing` +* Pasa el/los tipo(s) interno(s) como "parámetros de tipo" usando corchetes: `[` y `]` + +En Python 3.9 sería: + +```Python +my_list: list[str] +``` + +En versiones de Python anteriores a 3.9, sería: + +```Python +from typing import List + +my_list: List[str] +``` + +Eso es toda la sintaxis estándar de Python para declaraciones de tipo. + +Usa esa misma sintaxis estándar para atributos de modelos con tipos internos. + +Así, en nuestro ejemplo, podemos hacer que `tags` sea específicamente una "lista de strings": + +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} + +## Tipos de conjunto + +Pero luego pensamos en ello, y nos damos cuenta de que los tags no deberían repetirse, probablemente serían strings únicos. + +Y Python tiene un tipo de datos especial para conjuntos de elementos únicos, el `set`. + +Entonces podemos declarar `tags` como un conjunto de strings: + +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} + +Con esto, incluso si recibes un request con datos duplicados, se convertirá en un conjunto de elementos únicos. + +Y siempre que emitas esos datos, incluso si la fuente tenía duplicados, se emitirá como un conjunto de elementos únicos. + +Y también se anotará/documentará en consecuencia. + +## Modelos Anidados + +Cada atributo de un modelo Pydantic tiene un tipo. + +Pero ese tipo puede ser en sí mismo otro modelo Pydantic. + +Así que, puedes declarar "objetos" JSON anidados profundamente con nombres de atributos específicos, tipos y validaciones. + +Todo eso, de manera arbitraria. + +### Definir un submodelo + +Por ejemplo, podemos definir un modelo `Image`: + +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} + +### Usar el submodelo como tipo + +Y luego podemos usarlo como el tipo de un atributo: + +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} + +Esto significaría que **FastAPI** esperaría un cuerpo similar a: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": ["rock", "metal", "bar"], + "image": { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + } +} +``` + +Nuevamente, haciendo solo esa declaración, con **FastAPI** obtienes: + +* Soporte de editor (autocompletado, etc.), incluso para modelos anidados +* Conversión de datos +* Validación de datos +* Documentación automática + +## Tipos especiales y validación + +Además de tipos singulares normales como `str`, `int`, `float`, etc., puedes usar tipos singulares más complejos que heredan de `str`. + +Para ver todas las opciones que tienes, revisa el Overview de Tipos de Pydantic. Verás algunos ejemplos en el siguiente capítulo. + +Por ejemplo, como en el modelo `Image` tenemos un campo `url`, podemos declararlo como una instance de `HttpUrl` de Pydantic en lugar de un `str`: + +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} + +El string será verificado para ser una URL válida, y documentado en JSON Schema / OpenAPI como tal. + +## Atributos con listas de submodelos + +También puedes usar modelos Pydantic como subtipos de `list`, `set`, etc.: + +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} + +Esto esperará (convertirá, validará, documentará, etc.) un cuerpo JSON como: + +```JSON hl_lines="11" +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": [ + "rock", + "metal", + "bar" + ], + "images": [ + { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + }, + { + "url": "http://example.com/dave.jpg", + "name": "The Baz" + } + ] +} +``` + +/// info | Información + +Nota cómo la clave `images` ahora tiene una lista de objetos de imagen. + +/// + +## Modelos anidados profundamente + +Puedes definir modelos anidados tan profundamente como desees: + +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} + +/// info | Información + +Observa cómo `Offer` tiene una lista de `Item`s, que a su vez tienen una lista opcional de `Image`s + +/// + +## Cuerpos de listas puras + +Si el valor superior del cuerpo JSON que esperas es un `array` JSON (una `list` en Python), puedes declarar el tipo en el parámetro de la función, al igual que en los modelos Pydantic: + +```Python +images: List[Image] +``` + +o en Python 3.9 y superior: + +```Python +images: list[Image] +``` + +como en: + +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} + +## Soporte de editor en todas partes + +Y obtienes soporte de editor en todas partes. + +Incluso para elementos dentro de listas: + + + +No podrías obtener este tipo de soporte de editor si estuvieras trabajando directamente con `dict` en lugar de modelos Pydantic. + +Pero tampoco tienes que preocuparte por ellos, los `dicts` entrantes se convierten automáticamente y tu salida se convierte automáticamente a JSON también. + +## Cuerpos de `dict`s arbitrarios + +También puedes declarar un cuerpo como un `dict` con claves de algún tipo y valores de algún otro tipo. + +De esta manera, no tienes que saber de antemano cuáles son los nombres válidos de campo/atributo (como sería el caso con modelos Pydantic). + +Esto sería útil si deseas recibir claves que aún no conoces. + +--- + +Otro caso útil es cuando deseas tener claves de otro tipo (por ejemplo, `int`). + +Eso es lo que vamos a ver aquí. + +En este caso, aceptarías cualquier `dict` siempre que tenga claves `int` con valores `float`: + +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} + +/// tip | Consejo + +Ten en cuenta que JSON solo admite `str` como claves. + +Pero Pydantic tiene conversión automática de datos. + +Esto significa que, aunque tus clientes de API solo pueden enviar strings como claves, mientras esos strings contengan enteros puros, Pydantic los convertirá y validará. + +Y el `dict` que recibas como `weights` tendrá realmente claves `int` y valores `float`. + +/// + +## Resumen + +Con **FastAPI** tienes la máxima flexibilidad proporcionada por los modelos Pydantic, manteniendo tu código simple, corto y elegante. + +Pero con todos los beneficios: + +* Soporte de editor (¡autocompletado en todas partes!) +* Conversión de datos (también conocido como parsing/serialización) +* Validación de datos +* Documentación del esquema +* Documentación automática diff --git a/docs/es/docs/tutorial/body-updates.md b/docs/es/docs/tutorial/body-updates.md new file mode 100644 index 000000000..26cd3345f --- /dev/null +++ b/docs/es/docs/tutorial/body-updates.md @@ -0,0 +1,116 @@ +# Cuerpo - Actualizaciones + +## Actualización reemplazando con `PUT` + +Para actualizar un ítem puedes utilizar la operación de HTTP `PUT`. + +Puedes usar el `jsonable_encoder` para convertir los datos de entrada en datos que se puedan almacenar como JSON (por ejemplo, con una base de datos NoSQL). Por ejemplo, convirtiendo `datetime` a `str`. + +{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *} + +`PUT` se usa para recibir datos que deben reemplazar los datos existentes. + +### Advertencia sobre el reemplazo + +Esto significa que si quieres actualizar el ítem `bar` usando `PUT` con un body que contenga: + +```Python +{ + "name": "Barz", + "price": 3, + "description": None, +} +``` + +debido a que no incluye el atributo ya almacenado `"tax": 20.2`, el modelo de entrada tomaría el valor por defecto de `"tax": 10.5`. + +Y los datos se guardarían con ese "nuevo" `tax` de `10.5`. + +## Actualizaciones parciales con `PATCH` + +También puedes usar la operación de HTTP `PATCH` para actualizar *parcialmente* datos. + +Esto significa que puedes enviar solo los datos que deseas actualizar, dejando el resto intacto. + +/// note | Nota + +`PATCH` es menos usado y conocido que `PUT`. + +Y muchos equipos utilizan solo `PUT`, incluso para actualizaciones parciales. + +Eres **libre** de usarlos como desees, **FastAPI** no impone ninguna restricción. + +Pero esta guía te muestra, más o menos, cómo se pretende que se usen. + +/// + +### Uso del parámetro `exclude_unset` de Pydantic + +Si quieres recibir actualizaciones parciales, es muy útil usar el parámetro `exclude_unset` en el `.model_dump()` del modelo de Pydantic. + +Como `item.model_dump(exclude_unset=True)`. + +/// info | Información + +En Pydantic v1 el método se llamaba `.dict()`, fue deprecado (pero aún soportado) en Pydantic v2, y renombrado a `.model_dump()`. + +Los ejemplos aquí usan `.dict()` para compatibilidad con Pydantic v1, pero deberías usar `.model_dump()` si puedes usar Pydantic v2. + +/// + +Eso generaría un `dict` solo con los datos que se establecieron al crear el modelo `item`, excluyendo los valores por defecto. + +Luego puedes usar esto para generar un `dict` solo con los datos que se establecieron (enviados en el request), omitiendo los valores por defecto: + +{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *} + +### Uso del parámetro `update` de Pydantic + +Ahora, puedes crear una copia del modelo existente usando `.model_copy()`, y pasar el parámetro `update` con un `dict` que contenga los datos a actualizar. + +/// info | Información + +En Pydantic v1 el método se llamaba `.copy()`, fue deprecado (pero aún soportado) en Pydantic v2, y renombrado a `.model_copy()`. + +Los ejemplos aquí usan `.copy()` para compatibilidad con Pydantic v1, pero deberías usar `.model_copy()` si puedes usar Pydantic v2. + +/// + +Como `stored_item_model.model_copy(update=update_data)`: + +{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *} + +### Resumen de actualizaciones parciales + +En resumen, para aplicar actualizaciones parciales deberías: + +* (Opcionalmente) usar `PATCH` en lugar de `PUT`. +* Recuperar los datos almacenados. +* Poner esos datos en un modelo de Pydantic. +* Generar un `dict` sin valores por defecto del modelo de entrada (usando `exclude_unset`). + * De esta manera puedes actualizar solo los valores realmente establecidos por el usuario, en lugar de sobrescribir valores ya almacenados con valores por defecto en tu modelo. +* Crear una copia del modelo almacenado, actualizando sus atributos con las actualizaciones parciales recibidas (usando el parámetro `update`). +* Convertir el modelo copiado en algo que pueda almacenarse en tu base de datos (por ejemplo, usando el `jsonable_encoder`). + * Esto es comparable a usar el método `.model_dump()` del modelo de nuevo, pero asegura (y convierte) los valores a tipos de datos que pueden convertirse a JSON, por ejemplo, `datetime` a `str`. +* Guardar los datos en tu base de datos. +* Devolver el modelo actualizado. + +{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *} + +/// tip | Consejo + +Puedes realmente usar esta misma técnica con una operación HTTP `PUT`. + +Pero el ejemplo aquí usa `PATCH` porque fue creado para estos casos de uso. + +/// + +/// note | Nota + +Observa que el modelo de entrada sigue siendo validado. + +Entonces, si deseas recibir actualizaciones parciales que puedan omitir todos los atributos, necesitas tener un modelo con todos los atributos marcados como opcionales (con valores por defecto o `None`). + +Para distinguir entre los modelos con todos los valores opcionales para **actualizaciones** y modelos con valores requeridos para **creación**, puedes utilizar las ideas descritas en [Modelos Extra](extra-models.md){.internal-link target=_blank}. + +/// diff --git a/docs/es/docs/tutorial/body.md b/docs/es/docs/tutorial/body.md new file mode 100644 index 000000000..6d0aa7c60 --- /dev/null +++ b/docs/es/docs/tutorial/body.md @@ -0,0 +1,164 @@ +# Request Body + +Cuando necesitas enviar datos desde un cliente (digamos, un navegador) a tu API, los envías como un **request body**. + +Un **request** body es un dato enviado por el cliente a tu API. Un **response** body es el dato que tu API envía al cliente. + +Tu API casi siempre tiene que enviar un **response** body. Pero los clientes no necesariamente necesitan enviar **request bodies** todo el tiempo, a veces solo solicitan un path, quizás con algunos parámetros de query, pero no envían un body. + +Para declarar un **request** body, usas modelos de Pydantic con todo su poder y beneficios. + +/// info | Información + +Para enviar datos, deberías usar uno de estos métodos: `POST` (el más común), `PUT`, `DELETE` o `PATCH`. + +Enviar un body con un request `GET` tiene un comportamiento indefinido en las especificaciones, no obstante, es soportado por FastAPI, solo para casos de uso muy complejos/extremos. + +Como no se recomienda, la documentación interactiva con Swagger UI no mostrará la documentación para el body cuando se usa `GET`, y los proxies intermedios podrían no soportarlo. + +/// + +## Importar `BaseModel` de Pydantic + +Primero, necesitas importar `BaseModel` de `pydantic`: + +{* ../../docs_src/body/tutorial001_py310.py hl[2] *} + +## Crea tu modelo de datos + +Luego, declaras tu modelo de datos como una clase que hereda de `BaseModel`. + +Usa tipos estándar de Python para todos los atributos: + +{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *} + +Al igual que al declarar parámetros de query, cuando un atributo del modelo tiene un valor por defecto, no es obligatorio. De lo contrario, es obligatorio. Usa `None` para hacerlo opcional. + +Por ejemplo, el modelo anterior declara un “`object`” JSON (o `dict` en Python) como: + +```JSON +{ + "name": "Foo", + "description": "An optional description", + "price": 45.2, + "tax": 3.5 +} +``` + +...dado que `description` y `tax` son opcionales (con un valor por defecto de `None`), este “`object`” JSON también sería válido: + +```JSON +{ + "name": "Foo", + "price": 45.2 +} +``` + +## Decláralo como un parámetro + +Para añadirlo a tu *path operation*, decláralo de la misma manera que declaraste parámetros de path y query: + +{* ../../docs_src/body/tutorial001_py310.py hl[16] *} + +...y declara su tipo como el modelo que creaste, `Item`. + +## Resultados + +Con solo esa declaración de tipo en Python, **FastAPI** hará lo siguiente: + +* Leer el body del request como JSON. +* Convertir los tipos correspondientes (si es necesario). +* Validar los datos. + * Si los datos son inválidos, devolverá un error claro e indicado, señalando exactamente dónde y qué fue lo incorrecto. +* Proporcionar los datos recibidos en el parámetro `item`. + * Como lo declaraste en la función como de tipo `Item`, también tendrás todo el soporte del editor (autocompletado, etc.) para todos los atributos y sus tipos. +* Generar definiciones de JSON Schema para tu modelo, que también puedes usar en cualquier otro lugar si tiene sentido para tu proyecto. +* Esquemas que serán parte del esquema de OpenAPI generado y usados por la UIs de documentación automática. + +## Documentación automática + +Los JSON Schemas de tus modelos serán parte del esquema OpenAPI generado y se mostrarán en la documentación API interactiva: + + + +Y también se utilizarán en la documentación API dentro de cada *path operation* que los necesite: + + + +## Soporte del editor + +En tu editor, dentro de tu función, obtendrás anotaciones de tipos y autocompletado en todas partes (esto no sucedería si recibieras un `dict` en lugar de un modelo de Pydantic): + + + +También recibirás chequeos de errores para operaciones de tipo incorrecto: + + + +No es por casualidad, todo el framework fue construido alrededor de ese diseño. + +Y fue rigurosamente probado en la fase de diseño, antes de cualquier implementación, para garantizar que funcionaría con todos los editores. + +Incluso se hicieron algunos cambios en Pydantic para admitir esto. + +Las capturas de pantalla anteriores se tomaron con Visual Studio Code. + +Pero obtendrías el mismo soporte en el editor con PyCharm y la mayoría de los otros editores de Python: + + + +/// tip | Consejo + +Si usas PyCharm como tu editor, puedes usar el Pydantic PyCharm Plugin. + +Mejora el soporte del editor para modelos de Pydantic, con: + +* autocompletado +* chequeo de tipos +* refactorización +* búsqueda +* inspecciones + +/// + +## Usa el modelo + +Dentro de la función, puedes acceder a todos los atributos del objeto modelo directamente: + +{* ../../docs_src/body/tutorial002_py310.py *} + +## Request body + parámetros de path + +Puedes declarar parámetros de path y request body al mismo tiempo. + +**FastAPI** reconocerá que los parámetros de función que coinciden con los parámetros de path deben ser **tomados del path**, y que los parámetros de función que se declaran como modelos de Pydantic deben ser **tomados del request body**. + +{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *} + +## Request body + path + parámetros de query + +También puedes declarar parámetros de **body**, **path** y **query**, todos al mismo tiempo. + +**FastAPI** reconocerá cada uno de ellos y tomará los datos del lugar correcto. + +{* ../../docs_src/body/tutorial004_py310.py hl[16] *} + +Los parámetros de la función se reconocerán de la siguiente manera: + +* Si el parámetro también se declara en el **path**, se utilizará como un parámetro de path. +* Si el parámetro es de un **tipo singular** (como `int`, `float`, `str`, `bool`, etc.), se interpretará como un parámetro de **query**. +* Si el parámetro se declara como del tipo de un **modelo de Pydantic**, se interpretará como un **request body**. + +/// note | Nota + +FastAPI sabrá que el valor de `q` no es requerido debido al valor por defecto `= None`. + +El `str | None` (Python 3.10+) o `Union` en `Union[str, None]` (Python 3.8+) no es utilizado por FastAPI para determinar que el valor no es requerido, sabrá que no es requerido porque tiene un valor por defecto de `= None`. + +Pero agregar las anotaciones de tipos permitirá que tu editor te brinde un mejor soporte y detecte errores. + +/// + +## Sin Pydantic + +Si no quieres usar modelos de Pydantic, también puedes usar parámetros **Body**. Consulta la documentación para [Body - Multiples Parametros: Valores singulares en body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}. diff --git a/docs/es/docs/tutorial/cookie-param-models.md b/docs/es/docs/tutorial/cookie-param-models.md new file mode 100644 index 000000000..ebdb59265 --- /dev/null +++ b/docs/es/docs/tutorial/cookie-param-models.md @@ -0,0 +1,76 @@ +# Modelos de Cookies + +Si tienes un grupo de **cookies** que están relacionadas, puedes crear un **modelo de Pydantic** para declararlas. 🍪 + +Esto te permitirá **reutilizar el modelo** en **múltiples lugares** y también declarar validaciones y metadatos para todos los parámetros a la vez. 😎 + +/// note | Nota + +Esto es compatible desde la versión `0.115.0` de FastAPI. 🤓 + +/// + +/// tip | Consejo + +Esta misma técnica se aplica a `Query`, `Cookie`, y `Header`. 😎 + +/// + +## Cookies con un Modelo de Pydantic + +Declara los parámetros de **cookie** que necesites en un **modelo de Pydantic**, y luego declara el parámetro como `Cookie`: + +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} + +**FastAPI** **extraerá** los datos para **cada campo** de las **cookies** recibidas en el request y te entregará el modelo de Pydantic que definiste. + +## Revisa la Documentación + +Puedes ver las cookies definidas en la UI de la documentación en `/docs`: + +
+ +
+ +/// info | Información + +Ten en cuenta que, como los **navegadores manejan las cookies** de maneras especiales y detrás de escenas, **no** permiten fácilmente que **JavaScript** las toque. + +Si vas a la **UI de la documentación de la API** en `/docs` podrás ver la **documentación** de las cookies para tus *path operations*. + +Pero incluso si **rellenas los datos** y haces clic en "Execute", como la UI de la documentación funciona con **JavaScript**, las cookies no serán enviadas y verás un **mensaje de error** como si no hubieras escrito ningún valor. + +/// + +## Prohibir Cookies Extra + +En algunos casos de uso especiales (probablemente no muy comunes), podrías querer **restringir** las cookies que deseas recibir. + +Tu API ahora tiene el poder de controlar su propio consentimiento de cookies. 🤪🍪 + +Puedes usar la configuración del modelo de Pydantic para `prohibir` cualquier campo `extra`: + +{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *} + +Si un cliente intenta enviar algunas **cookies extra**, recibirán un response de **error**. + +Pobres banners de cookies con todo su esfuerzo para obtener tu consentimiento para que la API lo rechace. 🍪 + +Por ejemplo, si el cliente intenta enviar una cookie `santa_tracker` con un valor de `good-list-please`, el cliente recibirá un response de **error** que le informa que la cookie `santa_tracker` no está permitida: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "santa_tracker"], + "msg": "Extra inputs are not permitted", + "input": "good-list-please", + } + ] +} +``` + +## Resumen + +Puedes usar **modelos de Pydantic** para declarar **cookies** en **FastAPI**. 😎 diff --git a/docs/es/docs/tutorial/cors.md b/docs/es/docs/tutorial/cors.md new file mode 100644 index 000000000..e493d4431 --- /dev/null +++ b/docs/es/docs/tutorial/cors.md @@ -0,0 +1,85 @@ +# CORS (Cross-Origin Resource Sharing) + +CORS o "Cross-Origin Resource Sharing" se refiere a situaciones en las que un frontend que se ejecuta en un navegador tiene código JavaScript que se comunica con un backend, y el backend está en un "origen" diferente al frontend. + +## Origen + +Un origen es la combinación de protocolo (`http`, `https`), dominio (`myapp.com`, `localhost`, `localhost.tiangolo.com`) y puerto (`80`, `443`, `8080`). + +Así que, todos estos son orígenes diferentes: + +* `http://localhost` +* `https://localhost` +* `http://localhost:8080` + +Aunque todos están en `localhost`, usan protocolos o puertos diferentes, por lo tanto, son "orígenes" diferentes. + +## Pasos + +Entonces, digamos que tienes un frontend corriendo en tu navegador en `http://localhost:8080`, y su JavaScript está tratando de comunicarse con un backend corriendo en `http://localhost` (porque no especificamos un puerto, el navegador asumirá el puerto por defecto `80`). + +Entonces, el navegador enviará un request HTTP `OPTIONS` al backend `:80`, y si el backend envía los headers apropiados autorizando la comunicación desde este origen diferente (`http://localhost:8080`), entonces el navegador `:8080` permitirá que el JavaScript en el frontend envíe su request al backend `:80`. + +Para lograr esto, el backend `:80` debe tener una lista de "orígenes permitidos". + +En este caso, la lista tendría que incluir `http://localhost:8080` para que el frontend `:8080` funcione correctamente. + +## Comodines + +También es posible declarar la lista como `"*"` (un "comodín") para decir que todos están permitidos. + +Pero eso solo permitirá ciertos tipos de comunicación, excluyendo todo lo que implique credenciales: Cookies, headers de autorización como los utilizados con Bearer Tokens, etc. + +Así que, para que todo funcione correctamente, es mejor especificar explícitamente los orígenes permitidos. + +## Usa `CORSMiddleware` + +Puedes configurarlo en tu aplicación **FastAPI** usando el `CORSMiddleware`. + +* Importa `CORSMiddleware`. +* Crea una lista de orígenes permitidos (como strings). +* Agrégalo como un "middleware" a tu aplicación **FastAPI**. + +También puedes especificar si tu backend permite: + +* Credenciales (headers de autorización, cookies, etc). +* Métodos HTTP específicos (`POST`, `PUT`) o todos ellos con el comodín `"*"`. +* Headers HTTP específicos o todos ellos con el comodín `"*"`. + +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} + +Los parámetros predeterminados utilizados por la implementación de `CORSMiddleware` son restrictivos por defecto, por lo que necesitarás habilitar explícitamente orígenes, métodos o headers particulares para que los navegadores estén permitidos de usarlos en un contexto de Cross-Domain. + +Se admiten los siguientes argumentos: + +* `allow_origins` - Una lista de orígenes que deberían estar permitidos para hacer requests cross-origin. Por ejemplo, `['https://example.org', 'https://www.example.org']`. Puedes usar `['*']` para permitir cualquier origen. +* `allow_origin_regex` - Una cadena regex para coincidir con orígenes que deberían estar permitidos para hacer requests cross-origin. por ejemplo, `'https://.*\.example\.org'`. +* `allow_methods` - Una lista de métodos HTTP que deberían estar permitidos para requests cross-origin. Por defecto es `['GET']`. Puedes usar `['*']` para permitir todos los métodos estándar. +* `allow_headers` - Una lista de headers de request HTTP que deberían estar soportados para requests cross-origin. Por defecto es `[]`. Puedes usar `['*']` para permitir todos los headers. Los headers `Accept`, `Accept-Language`, `Content-Language` y `Content-Type` siempre están permitidos para requests CORS simples. +* `allow_credentials` - Indica que las cookies deberían estar soportadas para requests cross-origin. Por defecto es `False`. Además, `allow_origins` no puede ser configurado a `['*']` para que las credenciales estén permitidas, los orígenes deben ser especificados. +* `expose_headers` - Indica cualquier header de response que debería ser accesible para el navegador. Por defecto es `[]`. +* `max_age` - Establece un tiempo máximo en segundos para que los navegadores almacenen en caché los responses CORS. Por defecto es `600`. + +El middleware responde a dos tipos particulares de request HTTP... + +### Requests de preflight CORS + +Estos son cualquier request `OPTIONS` con headers `Origin` y `Access-Control-Request-Method`. + +En este caso, el middleware interceptará el request entrante y responderá con los headers CORS adecuados, y un response `200` o `400` con fines informativos. + +### Requests simples + +Cualquier request con un header `Origin`. En este caso, el middleware pasará el request a través de lo normal, pero incluirá los headers CORS adecuados en el response. + +## Más info + +Para más información sobre CORS, revisa la documentación de CORS de Mozilla. + +/// note | Detalles Técnicos + +También podrías usar `from starlette.middleware.cors import CORSMiddleware`. + +**FastAPI** proporciona varios middlewares en `fastapi.middleware` como una conveniencia para ti, el desarrollador. Pero la mayoría de los middlewares disponibles provienen directamente de Starlette. + +/// diff --git a/docs/es/docs/tutorial/debugging.md b/docs/es/docs/tutorial/debugging.md new file mode 100644 index 000000000..2a7544e83 --- /dev/null +++ b/docs/es/docs/tutorial/debugging.md @@ -0,0 +1,113 @@ +# Depuración + +Puedes conectar el depurador en tu editor, por ejemplo con Visual Studio Code o PyCharm. + +## Llama a `uvicorn` + +En tu aplicación de FastAPI, importa y ejecuta `uvicorn` directamente: + +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} + +### Acerca de `__name__ == "__main__"` + +El objetivo principal de `__name__ == "__main__"` es tener algo de código que se ejecute cuando tu archivo es llamado con: + +
+ +```console +$ python myapp.py +``` + +
+ +pero no es llamado cuando otro archivo lo importa, como en: + +```Python +from myapp import app +``` + +#### Más detalles + +Supongamos que tu archivo se llama `myapp.py`. + +Si lo ejecutas con: + +
+ +```console +$ python myapp.py +``` + +
+ +entonces la variable interna `__name__` en tu archivo, creada automáticamente por Python, tendrá como valor el string `"__main__"`. + +Así que, la sección: + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +se ejecutará. + +--- + +Esto no ocurrirá si importas ese módulo (archivo). + +Entonces, si tienes otro archivo `importer.py` con: + +```Python +from myapp import app + +# Algún código adicional +``` + +en ese caso, la variable creada automáticamente dentro de `myapp.py` no tendrá la variable `__name__` con un valor de `"__main__"`. + +Así que, la línea: + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +no se ejecutará. + +/// info | Información + +Para más información, revisa la documentación oficial de Python. + +/// + +## Ejecuta tu código con tu depurador + +Dado que estás ejecutando el servidor Uvicorn directamente desde tu código, puedes llamar a tu programa de Python (tu aplicación FastAPI) directamente desde el depurador. + +--- + +Por ejemplo, en Visual Studio Code, puedes: + +* Ir al panel de "Debug". +* "Add configuration...". +* Seleccionar "Python". +* Ejecutar el depurador con la opción "`Python: Current File (Integrated Terminal)`". + +Luego, iniciará el servidor con tu código **FastAPI**, deteniéndose en tus puntos de interrupción, etc. + +Así es como podría verse: + + + +--- + +Si usas PyCharm, puedes: + +* Abrir el menú "Run". +* Seleccionar la opción "Debug...". +* Luego aparece un menú contextual. +* Selecciona el archivo para depurar (en este caso, `main.py`). + +Luego, iniciará el servidor con tu código **FastAPI**, deteniéndose en tus puntos de interrupción, etc. + +Así es como podría verse: + + diff --git a/docs/es/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/es/docs/tutorial/dependencies/classes-as-dependencies.md new file mode 100644 index 000000000..d0868240e --- /dev/null +++ b/docs/es/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,288 @@ +# Clases como dependencias + +Antes de profundizar en el sistema de **Inyección de Dependencias**, vamos a mejorar el ejemplo anterior. + +## Un `dict` del ejemplo anterior + +En el ejemplo anterior, estábamos devolviendo un `dict` de nuestra dependencia ("dependable"): + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *} + +Pero luego obtenemos un `dict` en el parámetro `commons` de la *path operation function*. + +Y sabemos que los editores no pueden proporcionar mucho soporte (como autocompletado) para `dict`s, porque no pueden conocer sus claves y tipos de valor. + +Podemos hacerlo mejor... + +## Qué hace a una dependencia + +Hasta ahora has visto dependencias declaradas como funciones. + +Pero esa no es la única forma de declarar dependencias (aunque probablemente sea la más común). + +El factor clave es que una dependencia debe ser un "callable". + +Un "**callable**" en Python es cualquier cosa que Python pueda "llamar" como una función. + +Entonces, si tienes un objeto `something` (que podría _no_ ser una función) y puedes "llamarlo" (ejecutarlo) como: + +```Python +something() +``` + +o + +```Python +something(some_argument, some_keyword_argument="foo") +``` + +entonces es un "callable". + +## Clases como dependencias + +Puedes notar que para crear una instance de una clase en Python, utilizas esa misma sintaxis. + +Por ejemplo: + +```Python +class Cat: + def __init__(self, name: str): + self.name = name + + +fluffy = Cat(name="Mr Fluffy") +``` + +En este caso, `fluffy` es una instance de la clase `Cat`. + +Y para crear `fluffy`, estás "llamando" a `Cat`. + +Entonces, una clase en Python también es un **callable**. + +Entonces, en **FastAPI**, podrías usar una clase de Python como una dependencia. + +Lo que **FastAPI** realmente comprueba es que sea un "callable" (función, clase o cualquier otra cosa) y los parámetros definidos. + +Si pasas un "callable" como dependencia en **FastAPI**, analizará los parámetros de ese "callable", y los procesará de la misma manera que los parámetros de una *path operation function*. Incluyendo sub-dependencias. + +Eso también se aplica a los callables sin parámetros. Igual que sería para *path operation functions* sin parámetros. + +Entonces, podemos cambiar la dependencia "dependable" `common_parameters` de arriba a la clase `CommonQueryParams`: + +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *} + +Presta atención al método `__init__` usado para crear la instance de la clase: + +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *} + +...tiene los mismos parámetros que nuestros `common_parameters` anteriores: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *} + +Esos parámetros son los que **FastAPI** usará para "resolver" la dependencia. + +En ambos casos, tendrá: + +* Un parámetro de query `q` opcional que es un `str`. +* Un parámetro de query `skip` que es un `int`, con un valor por defecto de `0`. +* Un parámetro de query `limit` que es un `int`, con un valor por defecto de `100`. + +En ambos casos, los datos serán convertidos, validados, documentados en el esquema de OpenAPI, etc. + +## Úsalo + +Ahora puedes declarar tu dependencia usando esta clase. + +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *} + +**FastAPI** llama a la clase `CommonQueryParams`. Esto crea una "instance" de esa clase y la instance será pasada como el parámetro `commons` a tu función. + +## Anotación de tipos vs `Depends` + +Nota cómo escribimos `CommonQueryParams` dos veces en el código anterior: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ sin `Annotated` + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// + +El último `CommonQueryParams`, en: + +```Python +... Depends(CommonQueryParams) +``` + +...es lo que **FastAPI** utilizará realmente para saber cuál es la dependencia. + +Es a partir de este que **FastAPI** extraerá los parámetros declarados y es lo que **FastAPI** realmente llamará. + +--- + +En este caso, el primer `CommonQueryParams`, en: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, ... +``` + +//// + +//// tab | Python 3.8+ sin `Annotated` + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +```Python +commons: CommonQueryParams ... +``` + +//// + +...no tiene ningún significado especial para **FastAPI**. **FastAPI** no lo usará para la conversión de datos, validación, etc. (ya que está usando `Depends(CommonQueryParams)` para eso). + +De hecho, podrías escribir simplemente: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[Any, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ sin `Annotated` + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +```Python +commons = Depends(CommonQueryParams) +``` + +//// + +...como en: + +{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *} + +Pero declarar el tipo es recomendable, ya que de esa manera tu editor sabrá lo que se pasará como el parámetro `commons`, y entonces podrá ayudarte con el autocompletado, chequeo de tipos, etc: + + + +## Atajo + +Pero ves que estamos teniendo algo de repetición de código aquí, escribiendo `CommonQueryParams` dos veces: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ sin `Annotated` + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// + +**FastAPI** proporciona un atajo para estos casos, en donde la dependencia es *específicamente* una clase que **FastAPI** "llamará" para crear una instance de la clase misma. + +Para esos casos específicos, puedes hacer lo siguiente: + +En lugar de escribir: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ sin `Annotated` + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// + +...escribes: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends()] +``` + +//// + +//// tab | Python 3.8 sin `Annotated` + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +```Python +commons: CommonQueryParams = Depends() +``` + +//// + +Declaras la dependencia como el tipo del parámetro, y usas `Depends()` sin ningún parámetro, en lugar de tener que escribir la clase completa *otra vez* dentro de `Depends(CommonQueryParams)`. + +El mismo ejemplo se vería entonces así: + +{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *} + +...y **FastAPI** sabrá qué hacer. + +/// tip | Consejo + +Si eso parece más confuso que útil, ignóralo, no lo *necesitas*. + +Es solo un atajo. Porque a **FastAPI** le importa ayudarte a minimizar la repetición de código. + +/// diff --git a/docs/es/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/es/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md new file mode 100644 index 000000000..fbe17c67a --- /dev/null +++ b/docs/es/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -0,0 +1,69 @@ +# Dependencias en decoradores de *path operation* + +En algunos casos realmente no necesitas el valor de retorno de una dependencia dentro de tu *path operation function*. + +O la dependencia no devuelve un valor. + +Pero aún necesitas que sea ejecutada/resuelta. + +Para esos casos, en lugar de declarar un parámetro de *path operation function* con `Depends`, puedes añadir una `list` de `dependencies` al decorador de *path operation*. + +## Agregar `dependencies` al decorador de *path operation* + +El decorador de *path operation* recibe un argumento opcional `dependencies`. + +Debe ser una `list` de `Depends()`: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *} + +Estas dependencias serán ejecutadas/resueltas de la misma manera que las dependencias normales. Pero su valor (si devuelven alguno) no será pasado a tu *path operation function*. + +/// tip | Consejo + +Algunos editores revisan los parámetros de función no usados y los muestran como errores. + +Usando estas `dependencies` en el decorador de *path operation* puedes asegurarte de que se ejecutan mientras evitas errores en editores/herramientas. + +También puede ayudar a evitar confusiones para nuevos desarrolladores que vean un parámetro no usado en tu código y puedan pensar que es innecesario. + +/// + +/// info | Información + +En este ejemplo usamos headers personalizados inventados `X-Key` y `X-Token`. + +Pero en casos reales, al implementar seguridad, obtendrías más beneficios usando las [Utilidades de Seguridad integradas (el próximo capítulo)](../security/index.md){.internal-link target=_blank}. + +/// + +## Errores de dependencias y valores de retorno + +Puedes usar las mismas *funciones* de dependencia que usas normalmente. + +### Requisitos de dependencia + +Pueden declarar requisitos de request (como headers) u otras sub-dependencias: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *} + +### Lanzar excepciones + +Estas dependencias pueden `raise` excepciones, igual que las dependencias normales: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *} + +### Valores de retorno + +Y pueden devolver valores o no, los valores no serán usados. + +Así que, puedes reutilizar una dependencia normal (que devuelve un valor) que ya uses en otro lugar, y aunque el valor no se use, la dependencia será ejecutada: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *} + +## Dependencias para un grupo de *path operations* + +Más adelante, cuando leas sobre cómo estructurar aplicaciones más grandes ([Aplicaciones Más Grandes - Múltiples Archivos](../../tutorial/bigger-applications.md){.internal-link target=_blank}), posiblemente con múltiples archivos, aprenderás cómo declarar un único parámetro `dependencies` para un grupo de *path operations*. + +## Dependencias Globales + +A continuación veremos cómo añadir dependencias a toda la aplicación `FastAPI`, de modo que se apliquen a cada *path operation*. diff --git a/docs/es/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/es/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 000000000..94290443a --- /dev/null +++ b/docs/es/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,275 @@ +# Dependencias con yield + +FastAPI admite dependencias que realizan algunos pasos adicionales después de finalizar. + +Para hacer esto, usa `yield` en lugar de `return` y escribe los pasos adicionales (código) después. + +/// tip | Consejo + +Asegúrate de usar `yield` una sola vez por dependencia. + +/// + +/// note | Nota técnica + +Cualquier función que sea válida para usar con: + +* `@contextlib.contextmanager` o +* `@contextlib.asynccontextmanager` + +sería válida para usar como una dependencia en **FastAPI**. + +De hecho, FastAPI usa esos dos decoradores internamente. + +/// + +## Una dependencia de base de datos con `yield` + +Por ejemplo, podrías usar esto para crear una sesión de base de datos y cerrarla después de finalizar. + +Solo el código anterior e incluyendo la declaración `yield` se ejecuta antes de crear un response: + +{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *} + +El valor generado es lo que se inyecta en *path operations* y otras dependencias: + +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} + +El código posterior a la declaración `yield` se ejecuta después de crear el response pero antes de enviarla: + +{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *} + +/// tip | Consejo + +Puedes usar funciones `async` o regulares. + +**FastAPI** hará lo correcto con cada una, igual que con dependencias normales. + +/// + +## Una dependencia con `yield` y `try` + +Si usas un bloque `try` en una dependencia con `yield`, recibirás cualquier excepción que se haya lanzado al usar la dependencia. + +Por ejemplo, si algún código en algún punto intermedio, en otra dependencia o en una *path operation*, realiza un "rollback" en una transacción de base de datos o crea cualquier otro error, recibirás la excepción en tu dependencia. + +Por lo tanto, puedes buscar esa excepción específica dentro de la dependencia con `except SomeException`. + +Del mismo modo, puedes usar `finally` para asegurarte de que los pasos de salida se ejecuten, sin importar si hubo una excepción o no. + +{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *} + +## Sub-dependencias con `yield` + +Puedes tener sub-dependencias y "árboles" de sub-dependencias de cualquier tamaño y forma, y cualquiera o todas ellas pueden usar `yield`. + +**FastAPI** se asegurará de que el "código de salida" en cada dependencia con `yield` se ejecute en el orden correcto. + +Por ejemplo, `dependency_c` puede tener una dependencia de `dependency_b`, y `dependency_b` de `dependency_a`: + +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *} + +Y todas ellas pueden usar `yield`. + +En este caso, `dependency_c`, para ejecutar su código de salida, necesita que el valor de `dependency_b` (aquí llamado `dep_b`) todavía esté disponible. + +Y, a su vez, `dependency_b` necesita que el valor de `dependency_a` (aquí llamado `dep_a`) esté disponible para su código de salida. + +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *} + +De la misma manera, podrías tener algunas dependencias con `yield` y otras dependencias con `return`, y hacer que algunas de esas dependan de algunas de las otras. + +Y podrías tener una sola dependencia que requiera varias otras dependencias con `yield`, etc. + +Puedes tener cualquier combinación de dependencias que quieras. + +**FastAPI** se asegurará de que todo se ejecute en el orden correcto. + +/// note | Nota técnica + +Esto funciona gracias a los Context Managers de Python. + +**FastAPI** los utiliza internamente para lograr esto. + +/// + +## Dependencias con `yield` y `HTTPException` + +Viste que puedes usar dependencias con `yield` y tener bloques `try` que capturen excepciones. + +De la misma manera, podrías lanzar una `HTTPException` o similar en el código de salida, después del `yield`. + +/// tip | Consejo + +Esta es una técnica algo avanzada, y en la mayoría de los casos realmente no lo necesitarás, ya que puedes lanzar excepciones (incluyendo `HTTPException`) desde dentro del resto del código de tu aplicación, por ejemplo, en la *path operation function*. + +Pero está ahí para ti si la necesitas. 🤓 + +/// + +{* ../../docs_src/dependencies/tutorial008b_an_py39.py hl[18:22,31] *} + +Una alternativa que podrías usar para capturar excepciones (y posiblemente también lanzar otra `HTTPException`) es crear un [Manejador de Excepciones Personalizado](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + +## Dependencias con `yield` y `except` + +Si capturas una excepción usando `except` en una dependencia con `yield` y no la lanzas nuevamente (o lanzas una nueva excepción), FastAPI no podrá notar que hubo una excepción, al igual que sucedería con Python normal: + +{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *} + +En este caso, el cliente verá un response *HTTP 500 Internal Server Error* como debería, dado que no estamos lanzando una `HTTPException` o similar, pero el servidor **no tendrá ningún registro** ni ninguna otra indicación de cuál fue el error. 😱 + +### Siempre `raise` en Dependencias con `yield` y `except` + +Si capturas una excepción en una dependencia con `yield`, a menos que estés lanzando otra `HTTPException` o similar, deberías volver a lanzar la excepción original. + +Puedes volver a lanzar la misma excepción usando `raise`: + +{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *} + +Ahora el cliente obtendrá el mismo response *HTTP 500 Internal Server Error*, pero el servidor tendrá nuestro `InternalError` personalizado en los registros. 😎 + +## Ejecución de dependencias con `yield` + +La secuencia de ejecución es más o menos como este diagrama. El tiempo fluye de arriba a abajo. Y cada columna es una de las partes que interactúa o ejecuta código. + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exception handler +participant dep as Dep with yield +participant operation as Path Operation +participant tasks as Background tasks + + Note over client,operation: Puede lanzar excepciones, incluyendo HTTPException + client ->> dep: Iniciar request + Note over dep: Ejecutar código hasta yield + opt raise Exception + dep -->> handler: Lanzar Exception + handler -->> client: Response HTTP de error + end + dep ->> operation: Ejecutar dependencia, por ejemplo, sesión de BD + opt raise + operation -->> dep: Lanzar Exception (por ejemplo, HTTPException) + opt handle + dep -->> dep: Puede capturar excepción, lanzar una nueva HTTPException, lanzar otra excepción + end + handler -->> client: Response HTTP de error + end + + operation ->> client: Devolver response al cliente + Note over client,operation: El response ya fue enviado, no se puede cambiar + opt Tasks + operation -->> tasks: Enviar tareas en background + end + opt Lanzar otra excepción + tasks -->> tasks: Manejar excepciones en el código de la tarea en background + end +``` + +/// info | Información + +Solo **un response** será enviado al cliente. Podría ser uno de los responses de error o será el response de la *path operation*. + +Después de que se envíe uno de esos responses, no se podrá enviar ningún otro response. + +/// + +/// tip | Consejo + +Este diagrama muestra `HTTPException`, pero también podrías lanzar cualquier otra excepción que captures en una dependencia con `yield` o con un [Manejador de Excepciones Personalizado](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + +Si lanzas alguna excepción, será pasada a las dependencias con yield, incluyendo `HTTPException`. En la mayoría de los casos querrás volver a lanzar esa misma excepción o una nueva desde la dependencia con `yield` para asegurarte de que se maneje correctamente. + +/// + +## Dependencias con `yield`, `HTTPException`, `except` y Tareas en Background + +/// warning | Advertencia + +Probablemente no necesites estos detalles técnicos, puedes omitir esta sección y continuar abajo. + +Estos detalles son útiles principalmente si estabas usando una versión de FastAPI anterior a 0.106.0 y usabas recursos de dependencias con `yield` en tareas en background. + +/// + +### Dependencias con `yield` y `except`, Detalles Técnicos + +Antes de FastAPI 0.110.0, si usabas una dependencia con `yield`, y luego capturabas una excepción con `except` en esa dependencia, y no volvías a lanzar la excepción, la excepción se lanzaría automáticamente/transmitiría a cualquier manejador de excepciones o al manejador de errores interno del servidor. + +Esto se cambió en la versión 0.110.0 para corregir el consumo no gestionado de memoria de excepciones transmitidas sin un manejador (errores internos del servidor), y para que sea consistente con el comportamiento del código regular de Python. + +### Tareas en Background y Dependencias con `yield`, Detalles Técnicos + +Antes de FastAPI 0.106.0, lanzar excepciones después de `yield` no era posible, el código de salida en dependencias con `yield` se ejecutaba *después* de que el response se enviara, por lo que los [Manejadores de Excepciones](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} ya se habrían ejecutado. + +Esto se diseñó de esta manera principalmente para permitir usar los mismos objetos "extraídos" por dependencias dentro de tareas en background, porque el código de salida se ejecutaría después de que las tareas en background terminaran. + +Sin embargo, ya que esto significaría esperar a que el response viaje a través de la red mientras se retiene innecesariamente un recurso en una dependencia con yield (por ejemplo, una conexión a base de datos), esto se cambió en FastAPI 0.106.0. + +/// tip | Consejo + +Además, una tarea en background es normalmente un conjunto independiente de lógica que debería manejarse por separado, con sus propios recursos (por ejemplo, su propia conexión a base de datos). + +De esta manera probablemente tendrás un código más limpio. + +/// + +Si solías depender de este comportamiento, ahora deberías crear los recursos para tareas en background dentro de la propia tarea en background, y usar internamente solo datos que no dependan de los recursos de las dependencias con `yield`. + +Por ejemplo, en lugar de usar la misma sesión de base de datos, crearías una nueva sesión de base de datos dentro de la tarea en background, y obtendrías los objetos de la base de datos usando esta nueva sesión. Y luego, en lugar de pasar el objeto de la base de datos como parámetro a la función de tarea en background, pasarías el ID de ese objeto y luego obtendrías el objeto nuevamente dentro de la función de tarea en background. + +## Context Managers + +### Qué son los "Context Managers" + +Los "Context Managers" son aquellos objetos de Python que puedes usar en una declaración `with`. + +Por ejemplo, puedes usar `with` para leer un archivo: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +Internamente, `open("./somefile.txt")` crea un objeto llamado "Context Manager". + +Cuando el bloque `with` termina, se asegura de cerrar el archivo, incluso si hubo excepciones. + +Cuando creas una dependencia con `yield`, **FastAPI** creará internamente un context manager para ella y lo combinará con algunas otras herramientas relacionadas. + +### Usando context managers en dependencias con `yield` + +/// warning | Advertencia + +Esto es, más o menos, una idea "avanzada". + +Si apenas estás comenzando con **FastAPI**, podrías querer omitirlo por ahora. + +/// + +En Python, puedes crear Context Managers creando una clase con dos métodos: `__enter__()` y `__exit__()`. + +También puedes usarlos dentro de las dependencias de **FastAPI** con `yield` usando +`with` o `async with` en la función de dependencia: + +{* ../../docs_src/dependencies/tutorial010.py hl[1:9,13] *} + +/// tip | Consejo + +Otra manera de crear un context manager es con: + +* `@contextlib.contextmanager` o +* `@contextlib.asynccontextmanager` + +usándolos para decorar una función con un solo `yield`. + +Eso es lo que **FastAPI** usa internamente para dependencias con `yield`. + +Pero no tienes que usar los decoradores para las dependencias de FastAPI (y no deberías). + +FastAPI lo hará por ti internamente. + +/// diff --git a/docs/es/docs/tutorial/dependencies/global-dependencies.md b/docs/es/docs/tutorial/dependencies/global-dependencies.md new file mode 100644 index 000000000..08dd3d5c5 --- /dev/null +++ b/docs/es/docs/tutorial/dependencies/global-dependencies.md @@ -0,0 +1,15 @@ +# Dependencias Globales + +Para algunos tipos de aplicaciones, podrías querer agregar dependencias a toda la aplicación. + +Similar a como puedes [agregar `dependencies` a los *path operation decorators*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, puedes agregarlos a la aplicación de `FastAPI`. + +En ese caso, se aplicarán a todas las *path operations* en la aplicación: + +{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[16] *} + +Y todas las ideas en la sección sobre [agregar `dependencies` a los *path operation decorators*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} siguen aplicándose, pero en este caso, a todas las *path operations* en la app. + +## Dependencias para grupos de *path operations* + +Más adelante, al leer sobre cómo estructurar aplicaciones más grandes ([Aplicaciones Más Grandes - Múltiples Archivos](../../tutorial/bigger-applications.md){.internal-link target=_blank}), posiblemente con múltiples archivos, aprenderás cómo declarar un solo parámetro de `dependencies` para un grupo de *path operations*. diff --git a/docs/es/docs/tutorial/dependencies/index.md b/docs/es/docs/tutorial/dependencies/index.md new file mode 100644 index 000000000..2fb060177 --- /dev/null +++ b/docs/es/docs/tutorial/dependencies/index.md @@ -0,0 +1,250 @@ +# Dependencias + +**FastAPI** tiene un sistema de **Inyección de Dependencias** muy poderoso pero intuitivo. + +Está diseñado para ser muy simple de usar, y para hacer que cualquier desarrollador integre otros componentes con **FastAPI** de forma muy sencilla. + +## Qué es la "Inyección de Dependencias" + +**"Inyección de Dependencias"** significa, en programación, que hay una manera para que tu código (en este caso, tus *path operation functions*) declare las cosas que necesita para funcionar y utilizar: "dependencias". + +Y luego, ese sistema (en este caso **FastAPI**) se encargará de hacer lo que sea necesario para proporcionar a tu código esas dependencias necesarias ("inyectar" las dependencias). + +Esto es muy útil cuando necesitas: + +* Tener lógica compartida (la misma lógica de código una y otra vez). +* Compartir conexiones a bases de datos. +* Imponer seguridad, autenticación, requisitos de roles, etc. +* Y muchas otras cosas... + +Todo esto, mientras minimizas la repetición de código. + +## Primeros Pasos + +Veamos un ejemplo muy simple. Será tan simple que no es muy útil, por ahora. + +Pero de esta manera podemos enfocarnos en cómo funciona el sistema de **Inyección de Dependencias**. + +### Crear una dependencia, o "dependable" + +Primero enfoquémonos en la dependencia. + +Es solo una función que puede tomar todos los mismos parámetros que una *path operation function* puede tomar: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *} + +Eso es todo. + +**2 líneas**. + +Y tiene la misma forma y estructura que todas tus *path operation functions*. + +Puedes pensar en ella como una *path operation function* sin el "decorador" (sin el `@app.get("/some-path")`). + +Y puede devolver lo que quieras. + +En este caso, esta dependencia espera: + +* Un parámetro de query opcional `q` que es un `str`. +* Un parámetro de query opcional `skip` que es un `int`, y por defecto es `0`. +* Un parámetro de query opcional `limit` que es un `int`, y por defecto es `100`. + +Y luego solo devuelve un `dict` que contiene esos valores. + +/// info | Información + +FastAPI agregó soporte para `Annotated` (y comenzó a recomendarlo) en la versión 0.95.0. + +Si tienes una versión anterior, obtendrás errores al intentar usar `Annotated`. + +Asegúrate de [Actualizar la versión de FastAPI](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} al menos a la 0.95.1 antes de usar `Annotated`. + +/// + +### Importar `Depends` + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} + +### Declarar la dependencia, en el "dependant" + +De la misma forma en que usas `Body`, `Query`, etc. con los parámetros de tu *path operation function*, usa `Depends` con un nuevo parámetro: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} + +Aunque usas `Depends` en los parámetros de tu función de la misma manera que usas `Body`, `Query`, etc., `Depends` funciona un poco diferente. + +Le das a `Depends` un solo parámetro. + +Este parámetro debe ser algo como una función. + +**No la llames** directamente (no agregues los paréntesis al final), solo pásala como un parámetro a `Depends()`. + +Y esa función toma parámetros de la misma manera que las *path operation functions*. + +/// tip | Consejo + +Verás qué otras "cosas", además de funciones, pueden usarse como dependencias en el próximo capítulo. + +/// + +Cada vez que llega un nuevo request, **FastAPI** se encargará de: + +* Llamar a tu función de dependencia ("dependable") con los parámetros correctos. +* Obtener el resultado de tu función. +* Asignar ese resultado al parámetro en tu *path operation function*. + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +De esta manera escribes código compartido una vez y **FastAPI** se encarga de llamarlo para tus *path operations*. + +/// check | Revisa + +Nota que no tienes que crear una clase especial y pasarla en algún lugar a **FastAPI** para "registrarla" o algo similar. + +Solo la pasas a `Depends` y **FastAPI** sabe cómo hacer el resto. + +/// + +## Compartir dependencias `Annotated` + +En los ejemplos anteriores, ves que hay un poquito de **duplicación de código**. + +Cuando necesitas usar la dependencia `common_parameters()`, tienes que escribir todo el parámetro con la anotación de tipo y `Depends()`: + +```Python +commons: Annotated[dict, Depends(common_parameters)] +``` + +Pero como estamos usando `Annotated`, podemos almacenar ese valor `Annotated` en una variable y usarlo en múltiples lugares: + +{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *} + +/// tip | Consejo + +Esto es solo Python estándar, se llama un "alias de tipo", en realidad no es específico de **FastAPI**. + +Pero porque **FastAPI** está basado en los estándares de Python, incluido `Annotated`, puedes usar este truco en tu código. 😎 + +/// + +Las dependencias seguirán funcionando como se esperaba, y la **mejor parte** es que la **información de tipo se preservará**, lo que significa que tu editor podrá seguir proporcionándote **autocompletado**, **errores en línea**, etc. Lo mismo para otras herramientas como `mypy`. + +Esto será especialmente útil cuando lo uses en una **gran base de código** donde uses **las mismas dependencias** una y otra vez en **muchas *path operations***. + +## Usar `async` o no usar `async` + +Como las dependencias también serán llamadas por **FastAPI** (lo mismo que tus *path operation functions*), las mismas reglas aplican al definir tus funciones. + +Puedes usar `async def` o `def` normal. + +Y puedes declarar dependencias con `async def` dentro de *path operation functions* normales `def`, o dependencias `def` dentro de *path operation functions* `async def`, etc. + +No importa. **FastAPI** sabrá qué hacer. + +/// note | Nota + +Si no lo sabes, revisa la sección [Async: *"¿Con prisa?"*](../../async.md#in-a-hurry){.internal-link target=_blank} sobre `async` y `await` en la documentación. + +/// + +## Integración con OpenAPI + +Todas las declaraciones de request, validaciones y requisitos de tus dependencias (y sub-dependencias) se integrarán en el mismo esquema de OpenAPI. + +Así, la documentación interactiva tendrá toda la información de estas dependencias también: + + + +## Uso simple + +Si lo ves, las *path operation functions* se declaran para ser usadas siempre que un *path* y una *operación* coincidan, y luego **FastAPI** se encarga de llamar la función con los parámetros correctos, extrayendo los datos del request. + +En realidad, todos (o la mayoría) de los frameworks web funcionan de esta misma manera. + +Nunca llamas directamente a esas funciones. Son llamadas por tu framework (en este caso, **FastAPI**). + +Con el sistema de Inyección de Dependencias, también puedes decirle a **FastAPI** que tu *path operation function* también "depende" de algo más que debe ejecutarse antes que tu *path operation function*, y **FastAPI** se encargará de ejecutarlo e "inyectar" los resultados. + +Otros términos comunes para esta misma idea de "inyección de dependencias" son: + +* recursos +* proveedores +* servicios +* inyectables +* componentes + +## Plug-ins de **FastAPI** + +Las integraciones y "plug-ins" pueden construirse usando el sistema de **Inyección de Dependencias**. Pero, de hecho, en realidad **no hay necesidad de crear "plug-ins"**, ya que al usar dependencias es posible declarar una cantidad infinita de integraciones e interacciones que se vuelven disponibles para tus *path operation functions*. + +Y las dependencias se pueden crear de una manera muy simple e intuitiva que te permite simplemente importar los paquetes de Python que necesitas, e integrarlos con tus funciones de API en un par de líneas de código, *literalmente*. + +Verás ejemplos de esto en los próximos capítulos, sobre bases de datos relacionales y NoSQL, seguridad, etc. + +## Compatibilidad de **FastAPI** + +La simplicidad del sistema de inyección de dependencias hace que **FastAPI** sea compatible con: + +* todas las bases de datos relacionales +* bases de datos NoSQL +* paquetes externos +* APIs externas +* sistemas de autenticación y autorización +* sistemas de monitoreo de uso de la API +* sistemas de inyección de datos de response +* etc. + +## Simple y Poderoso + +Aunque el sistema de inyección de dependencias jerárquico es muy simple de definir y usar, sigue siendo muy poderoso. + +Puedes definir dependencias que a su vez pueden definir dependencias ellas mismas. + +Al final, se construye un árbol jerárquico de dependencias, y el sistema de **Inyección de Dependencias** se encarga de resolver todas estas dependencias por ti (y sus sub-dependencias) y proporcionar (inyectar) los resultados en cada paso. + +Por ejemplo, digamos que tienes 4 endpoints de API (*path operations*): + +* `/items/public/` +* `/items/private/` +* `/users/{user_id}/activate` +* `/items/pro/` + +entonces podrías agregar diferentes requisitos de permiso para cada uno de ellos solo con dependencias y sub-dependencias: + +```mermaid +graph TB + +current_user(["current_user"]) +active_user(["active_user"]) +admin_user(["admin_user"]) +paying_user(["paying_user"]) + +public["/items/public/"] +private["/items/private/"] +activate_user["/users/{user_id}/activate"] +pro_items["/items/pro/"] + +current_user --> active_user +active_user --> admin_user +active_user --> paying_user + +current_user --> public +active_user --> private +admin_user --> activate_user +paying_user --> pro_items +``` + +## Integrado con **OpenAPI** + +Todas estas dependencias, al declarar sus requisitos, también añaden parámetros, validaciones, etc. a tus *path operations*. + +**FastAPI** se encargará de agregar todo al esquema de OpenAPI, para que se muestre en los sistemas de documentación interactiva. diff --git a/docs/es/docs/tutorial/dependencies/sub-dependencies.md b/docs/es/docs/tutorial/dependencies/sub-dependencies.md new file mode 100644 index 000000000..bba532207 --- /dev/null +++ b/docs/es/docs/tutorial/dependencies/sub-dependencies.md @@ -0,0 +1,105 @@ +# Sub-dependencias + +Puedes crear dependencias que tengan **sub-dependencias**. + +Pueden ser tan **profundas** como necesites. + +**FastAPI** se encargará de resolverlas. + +## Primera dependencia "dependable" + +Podrías crear una primera dependencia ("dependable") así: + +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *} + +Declara un parámetro de query opcional `q` como un `str`, y luego simplemente lo devuelve. + +Esto es bastante simple (no muy útil), pero nos ayudará a centrarnos en cómo funcionan las sub-dependencias. + +## Segunda dependencia, "dependable" y "dependant" + +Luego puedes crear otra función de dependencia (un "dependable") que al mismo tiempo declare una dependencia propia (por lo que también es un "dependant"): + +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *} + +Centrémonos en los parámetros declarados: + +* Aunque esta función es una dependencia ("dependable") en sí misma, también declara otra dependencia (depende de algo más). + * Depende del `query_extractor`, y asigna el valor que devuelve al parámetro `q`. +* También declara una `last_query` cookie opcional, como un `str`. + * Si el usuario no proporcionó ningún query `q`, usamos el último query utilizado, que guardamos previamente en una cookie. + +## Usa la dependencia + +Entonces podemos usar la dependencia con: + +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *} + +/// info | Información + +Fíjate que solo estamos declarando una dependencia en la *path operation function*, `query_or_cookie_extractor`. + +Pero **FastAPI** sabrá que tiene que resolver `query_extractor` primero, para pasar los resultados de eso a `query_or_cookie_extractor` al llamarlo. + +/// + +```mermaid +graph TB + +query_extractor(["query_extractor"]) +query_or_cookie_extractor(["query_or_cookie_extractor"]) + +read_query["/items/"] + +query_extractor --> query_or_cookie_extractor --> read_query +``` + +## Usando la misma dependencia múltiples veces + +Si una de tus dependencias se declara varias veces para la misma *path operation*, por ejemplo, múltiples dependencias tienen una sub-dependencia común, **FastAPI** sabrá llamar a esa sub-dependencia solo una vez por request. + +Y guardará el valor devuelto en un "cache" y lo pasará a todos los "dependants" que lo necesiten en ese request específico, en lugar de llamar a la dependencia varias veces para el mismo request. + +En un escenario avanzado donde sabes que necesitas que la dependencia se llame en cada paso (posiblemente varias veces) en el mismo request en lugar de usar el valor "cache", puedes establecer el parámetro `use_cache=False` al usar `Depends`: + +//// tab | Python 3.8+ + +```Python hl_lines="1" +async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): + return {"fresh_value": fresh_value} +``` + +//// + +//// tab | Python 3.8+ sin Anotaciones + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +```Python hl_lines="1" +async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} +``` + +//// + +## Resumen + +Aparte de todas las palabras rimbombantes usadas aquí, el sistema de **Inyección de Dependencias** es bastante simple. + +Solo son funciones que se ven igual que las *path operation functions*. + +Pero aun así, es muy potente y te permite declarar "grafos" de dependencia anidados arbitrariamente profundos (árboles). + +/// tip | Consejo + +Todo esto podría no parecer tan útil con estos ejemplos simples. + +Pero verás lo útil que es en los capítulos sobre **seguridad**. + +Y también verás la cantidad de código que te ahorrará. + +/// diff --git a/docs/es/docs/tutorial/encoder.md b/docs/es/docs/tutorial/encoder.md new file mode 100644 index 000000000..9b8919d4b --- /dev/null +++ b/docs/es/docs/tutorial/encoder.md @@ -0,0 +1,35 @@ +# JSON Compatible Encoder + +Hay algunos casos en los que podrías necesitar convertir un tipo de dato (como un modelo de Pydantic) a algo compatible con JSON (como un `dict`, `list`, etc). + +Por ejemplo, si necesitas almacenarlo en una base de datos. + +Para eso, **FastAPI** proporciona una función `jsonable_encoder()`. + +## Usando el `jsonable_encoder` + +Imaginemos que tienes una base de datos `fake_db` que solo recibe datos compatibles con JSON. + +Por ejemplo, no recibe objetos `datetime`, ya que no son compatibles con JSON. + +Entonces, un objeto `datetime` tendría que ser convertido a un `str` que contenga los datos en formato ISO. + +De la misma manera, esta base de datos no recibiría un modelo de Pydantic (un objeto con atributos), solo un `dict`. + +Puedes usar `jsonable_encoder` para eso. + +Recibe un objeto, como un modelo de Pydantic, y devuelve una versión compatible con JSON: + +{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *} + +En este ejemplo, convertiría el modelo de Pydantic a un `dict`, y el `datetime` a un `str`. + +El resultado de llamarlo es algo que puede ser codificado con la función estándar de Python `json.dumps()`. + +No devuelve un gran `str` que contenga los datos en formato JSON (como una cadena de texto). Devuelve una estructura de datos estándar de Python (por ejemplo, un `dict`) con valores y sub-valores que son todos compatibles con JSON. + +/// note | Nota + +`jsonable_encoder` es utilizado internamente por **FastAPI** para convertir datos. Pero es útil en muchos otros escenarios. + +/// diff --git a/docs/es/docs/tutorial/extra-data-types.md b/docs/es/docs/tutorial/extra-data-types.md new file mode 100644 index 000000000..28775780f --- /dev/null +++ b/docs/es/docs/tutorial/extra-data-types.md @@ -0,0 +1,62 @@ +# Tipos de Datos Extra + +Hasta ahora, has estado usando tipos de datos comunes, como: + +* `int` +* `float` +* `str` +* `bool` + +Pero también puedes usar tipos de datos más complejos. + +Y seguirás teniendo las mismas funcionalidades como hasta ahora: + +* Gran soporte de editor. +* Conversión de datos de requests entrantes. +* Conversión de datos para datos de response. +* Validación de datos. +* Anotación y documentación automática. + +## Otros tipos de datos + +Aquí hay algunos de los tipos de datos adicionales que puedes usar: + +* `UUID`: + * Un "Identificador Universalmente Único" estándar, común como un ID en muchas bases de datos y sistemas. + * En requests y responses se representará como un `str`. +* `datetime.datetime`: + * Un `datetime.datetime` de Python. + * En requests y responses se representará como un `str` en formato ISO 8601, como: `2008-09-15T15:53:00+05:00`. +* `datetime.date`: + * `datetime.date` de Python. + * En requests y responses se representará como un `str` en formato ISO 8601, como: `2008-09-15`. +* `datetime.time`: + * Un `datetime.time` de Python. + * En requests y responses se representará como un `str` en formato ISO 8601, como: `14:23:55.003`. +* `datetime.timedelta`: + * Un `datetime.timedelta` de Python. + * En requests y responses se representará como un `float` de segundos totales. + * Pydantic también permite representarlo como una "codificación de diferencia horaria ISO 8601", consulta la documentación para más información. +* `frozenset`: + * En requests y responses, tratado igual que un `set`: + * En requests, se leerá una list, eliminando duplicados y convirtiéndola en un `set`. + * En responses, el `set` se convertirá en una `list`. + * El esquema generado especificará que los valores del `set` son únicos (usando `uniqueItems` de JSON Schema). +* `bytes`: + * `bytes` estándar de Python. + * En requests y responses se tratará como `str`. + * El esquema generado especificará que es un `str` con "binary" como "format". +* `Decimal`: + * `Decimal` estándar de Python. + * En requests y responses, manejado igual que un `float`. +* Puedes revisar todos los tipos de datos válidos de Pydantic aquí: Tipos de datos de Pydantic. + +## Ejemplo + +Aquí tienes un ejemplo de una *path operation* con parámetros usando algunos de los tipos anteriores. + +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} + +Nota que los parámetros dentro de la función tienen su tipo de dato natural, y puedes, por ejemplo, realizar manipulaciones de fechas normales, como: + +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/es/docs/tutorial/extra-models.md b/docs/es/docs/tutorial/extra-models.md new file mode 100644 index 000000000..0380b9690 --- /dev/null +++ b/docs/es/docs/tutorial/extra-models.md @@ -0,0 +1,222 @@ +# Modelos Extra + +Continuando con el ejemplo anterior, será común tener más de un modelo relacionado. + +Esto es especialmente el caso para los modelos de usuario, porque: + +* El **modelo de entrada** necesita poder tener una contraseña. +* El **modelo de salida** no debería tener una contraseña. +* El **modelo de base de datos** probablemente necesitaría tener una contraseña hasheada. + +/// danger | Peligro + +Nunca almacenes contraseñas de usuarios en texto plano. Siempre almacena un "hash seguro" que puedas verificar luego. + +Si no lo sabes, aprenderás qué es un "hash de contraseña" en los [capítulos de seguridad](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. + +/// + +## Múltiples modelos + +Aquí tienes una idea general de cómo podrían ser los modelos con sus campos de contraseña y los lugares donde se utilizan: + +{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *} + +/// info | Información + +En Pydantic v1 el método se llamaba `.dict()`, fue deprecado (pero aún soportado) en Pydantic v2, y renombrado a `.model_dump()`. + +Los ejemplos aquí usan `.dict()` para compatibilidad con Pydantic v1, pero deberías usar `.model_dump()` en su lugar si puedes usar Pydantic v2. + +/// + +### Acerca de `**user_in.dict()` + +#### `.dict()` de Pydantic + +`user_in` es un modelo Pydantic de la clase `UserIn`. + +Los modelos Pydantic tienen un método `.dict()` que devuelve un `dict` con los datos del modelo. + +Así que, si creamos un objeto Pydantic `user_in` como: + +```Python +user_in = UserIn(username="john", password="secret", email="john.doe@example.com") +``` + +y luego llamamos a: + +```Python +user_dict = user_in.dict() +``` + +ahora tenemos un `dict` con los datos en la variable `user_dict` (es un `dict` en lugar de un objeto modelo Pydantic). + +Y si llamamos a: + +```Python +print(user_dict) +``` + +obtendremos un `dict` de Python con: + +```Python +{ + 'username': 'john', + 'password': 'secret', + 'email': 'john.doe@example.com', + 'full_name': None, +} +``` + +#### Desempaquetando un `dict` + +Si tomamos un `dict` como `user_dict` y lo pasamos a una función (o clase) con `**user_dict`, Python lo "desempaquetará". Pasará las claves y valores del `user_dict` directamente como argumentos clave-valor. + +Así que, continuando con el `user_dict` anterior, escribir: + +```Python +UserInDB(**user_dict) +``` + +sería equivalente a algo como: + +```Python +UserInDB( + username="john", + password="secret", + email="john.doe@example.com", + full_name=None, +) +``` + +O más exactamente, usando `user_dict` directamente, con cualquier contenido que pueda tener en el futuro: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], +) +``` + +#### Un modelo Pydantic a partir del contenido de otro + +Como en el ejemplo anterior obtuvimos `user_dict` de `user_in.dict()`, este código: + +```Python +user_dict = user_in.dict() +UserInDB(**user_dict) +``` + +sería equivalente a: + +```Python +UserInDB(**user_in.dict()) +``` + +...porque `user_in.dict()` es un `dict`, y luego hacemos que Python lo "desempaquete" al pasarlo a `UserInDB` con el prefijo `**`. + +Así, obtenemos un modelo Pydantic a partir de los datos en otro modelo Pydantic. + +#### Desempaquetando un `dict` y palabras clave adicionales + +Y luego agregando el argumento de palabra clave adicional `hashed_password=hashed_password`, como en: + +```Python +UserInDB(**user_in.dict(), hashed_password=hashed_password) +``` + +...termina siendo como: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], + hashed_password = hashed_password, +) +``` + +/// warning | Advertencia + +Las funciones adicionales de soporte `fake_password_hasher` y `fake_save_user` son solo para demostrar un posible flujo de datos, pero por supuesto no proporcionan ninguna seguridad real. + +/// + +## Reducir duplicación + +Reducir la duplicación de código es una de las ideas centrales en **FastAPI**. + +Ya que la duplicación de código incrementa las posibilidades de bugs, problemas de seguridad, problemas de desincronización de código (cuando actualizas en un lugar pero no en los otros), etc. + +Y estos modelos están compartiendo muchos de los datos y duplicando nombres y tipos de atributos. + +Podríamos hacerlo mejor. + +Podemos declarar un modelo `UserBase` que sirva como base para nuestros otros modelos. Y luego podemos hacer subclases de ese modelo que heredan sus atributos (declaraciones de tipo, validación, etc). + +Toda la conversión de datos, validación, documentación, etc. seguirá funcionando normalmente. + +De esa manera, podemos declarar solo las diferencias entre los modelos (con `password` en texto plano, con `hashed_password` y sin contraseña): + +{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *} + +## `Union` o `anyOf` + +Puedes declarar un response que sea la `Union` de dos o más tipos, eso significa que el response sería cualquiera de ellos. + +Se definirá en OpenAPI con `anyOf`. + +Para hacerlo, usa el type hint estándar de Python `typing.Union`: + +/// note | Nota + +Al definir una `Union`, incluye el tipo más específico primero, seguido por el tipo menos específico. En el ejemplo a continuación, el más específico `PlaneItem` viene antes de `CarItem` en `Union[PlaneItem, CarItem]`. + +/// + +{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *} + + +### `Union` en Python 3.10 + +En este ejemplo pasamos `Union[PlaneItem, CarItem]` como el valor del argumento `response_model`. + +Porque lo estamos pasando como un **valor a un argumento** en lugar de ponerlo en una **anotación de tipo**, tenemos que usar `Union` incluso en Python 3.10. + +Si estuviera en una anotación de tipo podríamos haber usado la barra vertical, como: + +```Python +some_variable: PlaneItem | CarItem +``` + +Pero si ponemos eso en la asignación `response_model=PlaneItem | CarItem` obtendríamos un error, porque Python intentaría realizar una **operación inválida** entre `PlaneItem` y `CarItem` en lugar de interpretar eso como una anotación de tipo. + +## Lista de modelos + +De la misma manera, puedes declarar responses de listas de objetos. + +Para eso, usa el `typing.List` estándar de Python (o simplemente `list` en Python 3.9 y posteriores): + +{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *} + + +## Response con `dict` arbitrario + +También puedes declarar un response usando un `dict` arbitrario plano, declarando solo el tipo de las claves y valores, sin usar un modelo Pydantic. + +Esto es útil si no conoces los nombres de los campos/atributos válidos (que serían necesarios para un modelo Pydantic) de antemano. + +En este caso, puedes usar `typing.Dict` (o solo `dict` en Python 3.9 y posteriores): + +{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *} + + +## Recapitulación + +Usa múltiples modelos Pydantic y hereda libremente para cada caso. + +No necesitas tener un solo modelo de datos por entidad si esa entidad debe poder tener diferentes "estados". Como el caso con la "entidad" usuario con un estado que incluye `password`, `password_hash` y sin contraseña. diff --git a/docs/es/docs/tutorial/handling-errors.md b/docs/es/docs/tutorial/handling-errors.md new file mode 100644 index 000000000..2e4464989 --- /dev/null +++ b/docs/es/docs/tutorial/handling-errors.md @@ -0,0 +1,255 @@ +# Manejo de Errores + +Existen muchas situaciones en las que necesitas notificar un error a un cliente que está usando tu API. + +Este cliente podría ser un navegador con un frontend, un código de otra persona, un dispositivo IoT, etc. + +Podrías necesitar decirle al cliente que: + +* El cliente no tiene suficientes privilegios para esa operación. +* El cliente no tiene acceso a ese recurso. +* El ítem al que el cliente intentaba acceder no existe. +* etc. + +En estos casos, normalmente devolverías un **código de estado HTTP** en el rango de **400** (de 400 a 499). + +Esto es similar a los códigos de estado HTTP 200 (de 200 a 299). Esos códigos de estado "200" significan que de alguna manera hubo un "éxito" en el request. + +Los códigos de estado en el rango de 400 significan que hubo un error por parte del cliente. + +¿Recuerdas todos esos errores de **"404 Not Found"** (y chistes)? + +## Usa `HTTPException` + +Para devolver responses HTTP con errores al cliente, usa `HTTPException`. + +### Importa `HTTPException` + +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} + +### Lanza un `HTTPException` en tu código + +`HTTPException` es una excepción de Python normal con datos adicionales relevantes para APIs. + +Debido a que es una excepción de Python, no la `return`, sino que la `raise`. + +Esto también significa que si estás dentro de una función de utilidad que estás llamando dentro de tu *path operation function*, y lanzas el `HTTPException` desde dentro de esa función de utilidad, no se ejecutará el resto del código en la *path operation function*, terminará ese request de inmediato y enviará el error HTTP del `HTTPException` al cliente. + +El beneficio de lanzar una excepción en lugar de `return`ar un valor será más evidente en la sección sobre Dependencias y Seguridad. + +En este ejemplo, cuando el cliente solicita un ítem por un ID que no existe, lanza una excepción con un código de estado de `404`: + +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} + +### El response resultante + +Si el cliente solicita `http://example.com/items/foo` (un `item_id` `"foo"`), ese cliente recibirá un código de estado HTTP de 200, y un response JSON de: + +```JSON +{ + "item": "The Foo Wrestlers" +} +``` + +Pero si el cliente solicita `http://example.com/items/bar` (un `item_id` inexistente `"bar"`), ese cliente recibirá un código de estado HTTP de 404 (el error "no encontrado"), y un response JSON de: + +```JSON +{ + "detail": "Item not found" +} +``` + +/// tip | Consejo + +Cuando lanzas un `HTTPException`, puedes pasar cualquier valor que pueda convertirse a JSON como el parámetro `detail`, no solo `str`. + +Podrías pasar un `dict`, un `list`, etc. + +Son manejados automáticamente por **FastAPI** y convertidos a JSON. + +/// + +## Agrega headers personalizados + +Existen algunas situaciones en las que es útil poder agregar headers personalizados al error HTTP. Por ejemplo, para algunos tipos de seguridad. + +Probablemente no necesitarás usarlos directamente en tu código. + +Pero en caso de que los necesites para un escenario avanzado, puedes agregar headers personalizados: + +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} + +## Instalar manejadores de excepciones personalizados + +Puedes agregar manejadores de excepciones personalizados con las mismas utilidades de excepciones de Starlette. + +Supongamos que tienes una excepción personalizada `UnicornException` que tú (o un paquete que usas) podría lanzar. + +Y quieres manejar esta excepción globalmente con FastAPI. + +Podrías agregar un manejador de excepciones personalizado con `@app.exception_handler()`: + +{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *} + +Aquí, si solicitas `/unicorns/yolo`, la *path operation* lanzará un `UnicornException`. + +Pero será manejado por el `unicorn_exception_handler`. + +Así que recibirás un error limpio, con un código de estado HTTP de `418` y un contenido JSON de: + +```JSON +{"message": "Oops! yolo did something. There goes a rainbow..."} +``` + +/// note | Nota Técnica + +También podrías usar `from starlette.requests import Request` y `from starlette.responses import JSONResponse`. + +**FastAPI** ofrece las mismas `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette. Lo mismo con `Request`. + +/// + +## Sobrescribir los manejadores de excepciones predeterminados + +**FastAPI** tiene algunos manejadores de excepciones predeterminados. + +Estos manejadores se encargan de devolver los responses JSON predeterminadas cuando lanzas un `HTTPException` y cuando el request tiene datos inválidos. + +Puedes sobrescribir estos manejadores de excepciones con los tuyos propios. + +### Sobrescribir excepciones de validación de request + +Cuando un request contiene datos inválidos, **FastAPI** lanza internamente un `RequestValidationError`. + +Y también incluye un manejador de excepciones predeterminado para ello. + +Para sobrescribirlo, importa el `RequestValidationError` y úsalo con `@app.exception_handler(RequestValidationError)` para decorar el manejador de excepciones. + +El manejador de excepciones recibirá un `Request` y la excepción. + +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *} + +Ahora, si vas a `/items/foo`, en lugar de obtener el error JSON por defecto con: + +```JSON +{ + "detail": [ + { + "loc": [ + "path", + "item_id" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ] +} +``` + +obtendrás una versión en texto, con: + +``` +1 validation error +path -> item_id + value is not a valid integer (type=type_error.integer) +``` + +#### `RequestValidationError` vs `ValidationError` + +/// warning | Advertencia + +Estos son detalles técnicos que podrías omitir si no es importante para ti en este momento. + +/// + +`RequestValidationError` es una subclase de `ValidationError` de Pydantic. + +**FastAPI** la usa para que, si usas un modelo Pydantic en `response_model`, y tus datos tienen un error, lo verás en tu log. + +Pero el cliente/usuario no lo verá. En su lugar, el cliente recibirá un "Error Interno del Servidor" con un código de estado HTTP `500`. + +Debería ser así porque si tienes un `ValidationError` de Pydantic en tu *response* o en cualquier lugar de tu código (no en el *request* del cliente), en realidad es un bug en tu código. + +Y mientras lo arreglas, tus clientes/usuarios no deberían tener acceso a información interna sobre el error, ya que eso podría exponer una vulnerabilidad de seguridad. + +### Sobrescribir el manejador de errores de `HTTPException` + +De la misma manera, puedes sobrescribir el manejador de `HTTPException`. + +Por ejemplo, podrías querer devolver un response de texto plano en lugar de JSON para estos errores: + +{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *} + +/// note | Nota Técnica + +También podrías usar `from starlette.responses import PlainTextResponse`. + +**FastAPI** ofrece las mismas `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette. + +/// + +### Usar el body de `RequestValidationError` + +El `RequestValidationError` contiene el `body` que recibió con datos inválidos. + +Podrías usarlo mientras desarrollas tu aplicación para registrar el body y depurarlo, devolverlo al usuario, etc. + +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} + +Ahora intenta enviar un ítem inválido como: + +```JSON +{ + "title": "towel", + "size": "XL" +} +``` + +Recibirás un response que te dirá que los datos son inválidos conteniendo el body recibido: + +```JSON hl_lines="12-15" +{ + "detail": [ + { + "loc": [ + "body", + "size" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ], + "body": { + "title": "towel", + "size": "XL" + } +} +``` + +#### `HTTPException` de FastAPI vs `HTTPException` de Starlette + +**FastAPI** tiene su propio `HTTPException`. + +Y la clase de error `HTTPException` de **FastAPI** hereda de la clase de error `HTTPException` de Starlette. + +La única diferencia es que el `HTTPException` de **FastAPI** acepta cualquier dato JSON-able para el campo `detail`, mientras que el `HTTPException` de Starlette solo acepta strings para ello. + +Así que puedes seguir lanzando un `HTTPException` de **FastAPI** como de costumbre en tu código. + +Pero cuando registras un manejador de excepciones, deberías registrarlo para el `HTTPException` de Starlette. + +De esta manera, si alguna parte del código interno de Starlette, o una extensión o complemento de Starlette, lanza un `HTTPException` de Starlette, tu manejador podrá capturarlo y manejarlo. + +En este ejemplo, para poder tener ambos `HTTPException` en el mismo código, las excepciones de Starlette son renombradas a `StarletteHTTPException`: + +```Python +from starlette.exceptions import HTTPException as StarletteHTTPException +``` + +### Reutilizar los manejadores de excepciones de **FastAPI** + +Si quieres usar la excepción junto con los mismos manejadores de excepciones predeterminados de **FastAPI**, puedes importar y reutilizar los manejadores de excepciones predeterminados de `fastapi.exception_handlers`: + +{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *} + +En este ejemplo solo estás `print`eando el error con un mensaje muy expresivo, pero te haces una idea. Puedes usar la excepción y luego simplemente reutilizar los manejadores de excepciones predeterminados. diff --git a/docs/es/docs/tutorial/header-param-models.md b/docs/es/docs/tutorial/header-param-models.md new file mode 100644 index 000000000..3676231e6 --- /dev/null +++ b/docs/es/docs/tutorial/header-param-models.md @@ -0,0 +1,56 @@ +# Modelos de Parámetros de Header + +Si tienes un grupo de **parámetros de header** relacionados, puedes crear un **modelo Pydantic** para declararlos. + +Esto te permitirá **reutilizar el modelo** en **múltiples lugares** y también declarar validaciones y metadatos para todos los parámetros al mismo tiempo. 😎 + +/// note | Nota + +Esto es compatible desde la versión `0.115.0` de FastAPI. 🤓 + +/// + +## Parámetros de Header con un Modelo Pydantic + +Declara los **parámetros de header** que necesitas en un **modelo Pydantic**, y luego declara el parámetro como `Header`: + +{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *} + +**FastAPI** **extraerá** los datos para **cada campo** de los **headers** en el request y te dará el modelo Pydantic que definiste. + +## Revisa la Documentación + +Puedes ver los headers requeridos en la interfaz de documentación en `/docs`: + +
+ +
+ +## Prohibir Headers Extra + +En algunos casos de uso especiales (probablemente no muy comunes), podrías querer **restringir** los headers que deseas recibir. + +Puedes usar la configuración del modelo de Pydantic para `prohibir` cualquier campo `extra`: + +{* ../../docs_src/header_param_models/tutorial002_an_py310.py hl[10] *} + +Si un cliente intenta enviar algunos **headers extra**, recibirán un response de **error**. + +Por ejemplo, si el cliente intenta enviar un header `tool` con un valor de `plumbus`, recibirán un response de **error** indicando que el parámetro de header `tool` no está permitido: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["header", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ] +} +``` + +## Resumen + +Puedes usar **modelos Pydantic** para declarar **headers** en **FastAPI**. 😎 diff --git a/docs/es/docs/tutorial/header-params.md b/docs/es/docs/tutorial/header-params.md new file mode 100644 index 000000000..9c0112bb2 --- /dev/null +++ b/docs/es/docs/tutorial/header-params.md @@ -0,0 +1,91 @@ +# Parámetros de Header + +Puedes definir los parámetros de Header de la misma manera que defines los parámetros de `Query`, `Path` y `Cookie`. + +## Importar `Header` + +Primero importa `Header`: + +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[3] *} + +## Declarar parámetros de `Header` + +Luego declara los parámetros de header usando la misma estructura que con `Path`, `Query` y `Cookie`. + +Puedes definir el valor por defecto así como toda la validación extra o los parámetros de anotaciones: + +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *} + +/// note | Detalles Técnicos + +`Header` es una clase "hermana" de `Path`, `Query` y `Cookie`. También hereda de la misma clase común `Param`. + +Pero recuerda que cuando importas `Query`, `Path`, `Header`, y otros de `fastapi`, en realidad son funciones que retornan clases especiales. + +/// + +/// info | Información + +Para declarar headers, necesitas usar `Header`, porque de otra forma los parámetros serían interpretados como parámetros de query. + +/// + +## Conversión automática + +`Header` tiene un poquito de funcionalidad extra además de lo que proporcionan `Path`, `Query` y `Cookie`. + +La mayoría de los headers estándar están separados por un carácter "guion", también conocido como el "símbolo menos" (`-`). + +Pero una variable como `user-agent` es inválida en Python. + +Así que, por defecto, `Header` convertirá los caracteres de los nombres de los parámetros de guion bajo (`_`) a guion (`-`) para extraer y documentar los headers. + +Además, los headers HTTP no diferencian entre mayúsculas y minúsculas, por lo que los puedes declarar con el estilo estándar de Python (también conocido como "snake_case"). + +Así que, puedes usar `user_agent` como normalmente lo harías en código Python, en lugar de necesitar capitalizar las primeras letras como `User_Agent` o algo similar. + +Si por alguna razón necesitas desactivar la conversión automática de guiones bajos a guiones, establece el parámetro `convert_underscores` de `Header` a `False`: + +{* ../../docs_src/header_params/tutorial002_an_py310.py hl[10] *} + +/// warning | Advertencia + +Antes de establecer `convert_underscores` a `False`, ten en cuenta que algunos proxies y servidores HTTP no permiten el uso de headers con guiones bajos. + +/// + +## Headers duplicados + +Es posible recibir headers duplicados. Eso significa, el mismo header con múltiples valores. + +Puedes definir esos casos usando una lista en la declaración del tipo. + +Recibirás todos los valores del header duplicado como una `list` de Python. + +Por ejemplo, para declarar un header de `X-Token` que puede aparecer más de una vez, puedes escribir: + +{* ../../docs_src/header_params/tutorial003_an_py310.py hl[9] *} + +Si te comunicas con esa *path operation* enviando dos headers HTTP como: + +``` +X-Token: foo +X-Token: bar +``` + +El response sería como: + +```JSON +{ + "X-Token values": [ + "bar", + "foo" + ] +} +``` + +## Recapitulación + +Declara headers con `Header`, usando el mismo patrón común que `Query`, `Path` y `Cookie`. + +Y no te preocupes por los guiones bajos en tus variables, **FastAPI** se encargará de convertirlos. diff --git a/docs/es/docs/tutorial/metadata.md b/docs/es/docs/tutorial/metadata.md new file mode 100644 index 000000000..1561e4ae3 --- /dev/null +++ b/docs/es/docs/tutorial/metadata.md @@ -0,0 +1,120 @@ +# Metadata y URLs de Docs + +Puedes personalizar varias configuraciones de metadata en tu aplicación **FastAPI**. + +## Metadata para la API + +Puedes establecer los siguientes campos que se usan en la especificación OpenAPI y en las interfaces automáticas de documentación de la API: + +| Parámetro | Tipo | Descripción | +|------------|------|-------------| +| `title` | `str` | El título de la API. | +| `summary` | `str` | Un resumen corto de la API. Disponible desde OpenAPI 3.1.0, FastAPI 0.99.0. | +| `description` | `str` | Una breve descripción de la API. Puede usar Markdown. | +| `version` | `string` | La versión de la API. Esta es la versión de tu propia aplicación, no de OpenAPI. Por ejemplo, `2.5.0`. | +| `terms_of_service` | `str` | Una URL a los Términos de Servicio para la API. Si se proporciona, debe ser una URL. | +| `contact` | `dict` | La información de contacto para la API expuesta. Puede contener varios campos.
contact fields
ParámetroTipoDescripción
namestrEl nombre identificativo de la persona/organización de contacto.
urlstrLa URL que apunta a la información de contacto. DEBE tener el formato de una URL.
emailstrLa dirección de correo electrónico de la persona/organización de contacto. DEBE tener el formato de una dirección de correo.
| +| `license_info` | `dict` | La información de la licencia para la API expuesta. Puede contener varios campos.
license_info fields
ParámetroTipoDescripción
namestrREQUERIDO (si se establece un license_info). El nombre de la licencia utilizada para la API.
identifierstrUna expresión de licencia SPDX para la API. El campo identifier es mutuamente excluyente del campo url. Disponible desde OpenAPI 3.1.0, FastAPI 0.99.0.
urlstrUna URL a la licencia utilizada para la API. DEBE tener el formato de una URL.
| + +Puedes configurarlos de la siguiente manera: + +{* ../../docs_src/metadata/tutorial001.py hl[3:16, 19:32] *} + +/// tip | Consejo + +Puedes escribir Markdown en el campo `description` y se mostrará en el resultado. + +/// + +Con esta configuración, la documentación automática de la API se vería así: + + + +## Identificador de licencia + +Desde OpenAPI 3.1.0 y FastAPI 0.99.0, también puedes establecer la `license_info` con un `identifier` en lugar de una `url`. + +Por ejemplo: + +{* ../../docs_src/metadata/tutorial001_1.py hl[31] *} + +## Metadata para etiquetas + +También puedes agregar metadata adicional para las diferentes etiquetas usadas para agrupar tus path operations con el parámetro `openapi_tags`. + +Este toma una list que contiene un diccionario para cada etiqueta. + +Cada diccionario puede contener: + +* `name` (**requerido**): un `str` con el mismo nombre de etiqueta que usas en el parámetro `tags` en tus *path operations* y `APIRouter`s. +* `description`: un `str` con una breve descripción de la etiqueta. Puede tener Markdown y se mostrará en la interfaz de documentación. +* `externalDocs`: un `dict` que describe documentación externa con: + * `description`: un `str` con una breve descripción para la documentación externa. + * `url` (**requerido**): un `str` con la URL para la documentación externa. + +### Crear metadata para etiquetas + +Probemos eso en un ejemplo con etiquetas para `users` y `items`. + +Crea metadata para tus etiquetas y pásala al parámetro `openapi_tags`: + +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} + +Nota que puedes utilizar Markdown dentro de las descripciones, por ejemplo "login" se mostrará en negrita (**login**) y "fancy" se mostrará en cursiva (_fancy_). + +/// tip | Consejo + +No tienes que agregar metadata para todas las etiquetas que uses. + +/// + +### Usar tus etiquetas + +Usa el parámetro `tags` con tus *path operations* (y `APIRouter`s) para asignarlas a diferentes etiquetas: + +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} + +/// info | Información + +Lee más sobre etiquetas en [Configuración de Path Operation](path-operation-configuration.md#tags){.internal-link target=_blank}. + +/// + +### Revisa la documentación + +Ahora, si revisas la documentación, mostrará toda la metadata adicional: + + + +### Orden de las etiquetas + +El orden de cada diccionario de metadata de etiqueta también define el orden mostrado en la interfaz de documentación. + +Por ejemplo, aunque `users` iría después de `items` en orden alfabético, se muestra antes porque agregamos su metadata como el primer diccionario en la list. + +## URL de OpenAPI + +Por defecto, el esquema OpenAPI se sirve en `/openapi.json`. + +Pero puedes configurarlo con el parámetro `openapi_url`. + +Por ejemplo, para configurarlo para que se sirva en `/api/v1/openapi.json`: + +{* ../../docs_src/metadata/tutorial002.py hl[3] *} + +Si quieres deshabilitar el esquema OpenAPI completamente, puedes establecer `openapi_url=None`, eso también deshabilitará las interfaces de usuario de documentación que lo usan. + +## URLs de Docs + +Puedes configurar las dos interfaces de usuario de documentación incluidas: + +* **Swagger UI**: servida en `/docs`. + * Puedes establecer su URL con el parámetro `docs_url`. + * Puedes deshabilitarla estableciendo `docs_url=None`. +* **ReDoc**: servida en `/redoc`. + * Puedes establecer su URL con el parámetro `redoc_url`. + * Puedes deshabilitarla estableciendo `redoc_url=None`. + +Por ejemplo, para configurar Swagger UI para que se sirva en `/documentation` y deshabilitar ReDoc: + +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/es/docs/tutorial/middleware.md b/docs/es/docs/tutorial/middleware.md new file mode 100644 index 000000000..296374525 --- /dev/null +++ b/docs/es/docs/tutorial/middleware.md @@ -0,0 +1,72 @@ +# Middleware + +Puedes añadir middleware a las aplicaciones de **FastAPI**. + +Un "middleware" es una función que trabaja con cada **request** antes de que sea procesada por cualquier *path operation* específica. Y también con cada **response** antes de devolverla. + +* Toma cada **request** que llega a tu aplicación. +* Puede entonces hacer algo a esa **request** o ejecutar cualquier código necesario. +* Luego pasa la **request** para que sea procesada por el resto de la aplicación (por alguna *path operation*). +* Después toma la **response** generada por la aplicación (por alguna *path operation*). +* Puede hacer algo a esa **response** o ejecutar cualquier código necesario. +* Luego devuelve la **response**. + +/// note | Detalles Técnicos + +Si tienes dependencias con `yield`, el código de salida se ejecutará *después* del middleware. + +Si hubiera alguna tarea en segundo plano (documentada más adelante), se ejecutará *después* de todo el middleware. + +/// + +## Crear un middleware + +Para crear un middleware usas el decorador `@app.middleware("http")` encima de una función. + +La función middleware recibe: + +* La `request`. +* Una función `call_next` que recibirá la `request` como parámetro. + * Esta función pasará la `request` a la correspondiente *path operation*. + * Luego devuelve la `response` generada por la correspondiente *path operation*. +* Puedes entonces modificar aún más la `response` antes de devolverla. + +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} + +/// tip | Consejo + +Ten en cuenta que los custom proprietary headers se pueden añadir usando el prefijo 'X-'. + +Pero si tienes custom headers que deseas que un cliente en un navegador pueda ver, necesitas añadirlos a tus configuraciones de CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) usando el parámetro `expose_headers` documentado en la documentación de CORS de Starlette. + +/// + +/// note | Detalles Técnicos + +También podrías usar `from starlette.requests import Request`. + +**FastAPI** lo proporciona como una conveniencia para ti, el desarrollador. Pero viene directamente de Starlette. + +/// + +### Antes y después de la `response` + +Puedes añadir código que se ejecute con la `request`, antes de que cualquier *path operation* la reciba. + +Y también después de que se genere la `response`, antes de devolverla. + +Por ejemplo, podrías añadir un custom header `X-Process-Time` que contenga el tiempo en segundos que tomó procesar la request y generar una response: + +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} + +/// tip | Consejo + +Aquí usamos `time.perf_counter()` en lugar de `time.time()` porque puede ser más preciso para estos casos de uso. 🤓 + +/// + +## Otros middlewares + +Más adelante puedes leer sobre otros middlewares en la [Guía del Usuario Avanzado: Middleware Avanzado](../advanced/middleware.md){.internal-link target=_blank}. + +Leerás sobre cómo manejar CORS con un middleware en la siguiente sección. diff --git a/docs/es/docs/tutorial/path-operation-configuration.md b/docs/es/docs/tutorial/path-operation-configuration.md new file mode 100644 index 000000000..909cd69b9 --- /dev/null +++ b/docs/es/docs/tutorial/path-operation-configuration.md @@ -0,0 +1,107 @@ +# Configuración de Path Operation + +Hay varios parámetros que puedes pasar a tu *path operation decorator* para configurarlo. + +/// warning | Advertencia + +Ten en cuenta que estos parámetros se pasan directamente al *path operation decorator*, no a tu *path operation function*. + +/// + +## Código de Estado del Response + +Puedes definir el `status_code` (HTTP) que se utilizará en el response de tu *path operation*. + +Puedes pasar directamente el código `int`, como `404`. + +Pero si no recuerdas para qué es cada código numérico, puedes usar las constantes atajo en `status`: + +{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *} + +Ese código de estado se usará en el response y se añadirá al esquema de OpenAPI. + +/// note | Detalles Técnicos + +También podrías usar `from starlette import status`. + +**FastAPI** ofrece el mismo `starlette.status` como `fastapi.status` solo por conveniencia para ti, el desarrollador. Pero viene directamente de Starlette. + +/// + +## Tags + +Puedes añadir tags a tu *path operation*, pasando el parámetro `tags` con un `list` de `str` (comúnmente solo una `str`): + +{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *} + +Serán añadidas al esquema de OpenAPI y usadas por las interfaces de documentación automática: + + + +### Tags con Enums + +Si tienes una gran aplicación, podrías terminar acumulando **varias tags**, y querrías asegurarte de que siempre uses la **misma tag** para *path operations* relacionadas. + +En estos casos, podría tener sentido almacenar las tags en un `Enum`. + +**FastAPI** soporta eso de la misma manera que con strings normales: + +{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *} + +## Resumen y Descripción + +Puedes añadir un `summary` y `description`: + +{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[18:19] *} + +## Descripción desde docstring + +Como las descripciones tienden a ser largas y cubrir múltiples líneas, puedes declarar la descripción de la *path operation* en la docstring de la función y **FastAPI** la leerá desde allí. + +Puedes escribir Markdown en el docstring, se interpretará y mostrará correctamente (teniendo en cuenta la indentación del docstring). + +{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *} + +Será usado en la documentación interactiva: + + + +## Descripción del Response + +Puedes especificar la descripción del response con el parámetro `response_description`: + +{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[19] *} + +/// info | Información + +Ten en cuenta que `response_description` se refiere específicamente al response, mientras que `description` se refiere a la *path operation* en general. + +/// + +/// check | Revisa + +OpenAPI especifica que cada *path operation* requiere una descripción de response. + +Entonces, si no proporcionas una, **FastAPI** generará automáticamente una de "Response exitoso". + +/// + + + +## Deprecar una *path operation* + +Si necesitas marcar una *path operation* como deprecated, pero sin eliminarla, pasa el parámetro `deprecated`: + +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} + +Se marcará claramente como deprecado en la documentación interactiva: + + + +Revisa cómo lucen las *path operations* deprecadas y no deprecadas: + + + +## Resumen + +Puedes configurar y añadir metadatos a tus *path operations* fácilmente pasando parámetros a los *path operation decorators*. diff --git a/docs/es/docs/tutorial/path-params-numeric-validations.md b/docs/es/docs/tutorial/path-params-numeric-validations.md new file mode 100644 index 000000000..44d73b5ed --- /dev/null +++ b/docs/es/docs/tutorial/path-params-numeric-validations.md @@ -0,0 +1,164 @@ +# Parámetros de Path y Validaciones Numéricas + +De la misma manera que puedes declarar más validaciones y metadatos para los parámetros de query con `Query`, puedes declarar el mismo tipo de validaciones y metadatos para los parámetros de path con `Path`. + +## Importar Path + +Primero, importa `Path` de `fastapi`, e importa `Annotated`: + +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *} + +/// info | Información + +FastAPI agregó soporte para `Annotated` (y comenzó a recomendar su uso) en la versión 0.95.0. + +Si tienes una versión anterior, obtendrás errores al intentar usar `Annotated`. + +Asegúrate de [Actualizar la versión de FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} a al menos la 0.95.1 antes de usar `Annotated`. + +/// + +## Declarar metadatos + +Puedes declarar todos los mismos parámetros que para `Query`. + +Por ejemplo, para declarar un valor de metadato `title` para el parámetro de path `item_id` puedes escribir: + +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *} + +/// note | Nota + +Un parámetro de path siempre es requerido ya que tiene que formar parte del path. Incluso si lo declaras con `None` o le asignas un valor por defecto, no afectará en nada, siempre será requerido. + +/// + +## Ordena los parámetros como necesites + +/// tip | Consejo + +Esto probablemente no es tan importante o necesario si usas `Annotated`. + +/// + +Supongamos que quieres declarar el parámetro de query `q` como un `str` requerido. + +Y no necesitas declarar nada más para ese parámetro, así que realmente no necesitas usar `Query`. + +Pero aún necesitas usar `Path` para el parámetro de path `item_id`. Y no quieres usar `Annotated` por alguna razón. + +Python se quejará si pones un valor con un "default" antes de un valor que no tenga un "default". + +Pero puedes reordenarlos y poner el valor sin un default (el parámetro de query `q`) primero. + +No importa para **FastAPI**. Detectará los parámetros por sus nombres, tipos y declaraciones por defecto (`Query`, `Path`, etc.), no le importa el orden. + +Así que puedes declarar tu función como: + +//// tab | Python 3.8 non-Annotated + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} + +//// + +Pero ten en cuenta que si usas `Annotated`, no tendrás este problema, no importará ya que no estás usando los valores por defecto de los parámetros de la función para `Query()` o `Path()`. + +{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py *} + +## Ordena los parámetros como necesites, trucos + +/// tip | Consejo + +Esto probablemente no es tan importante o necesario si usas `Annotated`. + +/// + +Aquí hay un **pequeño truco** que puede ser útil, pero no lo necesitarás a menudo. + +Si quieres: + +* declarar el parámetro de query `q` sin un `Query` ni ningún valor por defecto +* declarar el parámetro de path `item_id` usando `Path` +* tenerlos en un orden diferente +* no usar `Annotated` + +...Python tiene una sintaxis especial para eso. + +Pasa `*`, como el primer parámetro de la función. + +Python no hará nada con ese `*`, pero sabrá que todos los parámetros siguientes deben ser llamados como argumentos de palabras clave (parejas key-value), también conocidos como kwargs. Incluso si no tienen un valor por defecto. + +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} + +### Mejor con `Annotated` + +Ten en cuenta que si usas `Annotated`, como no estás usando valores por defecto de los parámetros de la función, no tendrás este problema y probablemente no necesitarás usar `*`. + +{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *} + +## Validaciones numéricas: mayor o igual + +Con `Query` y `Path` (y otros que verás más adelante) puedes declarar restricciones numéricas. + +Aquí, con `ge=1`, `item_id` necesitará ser un número entero "`g`reater than or `e`qual" a `1`. + +{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *} + +## Validaciones numéricas: mayor que y menor o igual + +Lo mismo aplica para: + +* `gt`: `g`reater `t`han +* `le`: `l`ess than or `e`qual + +{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *} + +## Validaciones numéricas: flotantes, mayor y menor + +Las validaciones numéricas también funcionan para valores `float`. + +Aquí es donde se convierte en importante poder declarar gt y no solo ge. Ya que con esto puedes requerir, por ejemplo, que un valor sea mayor que `0`, incluso si es menor que `1`. + +Así, `0.5` sería un valor válido. Pero `0.0` o `0` no lo serían. + +Y lo mismo para lt. + +{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *} + +## Resumen + +Con `Query`, `Path` (y otros que aún no has visto) puedes declarar metadatos y validaciones de string de las mismas maneras que con [Parámetros de Query y Validaciones de String](query-params-str-validations.md){.internal-link target=_blank}. + +Y también puedes declarar validaciones numéricas: + +* `gt`: `g`reater `t`han +* `ge`: `g`reater than or `e`qual +* `lt`: `l`ess `t`han +* `le`: `l`ess than or `e`qual + +/// info | Información + +`Query`, `Path` y otras clases que verás más adelante son subclases de una clase común `Param`. + +Todas ellas comparten los mismos parámetros para validación adicional y metadatos que has visto. + +/// + +/// note | Nota técnica + +Cuando importas `Query`, `Path` y otros de `fastapi`, en realidad son funciones. + +Que cuando se llaman, retornan instances de clases con el mismo nombre. + +Así que importas `Query`, que es una función. Y cuando la llamas, retorna una instance de una clase también llamada `Query`. + +Estas funciones están allí (en lugar de usar simplemente las clases directamente) para que tu editor no marque errores sobre sus tipos. + +De esa forma puedes usar tu editor y herramientas de programación normales sin tener que agregar configuraciones personalizadas para omitir esos errores. + +/// diff --git a/docs/es/docs/tutorial/query-param-models.md b/docs/es/docs/tutorial/query-param-models.md new file mode 100644 index 000000000..8338fc358 --- /dev/null +++ b/docs/es/docs/tutorial/query-param-models.md @@ -0,0 +1,68 @@ +# Modelos de Parámetros Query + +Si tienes un grupo de **parámetros query** que están relacionados, puedes crear un **modelo de Pydantic** para declararlos. + +Esto te permitiría **reutilizar el modelo** en **múltiples lugares** y también declarar validaciones y metadatos para todos los parámetros de una vez. 😎 + +/// note | Nota + +Esto es compatible desde la versión `0.115.0` de FastAPI. 🤓 + +/// + +## Parámetros Query con un Modelo Pydantic + +Declara los **parámetros query** que necesitas en un **modelo de Pydantic**, y luego declara el parámetro como `Query`: + +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} + +**FastAPI** **extraerá** los datos para **cada campo** de los **parámetros query** en el request y te proporcionará el modelo de Pydantic que definiste. + +## Revisa la Documentación + +Puedes ver los parámetros query en la UI de documentación en `/docs`: + +
+ +
+ +## Prohibir Parámetros Query Extras + +En algunos casos de uso especiales (probablemente no muy comunes), podrías querer **restringir** los parámetros query que deseas recibir. + +Puedes usar la configuración del modelo de Pydantic para `forbid` cualquier campo `extra`: + +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} + +Si un cliente intenta enviar algunos datos **extra** en los **parámetros query**, recibirán un response de **error**. + +Por ejemplo, si el cliente intenta enviar un parámetro query `tool` con un valor de `plumbus`, como: + +```http +https://example.com/items/?limit=10&tool=plumbus +``` + +Recibirán un response de **error** que les indica que el parámetro query `tool` no está permitido: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus" + } + ] +} +``` + +## Resumen + +Puedes usar **modelos de Pydantic** para declarar **parámetros query** en **FastAPI**. 😎 + +/// tip | Consejo + +Alerta de spoiler: también puedes usar modelos de Pydantic para declarar cookies y headers, pero leerás sobre eso más adelante en el tutorial. 🤫 + +/// diff --git a/docs/es/docs/tutorial/query-params-str-validations.md b/docs/es/docs/tutorial/query-params-str-validations.md new file mode 100644 index 000000000..f378b9dce --- /dev/null +++ b/docs/es/docs/tutorial/query-params-str-validations.md @@ -0,0 +1,515 @@ +# Parámetros de Query y Validaciones de String + +**FastAPI** te permite declarar información adicional y validación para tus parámetros. + +Tomemos esta aplicación como ejemplo: + +{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *} + +El parámetro de query `q` es del tipo `Union[str, None]` (o `str | None` en Python 3.10), lo que significa que es de tipo `str` pero también podría ser `None`, y de hecho, el valor por defecto es `None`, así que FastAPI sabrá que no es requerido. + +/// note | Nota + +FastAPI sabrá que el valor de `q` no es requerido por el valor por defecto `= None`. + +El `Union` en `Union[str, None]` permitirá a tu editor darte un mejor soporte y detectar errores. + +/// + +## Validaciones adicionales + +Vamos a hacer que, aunque `q` sea opcional, siempre que se proporcione, **su longitud no exceda los 50 caracteres**. + +### Importar `Query` y `Annotated` + +Para lograr eso, primero importa: + +* `Query` desde `fastapi` +* `Annotated` desde `typing` (o desde `typing_extensions` en Python por debajo de 3.9) + +//// tab | Python 3.10+ + +En Python 3.9 o superior, `Annotated` es parte de la biblioteca estándar, así que puedes importarlo desde `typing`. + +```Python hl_lines="1 3" +{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +En versiones de Python por debajo de 3.9 importas `Annotated` desde `typing_extensions`. + +Ya estará instalado con FastAPI. + +```Python hl_lines="3-4" +{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} +``` + +//// + +/// info | Información + +FastAPI añadió soporte para `Annotated` (y empezó a recomendarlo) en la versión 0.95.0. + +Si tienes una versión más antigua, obtendrás errores al intentar usar `Annotated`. + +Asegúrate de [Actualizar la versión de FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} a al menos 0.95.1 antes de usar `Annotated`. + +/// + +## Usar `Annotated` en el tipo del parámetro `q` + +¿Recuerdas que te dije antes que `Annotated` puede ser usado para agregar metadatos a tus parámetros en la [Introducción a Tipos de Python](../python-types.md#type-hints-with-metadata-annotations){.internal-link target=_blank}? + +Ahora es el momento de usarlo con FastAPI. 🚀 + +Teníamos esta anotación de tipo: + +//// tab | Python 3.10+ + +```Python +q: str | None = None +``` + +//// + +//// tab | Python 3.8+ + +```Python +q: Union[str, None] = None +``` + +//// + +Lo que haremos es envolver eso con `Annotated`, para que se convierta en: + +//// tab | Python 3.10+ + +```Python +q: Annotated[str | None] = None +``` + +//// + +//// tab | Python 3.8+ + +```Python +q: Annotated[Union[str, None]] = None +``` + +//// + +Ambas versiones significan lo mismo, `q` es un parámetro que puede ser un `str` o `None`, y por defecto, es `None`. + +Ahora vamos a lo divertido. 🎉 + +## Agregar `Query` a `Annotated` en el parámetro `q` + +Ahora que tenemos este `Annotated` donde podemos poner más información (en este caso algunas validaciones adicionales), agrega `Query` dentro de `Annotated`, y establece el parámetro `max_length` a `50`: + +{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[9] *} + +Nota que el valor por defecto sigue siendo `None`, por lo que el parámetro sigue siendo opcional. + +Pero ahora, al tener `Query(max_length=50)` dentro de `Annotated`, le estamos diciendo a FastAPI que queremos que tenga **validación adicional** para este valor, queremos que tenga un máximo de 50 caracteres. 😎 + +/// tip | Consejo + +Aquí estamos usando `Query()` porque este es un **parámetro de query**. Más adelante veremos otros como `Path()`, `Body()`, `Header()`, y `Cookie()`, que también aceptan los mismos argumentos que `Query()`. + +/// + +FastAPI ahora: + +* **Validará** los datos asegurándose de que la longitud máxima sea de 50 caracteres +* Mostrará un **error claro** para el cliente cuando los datos no sean válidos +* **Documentará** el parámetro en el OpenAPI esquema *path operation* (así aparecerá en la **UI de documentación automática**) + +## Alternativa (antigua): `Query` como valor por defecto + +Versiones anteriores de FastAPI (antes de 0.95.0) requerían que usaras `Query` como el valor por defecto de tu parámetro, en lugar de ponerlo en `Annotated`. Hay una alta probabilidad de que veas código usándolo alrededor, así que te lo explicaré. + +/// tip | Consejo + +Para nuevo código y siempre que sea posible, usa `Annotated` como se explicó arriba. Hay múltiples ventajas (explicadas a continuación) y no hay desventajas. 🍰 + +/// + +Así es como usarías `Query()` como el valor por defecto de tu parámetro de función, estableciendo el parámetro `max_length` a 50: + +{* ../../docs_src/query_params_str_validations/tutorial002_py310.py hl[7] *} + +Ya que en este caso (sin usar `Annotated`) debemos reemplazar el valor por defecto `None` en la función con `Query()`, ahora necesitamos establecer el valor por defecto con el parámetro `Query(default=None)`, esto sirve al mismo propósito de definir ese valor por defecto (al menos para FastAPI). + +Entonces: + +```Python +q: Union[str, None] = Query(default=None) +``` + +...hace que el parámetro sea opcional, con un valor por defecto de `None`, lo mismo que: + +```Python +q: Union[str, None] = None +``` + +Y en Python 3.10 y superior: + +```Python +q: str | None = Query(default=None) +``` + +...hace que el parámetro sea opcional, con un valor por defecto de `None`, lo mismo que: + +```Python +q: str | None = None +``` + +Pero las versiones de `Query` lo declaran explícitamente como un parámetro de query. + +/// info | Información + +Ten en cuenta que la parte más importante para hacer un parámetro opcional es la parte: + +```Python += None +``` + +o la parte: + +```Python += Query(default=None) +``` + +ya que usará ese `None` como el valor por defecto, y de esa manera hará el parámetro **no requerido**. + +La parte `Union[str, None]` permite que tu editor brinde un mejor soporte, pero no es lo que le dice a FastAPI que este parámetro no es requerido. + +/// + +Luego, podemos pasar más parámetros a `Query`. En este caso, el parámetro `max_length` que se aplica a los strings: + +```Python +q: Union[str, None] = Query(default=None, max_length=50) +``` + +Esto validará los datos, mostrará un error claro cuando los datos no sean válidos, y documentará el parámetro en el esquema del *path operation* de OpenaPI. + +### `Query` como valor por defecto o en `Annotated` + +Ten en cuenta que cuando uses `Query` dentro de `Annotated` no puedes usar el parámetro `default` para `Query`. + +En su lugar utiliza el valor por defecto real del parámetro de la función. De lo contrario, sería inconsistente. + +Por ejemplo, esto no está permitido: + +```Python +q: Annotated[str, Query(default="rick")] = "morty" +``` + +...porque no está claro si el valor por defecto debería ser `"rick"` o `"morty"`. + +Así que utilizarías (preferentemente): + +```Python +q: Annotated[str, Query()] = "rick" +``` + +...o en code bases más antiguos encontrarás: + +```Python +q: str = Query(default="rick") +``` + +### Ventajas de `Annotated` + +**Usar `Annotated` es recomendado** en lugar del valor por defecto en los parámetros de función, es **mejor** por múltiples razones. 🤓 + +El valor **por defecto** del **parámetro de función** es el valor **real por defecto**, eso es más intuitivo con Python en general. 😌 + +Podrías **llamar** a esa misma función en **otros lugares** sin FastAPI, y **funcionaría como se espera**. Si hay un parámetro **requerido** (sin un valor por defecto), tu **editor** te avisará con un error, **Python** también se quejará si lo ejecutas sin pasar el parámetro requerido. + +Cuando no usas `Annotated` y en su lugar usas el estilo de valor por defecto **(antiguo)**, si llamas a esa función sin FastAPI en **otros lugares**, tienes que **recordar** pasar los argumentos a la función para que funcione correctamente, de lo contrario, los valores serán diferentes de lo que esperas (por ejemplo, `QueryInfo` o algo similar en lugar de `str`). Y tu editor no se quejará, y Python no se quejará al ejecutar esa función, solo cuando los errores dentro de las operaciones hagan que funcione incorrectamente. + +Dado que `Annotated` puede tener más de una anotación de metadato, ahora podrías incluso usar la misma función con otras herramientas, como Typer. 🚀 + +## Agregar más validaciones + +También puedes agregar un parámetro `min_length`: + +{* ../../docs_src/query_params_str_validations/tutorial003_an_py310.py hl[10] *} + +## Agregar expresiones regulares + +Puedes definir una expresión regular `pattern` que el parámetro debe coincidir: + +{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *} + +Este patrón específico de expresión regular comprueba que el valor recibido del parámetro: + +* `^`: comience con los siguientes caracteres, no tiene caracteres antes. +* `fixedquery`: tiene el valor exacto `fixedquery`. +* `$`: termina allí, no tiene más caracteres después de `fixedquery`. + +Si te sientes perdido con todas estas ideas de **"expresión regular"**, no te preocupes. Son un tema difícil para muchas personas. Aún puedes hacer muchas cosas sin necesitar expresiones regulares todavía. + +Pero cuando las necesites y vayas a aprenderlas, ya sabes que puedes usarlas directamente en **FastAPI**. + +### Pydantic v1 `regex` en lugar de `pattern` + +Antes de la versión 2 de Pydantic y antes de FastAPI 0.100.0, el parámetro se llamaba `regex` en lugar de `pattern`, pero ahora está en desuso. + +Todavía podrías ver algo de código que lo usa: + +//// tab | Pydantic v1 + +{* ../../docs_src/query_params_str_validations/tutorial004_regex_an_py310.py hl[11] *} + +//// + +Pero que sepas que esto está deprecado y debería actualizarse para usar el nuevo parámetro `pattern`. 🤓 + +## Valores por defecto + +Puedes, por supuesto, usar valores por defecto diferentes de `None`. + +Digamos que quieres declarar el parámetro de query `q` para que tenga un `min_length` de `3`, y para que tenga un valor por defecto de `"fixedquery"`: + +{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *} + +/// note | Nota + +Tener un valor por defecto de cualquier tipo, incluyendo `None`, hace que el parámetro sea opcional (no requerido). + +/// + +## Parámetros requeridos + +Cuando no necesitamos declarar más validaciones o metadatos, podemos hacer que el parámetro de query `q` sea requerido simplemente no declarando un valor por defecto, como: + +```Python +q: str +``` + +en lugar de: + +```Python +q: Union[str, None] = None +``` + +Pero ahora lo estamos declarando con `Query`, por ejemplo, como: + +//// tab | Annotated + +```Python +q: Annotated[Union[str, None], Query(min_length=3)] = None +``` + +//// + +//// tab | non-Annotated + +```Python +q: Union[str, None] = Query(default=None, min_length=3) +``` + +//// + +Así que, cuando necesites declarar un valor como requerido mientras usas `Query`, simplemente puedes no declarar un valor por defecto: + +{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} + +### Requerido con Puntos suspensivos (`...`) + +Hay una manera alternativa de declarar explícitamente que un valor es requerido. Puedes establecer el valor por defecto al valor literal `...`: + +{* ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py hl[9] *} + +/// info | Información + +Si no habías visto eso `...` antes: es un valor especial único, es parte de Python y se llama "Ellipsis". + +Se usa por Pydantic y FastAPI para declarar explícitamente que un valor es requerido. + +/// + +Esto le permitirá a **FastAPI** saber que este parámetro es requerido. + +### Requerido, puede ser `None` + +Puedes declarar que un parámetro puede aceptar `None`, pero que aún así es requerido. Esto obligaría a los clientes a enviar un valor, incluso si el valor es `None`. + +Para hacer eso, puedes declarar que `None` es un tipo válido pero aún usar `...` como el valor por defecto: + +{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} + +/// tip | Consejo + +Pydantic, que es lo que impulsa toda la validación y serialización de datos en FastAPI, tiene un comportamiento especial cuando usas `Optional` o `Union[Something, None]` sin un valor por defecto, puedes leer más al respecto en la documentación de Pydantic sobre Campos requeridos. + +/// + +/// tip | Consejo + +Recuerda que en la mayoría de los casos, cuando algo es requerido, puedes simplemente omitir el default, así que normalmente no tienes que usar `...`. + +/// + +## Lista de parámetros de Query / múltiples valores + +Cuando defines un parámetro de query explícitamente con `Query` también puedes declararlo para recibir una lista de valores, o dicho de otra manera, para recibir múltiples valores. + +Por ejemplo, para declarar un parámetro de query `q` que puede aparecer varias veces en la URL, puedes escribir: + +{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *} + +Entonces, con una URL como: + +``` +http://localhost:8000/items/?q=foo&q=bar +``` + +recibirías los múltiples valores del *query parameter* `q` (`foo` y `bar`) en una `list` de Python dentro de tu *path operation function*, en el *parámetro de función* `q`. + +Entonces, el response a esa URL sería: + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +/// tip | Consejo + +Para declarar un parámetro de query con un tipo de `list`, como en el ejemplo anterior, necesitas usar explícitamente `Query`, de lo contrario sería interpretado como un request body. + +/// + +La documentación interactiva de API se actualizará en consecuencia, para permitir múltiples valores: + + + +### Lista de parámetros de Query / múltiples valores con valores por defecto + +Y también puedes definir un valor por defecto `list` de valores si no se proporcionan ninguno: + +{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *} + +Si vas a: + +``` +http://localhost:8000/items/ +``` + +el valor por defecto de `q` será: `["foo", "bar"]` y tu response será: + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +#### Usando solo `list` + +También puedes usar `list` directamente en lugar de `List[str]` (o `list[str]` en Python 3.9+): + +{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *} + +/// note | Nota + +Ten en cuenta que en este caso, FastAPI no comprobará el contenido de la lista. + +Por ejemplo, `List[int]` comprobaría (y documentaría) que el contenido de la lista son enteros. Pero `list` sola no lo haría. + +/// + +## Declarar más metadatos + +Puedes agregar más información sobre el parámetro. + +Esa información se incluirá en el OpenAPI generado y será utilizada por las interfaces de usuario de documentación y herramientas externas. + +/// note | Nota + +Ten en cuenta que diferentes herramientas podrían tener diferentes niveles de soporte de OpenAPI. + +Algunas de ellas podrían no mostrar toda la información extra declarada todavía, aunque en la mayoría de los casos, la funcionalidad faltante ya está planificada para desarrollo. + +/// + +Puedes agregar un `title`: + +{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *} + +Y una `description`: + +{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *} + +## Alias para parámetros + +Imagina que quieres que el parámetro sea `item-query`. + +Como en: + +``` +http://127.0.0.1:8000/items/?item-query=foobaritems +``` + +Pero `item-query` no es un nombre de variable válido en Python. + +Lo más cercano sería `item_query`. + +Pero aún necesitas que sea exactamente `item-query`... + +Entonces puedes declarar un `alias`, y ese alias será usado para encontrar el valor del parámetro: + +{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *} + +## Declarar parámetros obsoletos + +Ahora digamos que ya no te gusta este parámetro. + +Tienes que dejarlo allí por un tiempo porque hay clientes usándolo, pero quieres que la documentación lo muestre claramente como deprecated. + +Luego pasa el parámetro `deprecated=True` a `Query`: + +{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *} + +La documentación lo mostrará así: + + + +## Excluir parámetros de OpenAPI + +Para excluir un parámetro de query del esquema de OpenAPI generado (y por lo tanto, de los sistemas de documentación automática), establece el parámetro `include_in_schema` de `Query` a `False`: + +{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *} + +## Recapitulación + +Puedes declarar validaciones y metadatos adicionales para tus parámetros. + +Validaciones genéricas y metadatos: + +* `alias` +* `title` +* `description` +* `deprecated` + +Validaciones específicas para strings: + +* `min_length` +* `max_length` +* `pattern` + +En estos ejemplos viste cómo declarar validaciones para valores de tipo `str`. + +Mira los siguientes capítulos para aprender cómo declarar validaciones para otros tipos, como números. diff --git a/docs/es/docs/tutorial/request-files.md b/docs/es/docs/tutorial/request-files.md new file mode 100644 index 000000000..330523c7e --- /dev/null +++ b/docs/es/docs/tutorial/request-files.md @@ -0,0 +1,176 @@ +# Archivos de Request + +Puedes definir archivos que serán subidos por el cliente utilizando `File`. + +/// info | Información + +Para recibir archivos subidos, primero instala `python-multipart`. + +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, activarlo y luego instalarlo, por ejemplo: + +```console +$ pip install python-multipart +``` + +Esto es porque los archivos subidos se envían como "form data". + +/// + +## Importar `File` + +Importa `File` y `UploadFile` desde `fastapi`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} + +## Definir Parámetros `File` + +Crea parámetros de archivo de la misma manera que lo harías para `Body` o `Form`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} + +/// info | Información + +`File` es una clase que hereda directamente de `Form`. + +Pero recuerda que cuando importas `Query`, `Path`, `File` y otros desde `fastapi`, esos son en realidad funciones que devuelven clases especiales. + +/// + +/// tip | Consejo + +Para declarar cuerpos de File, necesitas usar `File`, porque de otra manera los parámetros serían interpretados como parámetros query o parámetros de cuerpo (JSON). + +/// + +Los archivos se subirán como "form data". + +Si declaras el tipo de tu parámetro de *path operation function* como `bytes`, **FastAPI** leerá el archivo por ti y recibirás el contenido como `bytes`. + +Ten en cuenta que esto significa que todo el contenido se almacenará en memoria. Esto funcionará bien para archivos pequeños. + +Pero hay varios casos en los que podrías beneficiarte de usar `UploadFile`. + +## Parámetros de Archivo con `UploadFile` + +Define un parámetro de archivo con un tipo de `UploadFile`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} + +Usar `UploadFile` tiene varias ventajas sobre `bytes`: + +* No tienes que usar `File()` en el valor por defecto del parámetro. +* Usa un archivo "spooled": + * Un archivo almacenado en memoria hasta un límite de tamaño máximo, y después de superar este límite, se almacenará en el disco. +* Esto significa que funcionará bien para archivos grandes como imágenes, videos, binarios grandes, etc. sin consumir toda la memoria. +* Puedes obtener metadatos del archivo subido. +* Tiene una interfaz `async` parecida a un archivo. +* Expone un objeto Python real `SpooledTemporaryFile` que puedes pasar directamente a otros paquetes que esperan un objeto parecido a un archivo. + +### `UploadFile` + +`UploadFile` tiene los siguientes atributos: + +* `filename`: Un `str` con el nombre original del archivo que fue subido (por ejemplo, `myimage.jpg`). +* `content_type`: Un `str` con el tipo de contenido (MIME type / media type) (por ejemplo, `image/jpeg`). +* `file`: Un `SpooledTemporaryFile` (un objeto parecido a un archivo). Este es el objeto de archivo Python real que puedes pasar directamente a otras funciones o paquetes que esperan un objeto "parecido a un archivo". + +`UploadFile` tiene los siguientes métodos `async`. Todos ellos llaman a los métodos correspondientes del archivo por debajo (usando el `SpooledTemporaryFile` interno). + +* `write(data)`: Escribe `data` (`str` o `bytes`) en el archivo. +* `read(size)`: Lee `size` (`int`) bytes/caracteres del archivo. +* `seek(offset)`: Va a la posición de bytes `offset` (`int`) en el archivo. + * Por ejemplo, `await myfile.seek(0)` iría al inicio del archivo. + * Esto es especialmente útil si ejecutas `await myfile.read()` una vez y luego necesitas leer el contenido nuevamente. +* `close()`: Cierra el archivo. + +Como todos estos métodos son métodos `async`, necesitas "await" para ellos. + +Por ejemplo, dentro de una *path operation function* `async` puedes obtener los contenidos con: + +```Python +contents = await myfile.read() +``` + +Si estás dentro de una *path operation function* normal `def`, puedes acceder al `UploadFile.file` directamente, por ejemplo: + +```Python +contents = myfile.file.read() +``` + +/// note | Detalles Técnicos de `async` + +Cuando usas los métodos `async`, **FastAPI** ejecuta los métodos del archivo en un threadpool y los espera. + +/// + +/// note | Detalles Técnicos de Starlette + +El `UploadFile` de **FastAPI** hereda directamente del `UploadFile` de **Starlette**, pero añade algunas partes necesarias para hacerlo compatible con **Pydantic** y las otras partes de FastAPI. + +/// + +## Qué es "Form Data" + +La manera en que los forms de HTML (`
`) envían los datos al servidor normalmente utiliza una codificación "especial" para esos datos, es diferente de JSON. + +**FastAPI** se asegurará de leer esos datos del lugar correcto en lugar de JSON. + +/// note | Detalles Técnicos + +Los datos de los forms normalmente se codifican usando el "media type" `application/x-www-form-urlencoded` cuando no incluyen archivos. + +Pero cuando el formulario incluye archivos, se codifica como `multipart/form-data`. Si usas `File`, **FastAPI** sabrá que tiene que obtener los archivos de la parte correcta del cuerpo. + +Si deseas leer más sobre estas codificaciones y campos de formularios, dirígete a la MDN web docs para POST. + +/// + +/// warning | Advertencia + +Puedes declarar múltiples parámetros `File` y `Form` en una *path operation*, pero no puedes declarar campos `Body` que esperas recibir como JSON, ya que el request tendrá el cuerpo codificado usando `multipart/form-data` en lugar de `application/json`. + +Esto no es una limitación de **FastAPI**, es parte del protocolo HTTP. + +/// + +## Subida de Archivos Opcional + +Puedes hacer un archivo opcional utilizando anotaciones de tipos estándar y estableciendo un valor por defecto de `None`: + +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} + +## `UploadFile` con Metadatos Adicionales + +También puedes usar `File()` con `UploadFile`, por ejemplo, para establecer metadatos adicionales: + +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} + +## Subidas de Múltiples Archivos + +Es posible subir varios archivos al mismo tiempo. + +Estarían asociados al mismo "campo de formulario" enviado usando "form data". + +Para usar eso, declara una lista de `bytes` o `UploadFile`: + +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} + +Recibirás, como se declaró, una `list` de `bytes` o `UploadFile`s. + +/// note | Detalles Técnicos + +También podrías usar `from starlette.responses import HTMLResponse`. + +**FastAPI** proporciona las mismas `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette. + +/// + +### Subidas de Múltiples Archivos con Metadatos Adicionales + +Y de la misma manera que antes, puedes usar `File()` para establecer parámetros adicionales, incluso para `UploadFile`: + +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} + +## Recapitulación + +Usa `File`, `bytes` y `UploadFile` para declarar archivos que se subirán en el request, enviados como form data. diff --git a/docs/es/docs/tutorial/request-form-models.md b/docs/es/docs/tutorial/request-form-models.md new file mode 100644 index 000000000..9d5d7495a --- /dev/null +++ b/docs/es/docs/tutorial/request-form-models.md @@ -0,0 +1,78 @@ +# Modelos de Formulario + +Puedes usar **modelos de Pydantic** para declarar **campos de formulario** en FastAPI. + +/// info | Información + +Para usar formularios, primero instala `python-multipart`. + +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, activarlo, y luego instalarlo, por ejemplo: + +```console +$ pip install python-multipart +``` + +/// + +/// note | Nota + +Esto es compatible desde la versión `0.113.0` de FastAPI. 🤓 + +/// + +## Modelos de Pydantic para Formularios + +Solo necesitas declarar un **modelo de Pydantic** con los campos que quieres recibir como **campos de formulario**, y luego declarar el parámetro como `Form`: + +{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *} + +**FastAPI** **extraerá** los datos de **cada campo** de los **form data** en el request y te dará el modelo de Pydantic que definiste. + +## Revisa la Documentación + +Puedes verificarlo en la interfaz de documentación en `/docs`: + +
+ +
+ +## Prohibir Campos de Formulario Extra + +En algunos casos de uso especiales (probablemente no muy comunes), podrías querer **restringir** los campos de formulario a solo aquellos declarados en el modelo de Pydantic. Y **prohibir** cualquier campo **extra**. + +/// note | Nota + +Esto es compatible desde la versión `0.114.0` de FastAPI. 🤓 + +/// + +Puedes usar la configuración del modelo de Pydantic para `forbid` cualquier campo `extra`: + +{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *} + +Si un cliente intenta enviar datos extra, recibirá un response de **error**. + +Por ejemplo, si el cliente intenta enviar los campos de formulario: + +* `username`: `Rick` +* `password`: `Portal Gun` +* `extra`: `Mr. Poopybutthole` + +Recibirá un response de error indicando que el campo `extra` no está permitido: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "Mr. Poopybutthole" + } + ] +} +``` + +## Resumen + +Puedes usar modelos de Pydantic para declarar campos de formulario en FastAPI. 😎 diff --git a/docs/es/docs/tutorial/request-forms-and-files.md b/docs/es/docs/tutorial/request-forms-and-files.md new file mode 100644 index 000000000..51dfbb357 --- /dev/null +++ b/docs/es/docs/tutorial/request-forms-and-files.md @@ -0,0 +1,41 @@ +# Request Forms and Files + +Puedes definir archivos y campos de formulario al mismo tiempo usando `File` y `Form`. + +/// info | Información + +Para recibir archivos subidos y/o form data, primero instala `python-multipart`. + +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, actívalo y luego instálalo, por ejemplo: + +```console +$ pip install python-multipart +``` + +/// + +## Importar `File` y `Form` + +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *} + +## Definir parámetros `File` y `Form` + +Crea parámetros de archivo y formulario de la misma manera que lo harías para `Body` o `Query`: + +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *} + +Los archivos y campos de formulario se subirán como form data y recibirás los archivos y campos de formulario. + +Y puedes declarar algunos de los archivos como `bytes` y algunos como `UploadFile`. + +/// warning | Advertencia + +Puedes declarar múltiples parámetros `File` y `Form` en una *path operation*, pero no puedes también declarar campos `Body` que esperas recibir como JSON, ya que el request tendrá el body codificado usando `multipart/form-data` en lugar de `application/json`. + +Esto no es una limitación de **FastAPI**, es parte del protocolo HTTP. + +/// + +## Resumen + +Usa `File` y `Form` juntos cuando necesites recibir datos y archivos en el mismo request. diff --git a/docs/es/docs/tutorial/request-forms.md b/docs/es/docs/tutorial/request-forms.md new file mode 100644 index 000000000..a9d62e660 --- /dev/null +++ b/docs/es/docs/tutorial/request-forms.md @@ -0,0 +1,73 @@ +# Form Data + +Cuando necesitas recibir campos de formulario en lugar de JSON, puedes usar `Form`. + +/// info | Información + +Para usar forms, primero instala `python-multipart`. + +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, activarlo, y luego instalarlo, por ejemplo: + +```console +$ pip install python-multipart +``` + +/// + +## Importar `Form` + +Importar `Form` desde `fastapi`: + +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} + +## Definir parámetros de `Form` + +Crea parámetros de formulario de la misma manera que lo harías para `Body` o `Query`: + +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} + +Por ejemplo, en una de las formas en las que se puede usar la especificación OAuth2 (llamada "password flow") se requiere enviar un `username` y `password` como campos de formulario. + +La especificación requiere que los campos se llamen exactamente `username` y `password`, y que se envíen como campos de formulario, no JSON. + +Con `Form` puedes declarar las mismas configuraciones que con `Body` (y `Query`, `Path`, `Cookie`), incluyendo validación, ejemplos, un alias (por ejemplo, `user-name` en lugar de `username`), etc. + +/// info | Información + +`Form` es una clase que hereda directamente de `Body`. + +/// + +/// tip | Consejo + +Para declarar bodies de forms, necesitas usar `Form` explícitamente, porque sin él, los parámetros se interpretarían como parámetros de query o como parámetros de body (JSON). + +/// + +## Sobre "Campos de Formulario" + +La manera en que los forms HTML (`
`) envían los datos al servidor normalmente usa una codificación "especial" para esos datos, es diferente de JSON. + +**FastAPI** se encargará de leer esos datos del lugar correcto en lugar de JSON. + +/// note | Detalles técnicos + +Los datos de forms normalmente se codifican usando el "media type" `application/x-www-form-urlencoded`. + +Pero cuando el formulario incluye archivos, se codifica como `multipart/form-data`. Leerás sobre la gestión de archivos en el próximo capítulo. + +Si quieres leer más sobre estas codificaciones y campos de formulario, dirígete a la MDN web docs para POST. + +/// + +/// warning | Advertencia + +Puedes declarar múltiples parámetros `Form` en una *path operation*, pero no puedes también declarar campos `Body` que esperas recibir como JSON, ya que el request tendrá el body codificado usando `application/x-www-form-urlencoded` en lugar de `application/json`. + +Esto no es una limitación de **FastAPI**, es parte del protocolo HTTP. + +/// + +## Recapitulación + +Usa `Form` para declarar parámetros de entrada de datos de formulario. diff --git a/docs/es/docs/tutorial/response-model.md b/docs/es/docs/tutorial/response-model.md new file mode 100644 index 000000000..09682f51b --- /dev/null +++ b/docs/es/docs/tutorial/response-model.md @@ -0,0 +1,357 @@ +# Modelo de Response - Tipo de Retorno + +Puedes declarar el tipo utilizado para el response anotando el **tipo de retorno** de la *path operation function*. + +Puedes utilizar **anotaciones de tipos** de la misma manera que lo harías para datos de entrada en **parámetros** de función, puedes utilizar modelos de Pydantic, listas, diccionarios, valores escalares como enteros, booleanos, etc. + +{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *} + +FastAPI usará este tipo de retorno para: + +* **Validar** los datos devueltos. + * Si los datos son inválidos (por ejemplo, falta un campo), significa que el código de *tu* aplicación está defectuoso, no devolviendo lo que debería, y retornará un error del servidor en lugar de devolver datos incorrectos. De esta manera, tú y tus clientes pueden estar seguros de que recibirán los datos y la forma de los datos esperada. +* Agregar un **JSON Schema** para el response, en la *path operation* de OpenAPI. + * Esto será utilizado por la **documentación automática**. + * También será utilizado por herramientas de generación automática de código de cliente. + +Pero lo más importante: + +* **Limitará y filtrará** los datos de salida a lo que se define en el tipo de retorno. + * Esto es particularmente importante para la **seguridad**, veremos más sobre eso a continuación. + +## Parámetro `response_model` + +Hay algunos casos en los que necesitas o quieres devolver algunos datos que no son exactamente lo que declara el tipo. + +Por ejemplo, podrías querer **devolver un diccionario** u objeto de base de datos, pero **declararlo como un modelo de Pydantic**. De esta manera el modelo de Pydantic haría toda la documentación de datos, validación, etc. para el objeto que devolviste (por ejemplo, un diccionario u objeto de base de datos). + +Si añadiste la anotación del tipo de retorno, las herramientas y editores se quejarían con un error (correcto) diciéndote que tu función está devolviendo un tipo (por ejemplo, un dict) que es diferente de lo que declaraste (por ejemplo, un modelo de Pydantic). + +En esos casos, puedes usar el parámetro del decorador de path operation `response_model` en lugar del tipo de retorno. + +Puedes usar el parámetro `response_model` en cualquiera de las *path operations*: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* etc. + +{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *} + +/// note | Nota + +Observa que `response_model` es un parámetro del método "decorador" (`get`, `post`, etc). No de tu *path operation function*, como todos los parámetros y el cuerpo. + +/// + +`response_model` recibe el mismo tipo que declararías para un campo de modelo Pydantic, por lo que puede ser un modelo de Pydantic, pero también puede ser, por ejemplo, un `list` de modelos de Pydantic, como `List[Item]`. + +FastAPI usará este `response_model` para hacer toda la documentación de datos, validación, etc. y también para **convertir y filtrar los datos de salida** a su declaración de tipo. + +/// tip | Consejo + +Si tienes chequeos estrictos de tipos en tu editor, mypy, etc., puedes declarar el tipo de retorno de la función como `Any`. + +De esa manera le dices al editor que intencionalmente estás devolviendo cualquier cosa. Pero FastAPI todavía hará la documentación de datos, validación, filtrado, etc. con `response_model`. + +/// + +### Prioridad del `response_model` + +Si declaras tanto un tipo de retorno como un `response_model`, el `response_model` tomará prioridad y será utilizado por FastAPI. + +De esta manera puedes añadir anotaciones de tipos correctas a tus funciones incluso cuando estás devolviendo un tipo diferente al modelo de response, para ser utilizado por el editor y herramientas como mypy. Y aún así puedes hacer que FastAPI realice la validación de datos, documentación, etc. usando el `response_model`. + +También puedes usar `response_model=None` para desactivar la creación de un modelo de response para esa *path operation*, podrías necesitar hacerlo si estás añadiendo anotaciones de tipos para cosas que no son campos válidos de Pydantic, verás un ejemplo de eso en una de las secciones a continuación. + +## Devolver los mismos datos de entrada + +Aquí estamos declarando un modelo `UserIn`, contendrá una contraseña en texto plano: + +{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *} + +/// info | Información + +Para usar `EmailStr`, primero instala `email-validator`. + +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, activarlo, y luego instalarlo, por ejemplo: + +```console +$ pip install email-validator +``` + +o con: + +```console +$ pip install "pydantic[email]" +``` + +/// + +Y estamos usando este modelo para declarar nuestra entrada y el mismo modelo para declarar nuestra salida: + +{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *} + +Ahora, cada vez que un navegador esté creando un usuario con una contraseña, la API devolverá la misma contraseña en el response. + +En este caso, podría no ser un problema, porque es el mismo usuario que envía la contraseña. + +Pero si usamos el mismo modelo para otra *path operation*, podríamos estar enviando las contraseñas de nuestros usuarios a cada cliente. + +/// danger | Peligro + +Nunca almacenes la contraseña en texto plano de un usuario ni la envíes en un response como esta, a menos que conozcas todas las advertencias y sepas lo que estás haciendo. + +/// + +## Añadir un modelo de salida + +Podemos en cambio crear un modelo de entrada con la contraseña en texto plano y un modelo de salida sin ella: + +{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *} + +Aquí, aunque nuestra *path operation function* está devolviendo el mismo usuario de entrada que contiene la contraseña: + +{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *} + +...hemos declarado el `response_model` para ser nuestro modelo `UserOut`, que no incluye la contraseña: + +{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *} + +Entonces, **FastAPI** se encargará de filtrar todos los datos que no estén declarados en el modelo de salida (usando Pydantic). + +### `response_model` o Tipo de Retorno + +En este caso, como los dos modelos son diferentes, si anotáramos el tipo de retorno de la función como `UserOut`, el editor y las herramientas se quejarían de que estamos devolviendo un tipo inválido, ya que son clases diferentes. + +Por eso en este ejemplo tenemos que declararlo en el parámetro `response_model`. + +...pero sigue leyendo abajo para ver cómo superar eso. + +## Tipo de Retorno y Filtrado de Datos + +Continuemos con el ejemplo anterior. Queríamos **anotar la función con un tipo**, pero queríamos poder devolver desde la función algo que en realidad incluya **más datos**. + +Queremos que FastAPI continúe **filtrando** los datos usando el modelo de response. Para que, incluso cuando la función devuelva más datos, el response solo incluya los campos declarados en el modelo de response. + +En el ejemplo anterior, debido a que las clases eran diferentes, tuvimos que usar el parámetro `response_model`. Pero eso también significa que no obtenemos el soporte del editor y las herramientas verificando el tipo de retorno de la función. + +Pero en la mayoría de los casos en los que necesitamos hacer algo como esto, queremos que el modelo solo **filtre/elimine** algunos de los datos como en este ejemplo. + +Y en esos casos, podemos usar clases y herencia para aprovechar las **anotaciones de tipos** de funciones para obtener mejor soporte en el editor y herramientas, y aún así obtener el **filtrado de datos** de FastAPI. + +{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *} + +Con esto, obtenemos soporte de las herramientas, de los editores y mypy ya que este código es correcto en términos de tipos, pero también obtenemos el filtrado de datos de FastAPI. + +¿Cómo funciona esto? Vamos a echarle un vistazo. 🤓 + +### Anotaciones de Tipos y Herramientas + +Primero vamos a ver cómo los editores, mypy y otras herramientas verían esto. + +`BaseUser` tiene los campos base. Luego `UserIn` hereda de `BaseUser` y añade el campo `password`, por lo que incluirá todos los campos de ambos modelos. + +Anotamos el tipo de retorno de la función como `BaseUser`, pero en realidad estamos devolviendo una instancia de `UserIn`. + +El editor, mypy y otras herramientas no se quejarán de esto porque, en términos de tipificación, `UserIn` es una subclase de `BaseUser`, lo que significa que es un tipo *válido* cuando se espera algo que es un `BaseUser`. + +### Filtrado de Datos en FastAPI + +Ahora, para FastAPI, verá el tipo de retorno y se asegurará de que lo que devuelves incluya **solo** los campos que están declarados en el tipo. + +FastAPI realiza varias cosas internamente con Pydantic para asegurarse de que esas mismas reglas de herencia de clases no se utilicen para el filtrado de datos devueltos, de lo contrario, podrías terminar devolviendo muchos más datos de los que esperabas. + +De esta manera, puedes obtener lo mejor de ambos mundos: anotaciones de tipos con **soporte de herramientas** y **filtrado de datos**. + +## Verlo en la documentación + +Cuando veas la documentación automática, puedes verificar que el modelo de entrada y el modelo de salida tendrán cada uno su propio JSON Schema: + + + +Y ambos modelos se utilizarán para la documentación interactiva de la API: + + + +## Otras Anotaciones de Tipos de Retorno + +Podría haber casos en los que devuelvas algo que no es un campo válido de Pydantic y lo anotes en la función, solo para obtener el soporte proporcionado por las herramientas (el editor, mypy, etc). + +### Devolver un Response Directamente + +El caso más común sería [devolver un Response directamente como se explica más adelante en la documentación avanzada](../advanced/response-directly.md){.internal-link target=_blank}. + +{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *} + +Este caso simple es manejado automáticamente por FastAPI porque la anotación del tipo de retorno es la clase (o una subclase de) `Response`. + +Y las herramientas también estarán felices porque tanto `RedirectResponse` como `JSONResponse` son subclases de `Response`, por lo que la anotación del tipo es correcta. + +### Anotar una Subclase de Response + +También puedes usar una subclase de `Response` en la anotación del tipo: + +{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *} + +Esto también funcionará porque `RedirectResponse` es una subclase de `Response`, y FastAPI manejará automáticamente este caso simple. + +### Anotaciones de Tipos de Retorno Inválidas + +Pero cuando devuelves algún otro objeto arbitrario que no es un tipo válido de Pydantic (por ejemplo, un objeto de base de datos) y lo anotas así en la función, FastAPI intentará crear un modelo de response de Pydantic a partir de esa anotación de tipo, y fallará. + +Lo mismo sucedería si tuvieras algo como un union entre diferentes tipos donde uno o más de ellos no son tipos válidos de Pydantic, por ejemplo esto fallaría 💥: + +{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *} + +...esto falla porque la anotación de tipo no es un tipo de Pydantic y no es solo una sola clase `Response` o subclase, es una unión (cualquiera de los dos) entre una `Response` y un `dict`. + +### Desactivar el Modelo de Response + +Continuando con el ejemplo anterior, puede que no quieras tener la validación de datos por defecto, documentación, filtrado, etc. que realiza FastAPI. + +Pero puedes querer mantener la anotación del tipo de retorno en la función para obtener el soporte de herramientas como editores y verificadores de tipos (por ejemplo, mypy). + +En este caso, puedes desactivar la generación del modelo de response configurando `response_model=None`: + +{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *} + +Esto hará que FastAPI omita la generación del modelo de response y de esa manera puedes tener cualquier anotación de tipo de retorno que necesites sin que afecte a tu aplicación FastAPI. 🤓 + +## Parámetros de codificación del Modelo de Response + +Tu modelo de response podría tener valores por defecto, como: + +{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *} + +* `description: Union[str, None] = None` (o `str | None = None` en Python 3.10) tiene un valor por defecto de `None`. +* `tax: float = 10.5` tiene un valor por defecto de `10.5`. +* `tags: List[str] = []` tiene un valor por defecto de una lista vacía: `[]`. + +pero podrías querer omitirlos del resultado si no fueron en realidad almacenados. + +Por ejemplo, si tienes modelos con muchos atributos opcionales en una base de datos NoSQL, pero no quieres enviar responses JSON muy largos llenos de valores por defecto. + +### Usa el parámetro `response_model_exclude_unset` + +Puedes configurar el parámetro del decorador de path operation `response_model_exclude_unset=True`: + +{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *} + +y esos valores por defecto no serán incluidos en el response, solo los valores realmente establecidos. + +Entonces, si envías un request a esa *path operation* para el ítem con ID `foo`, el response (no incluyendo valores por defecto) será: + +```JSON +{ + "name": "Foo", + "price": 50.2 +} +``` + +/// info | Información + +En Pydantic v1 el método se llamaba `.dict()`, fue deprecado (pero aún soportado) en Pydantic v2, y renombrado a `.model_dump()`. + +Los ejemplos aquí usan `.dict()` para compatibilidad con Pydantic v1, pero deberías usar `.model_dump()` en su lugar si puedes usar Pydantic v2. + +/// + +/// info | Información + +FastAPI usa el método `.dict()` del modelo de Pydantic con su parámetro `exclude_unset` para lograr esto. + +/// + +/// info | Información + +También puedes usar: + +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` + +como se describe en la documentación de Pydantic para `exclude_defaults` y `exclude_none`. + +/// + +#### Datos con valores para campos con valores por defecto + +Pero si tus datos tienen valores para los campos del modelo con valores por defecto, como el artículo con ID `bar`: + +```Python hl_lines="3 5" +{ + "name": "Bar", + "description": "The bartenders", + "price": 62, + "tax": 20.2 +} +``` + +serán incluidos en el response. + +#### Datos con los mismos valores que los valores por defecto + +Si los datos tienen los mismos valores que los valores por defecto, como el artículo con ID `baz`: + +```Python hl_lines="3 5-6" +{ + "name": "Baz", + "description": None, + "price": 50.2, + "tax": 10.5, + "tags": [] +} +``` + +FastAPI es lo suficientemente inteligente (de hecho, Pydantic es lo suficientemente inteligente) para darse cuenta de que, a pesar de que `description`, `tax` y `tags` tienen los mismos valores que los valores por defecto, fueron establecidos explícitamente (en lugar de tomados de los valores por defecto). + +Por lo tanto, se incluirán en el response JSON. + +/// tip | Consejo + +Ten en cuenta que los valores por defecto pueden ser cualquier cosa, no solo `None`. + +Pueden ser una lista (`[]`), un `float` de `10.5`, etc. + +/// + +### `response_model_include` y `response_model_exclude` + +También puedes usar los parámetros del decorador de path operation `response_model_include` y `response_model_exclude`. + +Aceptan un `set` de `str` con el nombre de los atributos a incluir (omitiendo el resto) o excluir (incluyendo el resto). + +Esto se puede usar como un atajo rápido si solo tienes un modelo de Pydantic y quieres eliminar algunos datos de la salida. + +/// tip | Consejo + +Pero todavía se recomienda usar las ideas anteriores, usando múltiples clases, en lugar de estos parámetros. + +Esto se debe a que el JSON Schema generado en el OpenAPI de tu aplicación (y la documentación) aún será el del modelo completo, incluso si usas `response_model_include` o `response_model_exclude` para omitir algunos atributos. + +Esto también se aplica a `response_model_by_alias` que funciona de manera similar. + +/// + +{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *} + +/// tip | Consejo + +La sintaxis `{"name", "description"}` crea un `set` con esos dos valores. + +Es equivalente a `set(["name", "description"])`. + +/// + +#### Usar `list`s en lugar de `set`s + +Si olvidas usar un `set` y usas un `list` o `tuple` en su lugar, FastAPI todavía lo convertirá a un `set` y funcionará correctamente: + +{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *} + +## Resumen + +Usa el parámetro `response_model` del *decorador de path operation* para definir modelos de response y especialmente para asegurarte de que los datos privados sean filtrados. + +Usa `response_model_exclude_unset` para devolver solo los valores establecidos explícitamente. diff --git a/docs/es/docs/tutorial/response-status-code.md b/docs/es/docs/tutorial/response-status-code.md new file mode 100644 index 000000000..92df1f4cc --- /dev/null +++ b/docs/es/docs/tutorial/response-status-code.md @@ -0,0 +1,101 @@ +# Código de Estado del Response + +De la misma manera que puedes especificar un modelo de response, también puedes declarar el código de estado HTTP usado para el response con el parámetro `status_code` en cualquiera de las *path operations*: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* etc. + +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} + +/// note | Nota + +Observa que `status_code` es un parámetro del método "decorador" (`get`, `post`, etc). No de tu *path operation function*, como todos los parámetros y body. + +/// + +El parámetro `status_code` recibe un número con el código de estado HTTP. + +/// info | Información + +`status_code` también puede recibir un `IntEnum`, como por ejemplo el `http.HTTPStatus` de Python. + +/// + +Esto hará: + +* Devolver ese código de estado en el response. +* Documentarlo como tal en el esquema de OpenAPI (y por lo tanto, en las interfaces de usuario): + + + +/// note | Nota + +Algunos códigos de response (ver la siguiente sección) indican que el response no tiene un body. + +FastAPI sabe esto, y producirá documentación OpenAPI que establece que no hay un response body. + +/// + +## Acerca de los códigos de estado HTTP + +/// note | Nota + +Si ya sabes qué son los códigos de estado HTTP, salta a la siguiente sección. + +/// + +En HTTP, envías un código de estado numérico de 3 dígitos como parte del response. + +Estos códigos de estado tienen un nombre asociado para reconocerlos, pero la parte importante es el número. + +En breve: + +* `100` y superiores son para "Información". Rara vez los usas directamente. Los responses con estos códigos de estado no pueden tener un body. +* **`200`** y superiores son para responses "Exitosos". Estos son los que usarías más. + * `200` es el código de estado por defecto, lo que significa que todo estaba "OK". + * Otro ejemplo sería `201`, "Created". Comúnmente se usa después de crear un nuevo registro en la base de datos. + * Un caso especial es `204`, "No Content". Este response se usa cuando no hay contenido para devolver al cliente, por lo tanto, el response no debe tener un body. +* **`300`** y superiores son para "Redirección". Los responses con estos códigos de estado pueden o no tener un body, excepto `304`, "Not Modified", que no debe tener uno. +* **`400`** y superiores son para responses de "Error del Cliente". Este es el segundo tipo que probablemente más usarías. + * Un ejemplo es `404`, para un response "Not Found". + * Para errores genéricos del cliente, puedes usar simplemente `400`. +* `500` y superiores son para errores del servidor. Casi nunca los usas directamente. Cuando algo sale mal en alguna parte de tu código de aplicación, o del servidor, automáticamente devolverá uno de estos códigos de estado. + +/// tip | Consejo + +Para saber más sobre cada código de estado y qué código es para qué, revisa la documentación de MDN sobre códigos de estado HTTP. + +/// + +## Atajo para recordar los nombres + +Veamos de nuevo el ejemplo anterior: + +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} + +`201` es el código de estado para "Created". + +Pero no tienes que memorizar lo que significa cada uno de estos códigos. + +Puedes usar las variables de conveniencia de `fastapi.status`. + +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} + +Son solo una conveniencia, mantienen el mismo número, pero de esa manera puedes usar el autocompletado del editor para encontrarlos: + + + +/// note | Nota Técnica + +También podrías usar `from starlette import status`. + +**FastAPI** proporciona el mismo `starlette.status` como `fastapi.status` solo como una conveniencia para ti, el desarrollador. Pero proviene directamente de Starlette. + +/// + +## Cambiando el valor por defecto + +Más adelante, en la [Guía de Usuario Avanzada](../advanced/response-change-status-code.md){.internal-link target=_blank}, verás cómo devolver un código de estado diferente al valor por defecto que estás declarando aquí. diff --git a/docs/es/docs/tutorial/schema-extra-example.md b/docs/es/docs/tutorial/schema-extra-example.md new file mode 100644 index 000000000..645060d71 --- /dev/null +++ b/docs/es/docs/tutorial/schema-extra-example.md @@ -0,0 +1,224 @@ +# Declarar Ejemplos de Request + +Puedes declarar ejemplos de los datos que tu aplicación puede recibir. + +Aquí tienes varias formas de hacerlo. + +## Datos extra de JSON Schema en modelos de Pydantic + +Puedes declarar `examples` para un modelo de Pydantic que se añadirá al JSON Schema generado. + +//// tab | Pydantic v2 + +{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *} + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/schema_extra_example/tutorial001_pv1_py310.py hl[13:23] *} + +//// + +Esa información extra se añadirá tal cual al **JSON Schema** generado para ese modelo, y se usará en la documentación de la API. + +//// tab | Pydantic v2 + +En Pydantic versión 2, usarías el atributo `model_config`, que toma un `dict` como se describe en la documentación de Pydantic: Configuración. + +Puedes establecer `"json_schema_extra"` con un `dict` que contenga cualquier dato adicional que desees que aparezca en el JSON Schema generado, incluyendo `examples`. + +//// + +//// tab | Pydantic v1 + +En Pydantic versión 1, usarías una clase interna `Config` y `schema_extra`, como se describe en la documentación de Pydantic: Personalización de Esquema. + +Puedes establecer `schema_extra` con un `dict` que contenga cualquier dato adicional que desees que aparezca en el JSON Schema generado, incluyendo `examples`. + +//// + +/// tip | Consejo + +Podrías usar la misma técnica para extender el JSON Schema y añadir tu propia información extra personalizada. + +Por ejemplo, podrías usarlo para añadir metadatos para una interfaz de usuario frontend, etc. + +/// + +/// info | Información + +OpenAPI 3.1.0 (usado desde FastAPI 0.99.0) añadió soporte para `examples`, que es parte del estándar de **JSON Schema**. + +Antes de eso, solo soportaba la palabra clave `example` con un solo ejemplo. Eso aún es soportado por OpenAPI 3.1.0, pero está obsoleto y no es parte del estándar de JSON Schema. Así que se recomienda migrar de `example` a `examples`. 🤓 + +Puedes leer más al final de esta página. + +/// + +## Argumentos adicionales en `Field` + +Cuando usas `Field()` con modelos de Pydantic, también puedes declarar `examples` adicionales: + +{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *} + +## `examples` en JSON Schema - OpenAPI + +Cuando usas cualquiera de: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` + +también puedes declarar un grupo de `examples` con información adicional que se añadirá a sus **JSON Schemas** dentro de **OpenAPI**. + +### `Body` con `examples` + +Aquí pasamos `examples` que contiene un ejemplo de los datos esperados en `Body()`: + +{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *} + +### Ejemplo en la interfaz de documentación + +Con cualquiera de los métodos anteriores se vería así en los `/docs`: + + + +### `Body` con múltiples `examples` + +Por supuesto, también puedes pasar múltiples `examples`: + +{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *} + +Cuando haces esto, los ejemplos serán parte del **JSON Schema** interno para esos datos de body. + +Sin embargo, al momento de escribir esto, Swagger UI, la herramienta encargada de mostrar la interfaz de documentación, no soporta mostrar múltiples ejemplos para los datos en **JSON Schema**. Pero lee más abajo para una solución alternativa. + +### `examples` específicos de OpenAPI + +Desde antes de que **JSON Schema** soportara `examples`, OpenAPI tenía soporte para un campo diferente también llamado `examples`. + +Estos `examples` específicos de **OpenAPI** van en otra sección en la especificación de OpenAPI. Van en los **detalles para cada *path operation***, no dentro de cada JSON Schema. + +Y Swagger UI ha soportado este campo particular de `examples` por un tiempo. Así que, puedes usarlo para **mostrar** diferentes **ejemplos en la interfaz de documentación**. + +La forma de este campo específico de OpenAPI `examples` es un `dict` con **múltiples ejemplos** (en lugar de una `list`), cada uno con información adicional que también se añadirá a **OpenAPI**. + +Esto no va dentro de cada JSON Schema contenido en OpenAPI, esto va afuera, directamente en la *path operation*. + +### Usando el Parámetro `openapi_examples` + +Puedes declarar los `examples` específicos de OpenAPI en FastAPI con el parámetro `openapi_examples` para: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` + +Las claves del `dict` identifican cada ejemplo, y cada valor es otro `dict`. + +Cada `dict` específico del ejemplo en los `examples` puede contener: + +* `summary`: Descripción corta del ejemplo. +* `description`: Una descripción larga que puede contener texto Markdown. +* `value`: Este es el ejemplo real mostrado, e.g. un `dict`. +* `externalValue`: alternativa a `value`, una URL que apunta al ejemplo. Aunque esto puede no ser soportado por tantas herramientas como `value`. + +Puedes usarlo así: + +{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *} + +### Ejemplos de OpenAPI en la Interfaz de Documentación + +Con `openapi_examples` añadido a `Body()`, los `/docs` se verían así: + + + +## Detalles Técnicos + +/// tip | Consejo + +Si ya estás usando la versión **0.99.0 o superior** de **FastAPI**, probablemente puedes **omitir** estos detalles. + +Son más relevantes para versiones más antiguas, antes de que OpenAPI 3.1.0 estuviera disponible. + +Puedes considerar esto una breve lección de **historia** de OpenAPI y JSON Schema. 🤓 + +/// + +/// warning | Advertencia + +Estos son detalles muy técnicos sobre los estándares **JSON Schema** y **OpenAPI**. + +Si las ideas anteriores ya funcionan para ti, eso podría ser suficiente, y probablemente no necesites estos detalles, siéntete libre de omitirlos. + +/// + +Antes de OpenAPI 3.1.0, OpenAPI usaba una versión más antigua y modificada de **JSON Schema**. + +JSON Schema no tenía `examples`, así que OpenAPI añadió su propio campo `example` a su versión modificada. + +OpenAPI también añadió los campos `example` y `examples` a otras partes de la especificación: + +* `Parameter Object` (en la especificación) que era usado por FastAPI: + * `Path()` + * `Query()` + * `Header()` + * `Cookie()` +* `Request Body Object`, en el campo `content`, sobre el `Media Type Object` (en la especificación) que era usado por FastAPI: + * `Body()` + * `File()` + * `Form()` + +/// info | Información + +Este viejo parámetro `examples` específico de OpenAPI ahora es `openapi_examples` desde FastAPI `0.103.0`. + +/// + +### Campo `examples` de JSON Schema + +Pero luego JSON Schema añadió un campo `examples` a una nueva versión de la especificación. + +Y entonces el nuevo OpenAPI 3.1.0 se basó en la última versión (JSON Schema 2020-12) que incluía este nuevo campo `examples`. + +Y ahora este nuevo campo `examples` tiene precedencia sobre el viejo campo único (y personalizado) `example`, que ahora está obsoleto. + +Este nuevo campo `examples` en JSON Schema es **solo una `list`** de ejemplos, no un dict con metadatos adicionales como en los otros lugares en OpenAPI (descritos arriba). + +/// info | Información + +Incluso después de que OpenAPI 3.1.0 fue lanzado con esta nueva integración más sencilla con JSON Schema, por un tiempo, Swagger UI, la herramienta que proporciona la documentación automática, no soportaba OpenAPI 3.1.0 (lo hace desde la versión 5.0.0 🎉). + +Debido a eso, las versiones de FastAPI anteriores a 0.99.0 todavía usaban versiones de OpenAPI menores a 3.1.0. + +/// + +### `examples` de Pydantic y FastAPI + +Cuando añades `examples` dentro de un modelo de Pydantic, usando `schema_extra` o `Field(examples=["algo"])`, ese ejemplo se añade al **JSON Schema** para ese modelo de Pydantic. + +Y ese **JSON Schema** del modelo de Pydantic se incluye en el **OpenAPI** de tu API, y luego se usa en la interfaz de documentación. + +En las versiones de FastAPI antes de 0.99.0 (0.99.0 y superior usan el nuevo OpenAPI 3.1.0) cuando usabas `example` o `examples` con cualquiera de las otras utilidades (`Query()`, `Body()`, etc.) esos ejemplos no se añadían al JSON Schema que describe esos datos (ni siquiera a la propia versión de JSON Schema de OpenAPI), se añadían directamente a la declaración de la *path operation* en OpenAPI (fuera de las partes de OpenAPI que usan JSON Schema). + +Pero ahora que FastAPI 0.99.0 y superiores usa OpenAPI 3.1.0, que usa JSON Schema 2020-12, y Swagger UI 5.0.0 y superiores, todo es más consistente y los ejemplos se incluyen en JSON Schema. + +### Swagger UI y `examples` específicos de OpenAPI + +Ahora, como Swagger UI no soportaba múltiples ejemplos de JSON Schema (a fecha de 2023-08-26), los usuarios no tenían una forma de mostrar múltiples ejemplos en los documentos. + +Para resolver eso, FastAPI `0.103.0` **añadió soporte** para declarar el mismo viejo campo **específico de OpenAPI** `examples` con el nuevo parámetro `openapi_examples`. 🤓 + +### Resumen + +Solía decir que no me gustaba mucho la historia... y mírame ahora dando lecciones de "historia tecnológica". 😅 + +En resumen, **actualiza a FastAPI 0.99.0 o superior**, y las cosas son mucho **más simples, consistentes e intuitivas**, y no necesitas conocer todos estos detalles históricos. 😎 diff --git a/docs/es/docs/tutorial/security/first-steps.md b/docs/es/docs/tutorial/security/first-steps.md new file mode 100644 index 000000000..5dbbab02a --- /dev/null +++ b/docs/es/docs/tutorial/security/first-steps.md @@ -0,0 +1,203 @@ +# Seguridad - Primeros pasos + +Imaginemos que tienes tu API de **backend** en algún dominio. + +Y tienes un **frontend** en otro dominio o en un path diferente del mismo dominio (o en una aplicación móvil). + +Y quieres tener una forma para que el frontend se autentique con el backend, usando un **username** y **password**. + +Podemos usar **OAuth2** para construir eso con **FastAPI**. + +Pero vamos a ahorrarte el tiempo de leer la larga especificación completa solo para encontrar esos pequeños fragmentos de información que necesitas. + +Usemos las herramientas proporcionadas por **FastAPI** para manejar la seguridad. + +## Cómo se ve + +Primero solo usemos el código y veamos cómo funciona, y luego volveremos para entender qué está sucediendo. + +## Crea `main.py` + +Copia el ejemplo en un archivo `main.py`: + +{* ../../docs_src/security/tutorial001_an_py39.py *} + +## Ejecútalo + +/// info | Información + +El paquete `python-multipart` se instala automáticamente con **FastAPI** cuando ejecutas el comando `pip install "fastapi[standard]"`. + +Sin embargo, si usas el comando `pip install fastapi`, el paquete `python-multipart` no se incluye por defecto. + +Para instalarlo manualmente, asegúrate de crear un [entorno virtual](../../virtual-environments.md){.internal-link target=_blank}, activarlo, y luego instalarlo con: + +```console +$ pip install python-multipart +``` + +Esto se debe a que **OAuth2** utiliza "form data" para enviar el `username` y `password`. + +/// + +Ejecuta el ejemplo con: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +## Revisa + +Ve a la documentación interactiva en: http://127.0.0.1:8000/docs. + +Verás algo así: + + + +/// check | ¡Botón de autorización! + +Ya tienes un nuevo y brillante botón de "Authorize". + +Y tu *path operation* tiene un pequeño candado en la esquina superior derecha que puedes pulsar. + +/// + +Y si lo haces, tendrás un pequeño formulario de autorización para escribir un `username` y `password` (y otros campos opcionales): + + + +/// note | Nota + +No importa lo que escribas en el formulario, aún no funcionará. Pero llegaremos allí. + +/// + +Esto por supuesto no es el frontend para los usuarios finales, pero es una gran herramienta automática para documentar interactivamente toda tu API. + +Puede ser utilizada por el equipo de frontend (que también puedes ser tú mismo). + +Puede ser utilizada por aplicaciones y sistemas de terceros. + +Y también puede ser utilizada por ti mismo, para depurar, revisar y probar la misma aplicación. + +## El flujo `password` + +Ahora retrocedamos un poco y entendamos qué es todo eso. + +El "flujo" `password` es una de las formas ("flujos") definidas en OAuth2, para manejar la seguridad y la autenticación. + +OAuth2 fue diseñado para que el backend o la API pudieran ser independientes del servidor que autentica al usuario. + +Pero en este caso, la misma aplicación de **FastAPI** manejará la API y la autenticación. + +Así que, revisémoslo desde ese punto de vista simplificado: + +* El usuario escribe el `username` y `password` en el frontend, y presiona `Enter`. +* El frontend (ejecutándose en el navegador del usuario) envía ese `username` y `password` a una URL específica en nuestra API (declarada con `tokenUrl="token"`). +* La API verifica ese `username` y `password`, y responde con un "token" (no hemos implementado nada de esto aún). + * Un "token" es solo un string con algún contenido que podemos usar luego para verificar a este usuario. + * Normalmente, un token se establece para que expire después de algún tiempo. + * Así que, el usuario tendrá que volver a iniciar sesión más adelante. + * Y si el token es robado, el riesgo es menor. No es como una llave permanente que funcionará para siempre (en la mayoría de los casos). +* El frontend almacena temporalmente ese token en algún lugar. +* El usuario hace clic en el frontend para ir a otra sección de la aplicación web frontend. +* El frontend necesita obtener más datos de la API. + * Pero necesita autenticación para ese endpoint específico. + * Así que, para autenticarse con nuestra API, envía un `header` `Authorization` con un valor de `Bearer ` más el token. + * Si el token contiene `foobar`, el contenido del `header` `Authorization` sería: `Bearer foobar`. + +## `OAuth2PasswordBearer` de **FastAPI** + +**FastAPI** proporciona varias herramientas, en diferentes niveles de abstracción, para implementar estas funcionalidades de seguridad. + +En este ejemplo vamos a usar **OAuth2**, con el flujo **Password**, usando un token **Bearer**. Hacemos eso utilizando la clase `OAuth2PasswordBearer`. + +/// info | Información + +Un token "bearer" no es la única opción. + +Pero es la mejor para nuestro caso de uso. + +Y podría ser la mejor para la mayoría de los casos de uso, a menos que seas un experto en OAuth2 y sepas exactamente por qué hay otra opción que se adapta mejor a tus necesidades. + +En ese caso, **FastAPI** también te proporciona las herramientas para construirlo. + +/// + +Cuando creamos una instance de la clase `OAuth2PasswordBearer` pasamos el parámetro `tokenUrl`. Este parámetro contiene la URL que el cliente (el frontend corriendo en el navegador del usuario) usará para enviar el `username` y `password` a fin de obtener un token. + +{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *} + +/// tip | Consejo + +Aquí `tokenUrl="token"` se refiere a una URL relativa `token` que aún no hemos creado. Como es una URL relativa, es equivalente a `./token`. + +Porque estamos usando una URL relativa, si tu API estuviera ubicada en `https://example.com/`, entonces se referiría a `https://example.com/token`. Pero si tu API estuviera ubicada en `https://example.com/api/v1/`, entonces se referiría a `https://example.com/api/v1/token`. + +Usar una URL relativa es importante para asegurarse de que tu aplicación siga funcionando incluso en un caso de uso avanzado como [Detrás de un Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. + +/// + +Este parámetro no crea ese endpoint / *path operation*, pero declara que la URL `/token` será la que el cliente deberá usar para obtener el token. Esa información se usa en OpenAPI, y luego en los sistemas de documentación interactiva del API. + +Pronto también crearemos la verdadera *path operation*. + +/// info | Información + +Si eres un "Pythonista" muy estricto, tal vez no te guste el estilo del nombre del parámetro `tokenUrl` en lugar de `token_url`. + +Eso es porque está usando el mismo nombre que en la especificación de OpenAPI. Para que si necesitas investigar más sobre cualquiera de estos esquemas de seguridad, puedas simplemente copiarlo y pegarlo para encontrar más información al respecto. + +/// + +La variable `oauth2_scheme` es una instance de `OAuth2PasswordBearer`, pero también es un "callable". + +Podría ser llamada como: + +```Python +oauth2_scheme(some, parameters) +``` + +Así que, puede usarse con `Depends`. + +### Úsalo + +Ahora puedes pasar ese `oauth2_scheme` en una dependencia con `Depends`. + +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} + +Esta dependencia proporcionará un `str` que se asigna al parámetro `token` de la *path operation function*. + +**FastAPI** sabrá que puede usar esta dependencia para definir un "security scheme" en el esquema OpenAPI (y en los docs automáticos del API). + +/// info | Detalles técnicos + +**FastAPI** sabrá que puede usar la clase `OAuth2PasswordBearer` (declarada en una dependencia) para definir el esquema de seguridad en OpenAPI porque hereda de `fastapi.security.oauth2.OAuth2`, que a su vez hereda de `fastapi.security.base.SecurityBase`. + +Todas las utilidades de seguridad que se integran con OpenAPI (y los docs automáticos del API) heredan de `SecurityBase`, así es como **FastAPI** puede saber cómo integrarlas en OpenAPI. + +/// + +## Lo que hace + +Irá y buscará en el request ese header `Authorization`, verificará si el valor es `Bearer ` más algún token, y devolverá el token como un `str`. + +Si no ve un header `Authorization`, o el valor no tiene un token `Bearer `, responderá directamente con un error de código de estado 401 (`UNAUTHORIZED`). + +Ni siquiera tienes que verificar si el token existe para devolver un error. Puedes estar seguro de que si tu función se ejecuta, tendrá un `str` en ese token. + +Puedes probarlo ya en los docs interactivos: + + + +Todavía no estamos verificando la validez del token, pero ya es un comienzo. + +## Resumen + +Así que, en solo 3 o 4 líneas adicionales, ya tienes alguna forma primitiva de seguridad. diff --git a/docs/es/docs/tutorial/security/get-current-user.md b/docs/es/docs/tutorial/security/get-current-user.md new file mode 100644 index 000000000..249a70c18 --- /dev/null +++ b/docs/es/docs/tutorial/security/get-current-user.md @@ -0,0 +1,103 @@ +# Obtener Usuario Actual + +En el capítulo anterior, el sistema de seguridad (que se basa en el sistema de inyección de dependencias) le estaba dando a la *path operation function* un `token` como un `str`: + +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} + +Pero eso aún no es tan útil. Vamos a hacer que nos dé el usuario actual. + +## Crear un modelo de usuario + +Primero, vamos a crear un modelo de usuario con Pydantic. + +De la misma manera que usamos Pydantic para declarar cuerpos, podemos usarlo en cualquier otra parte: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *} + +## Crear una dependencia `get_current_user` + +Vamos a crear una dependencia `get_current_user`. + +¿Recuerdas que las dependencias pueden tener sub-dependencias? + +`get_current_user` tendrá una dependencia con el mismo `oauth2_scheme` que creamos antes. + +De la misma manera que estábamos haciendo antes en la *path operation* directamente, nuestra nueva dependencia `get_current_user` recibirá un `token` como un `str` de la sub-dependencia `oauth2_scheme`: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *} + +## Obtener el usuario + +`get_current_user` usará una función de utilidad (falsa) que creamos, que toma un token como un `str` y devuelve nuestro modelo de Pydantic `User`: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *} + +## Inyectar al usuario actual + +Entonces ahora podemos usar el mismo `Depends` con nuestro `get_current_user` en la *path operation*: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *} + +Ten en cuenta que declaramos el tipo de `current_user` como el modelo de Pydantic `User`. + +Esto nos ayudará dentro de la función con todo el autocompletado y chequeo de tipos. + +/// tip | Consejo + +Tal vez recuerdes que los cuerpos de request también se declaran con modelos de Pydantic. + +Aquí **FastAPI** no se confundirá porque estás usando `Depends`. + +/// + +/// check | Revisa + +El modo en que este sistema de dependencias está diseñado nos permite tener diferentes dependencias (diferentes "dependables") que todas devuelven un modelo `User`. + +No estamos restringidos a tener solo una dependencia que pueda devolver ese tipo de datos. + +/// + +## Otros modelos + +Ahora puedes obtener el usuario actual directamente en las *path operation functions* y manejar los mecanismos de seguridad a nivel de **Dependency Injection**, usando `Depends`. + +Y puedes usar cualquier modelo o datos para los requisitos de seguridad (en este caso, un modelo de Pydantic `User`). + +Pero no estás limitado a usar algún modelo de datos, clase o tipo específico. + +¿Quieres tener un `id` y `email` y no tener un `username` en tu modelo? Claro. Puedes usar estas mismas herramientas. + +¿Quieres solo tener un `str`? ¿O solo un `dict`? ¿O un instance de clase modelo de base de datos directamente? Todo funciona de la misma manera. + +¿En realidad no tienes usuarios que inicien sesión en tu aplicación sino robots, bots u otros sistemas, que solo tienen un token de acceso? Una vez más, todo funciona igual. + +Usa cualquier tipo de modelo, cualquier tipo de clase, cualquier tipo de base de datos que necesites para tu aplicación. **FastAPI** te cubre con el sistema de inyección de dependencias. + +## Tamaño del código + +Este ejemplo podría parecer extenso. Ten en cuenta que estamos mezclando seguridad, modelos de datos, funciones de utilidad y *path operations* en el mismo archivo. + +Pero aquí está el punto clave. + +El tema de seguridad e inyección de dependencias se escribe una vez. + +Y puedes hacerlo tan complejo como desees. Y aún así, tenerlo escrito solo una vez, en un solo lugar. Con toda la flexibilidad. + +Pero puedes tener miles de endpoints (*path operations*) usando el mismo sistema de seguridad. + +Y todos ellos (o cualquier porción de ellos que quieras) pueden aprovechar la reutilización de estas dependencias o cualquier otra dependencia que crees. + +Y todas estas miles de *path operations* pueden ser tan pequeñas como 3 líneas: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *} + +## Resumen + +Ahora puedes obtener el usuario actual directamente en tu *path operation function*. + +Ya estamos a mitad de camino. + +Solo necesitamos agregar una *path operation* para que el usuario/cliente envíe realmente el `username` y `password`. + +Eso es lo que viene a continuación. diff --git a/docs/es/docs/tutorial/security/index.md b/docs/es/docs/tutorial/security/index.md new file mode 100644 index 000000000..12e39fdaa --- /dev/null +++ b/docs/es/docs/tutorial/security/index.md @@ -0,0 +1,105 @@ +# Seguridad + +Hay muchas formas de manejar la seguridad, autenticación y autorización. + +Y normalmente es un tema complejo y "difícil". + +En muchos frameworks y sistemas, solo manejar la seguridad y autenticación requiere una gran cantidad de esfuerzo y código (en muchos casos puede ser el 50% o más de todo el código escrito). + +**FastAPI** proporciona varias herramientas para ayudarte a manejar la **Seguridad** de manera fácil, rápida y estándar, sin tener que estudiar y aprender todas las especificaciones de seguridad. + +Pero primero, vamos a revisar algunos pequeños conceptos. + +## ¿Con prisa? + +Si no te importan ninguno de estos términos y solo necesitas agregar seguridad con autenticación basada en nombre de usuario y contraseña *ahora mismo*, salta a los siguientes capítulos. + +## OAuth2 + +OAuth2 es una especificación que define varias maneras de manejar la autenticación y autorización. + +Es una especificación bastante extensa y cubre varios casos de uso complejos. + +Incluye formas de autenticarse usando un "tercero". + +Eso es lo que todos los sistemas con "iniciar sesión con Facebook, Google, Twitter, GitHub" utilizan internamente. + +### OAuth 1 + +Hubo un OAuth 1, que es muy diferente de OAuth2, y más complejo, ya que incluía especificaciones directas sobre cómo encriptar la comunicación. + +No es muy popular o usado hoy en día. + +OAuth2 no especifica cómo encriptar la comunicación, espera que tengas tu aplicación servida con HTTPS. + +/// tip | Consejo + +En la sección sobre **deployment** verás cómo configurar HTTPS de forma gratuita, usando Traefik y Let's Encrypt. + +/// + +## OpenID Connect + +OpenID Connect es otra especificación, basada en **OAuth2**. + +Solo extiende OAuth2 especificando algunas cosas que son relativamente ambiguas en OAuth2, para intentar hacerla más interoperable. + +Por ejemplo, el login de Google usa OpenID Connect (que internamente usa OAuth2). + +Pero el login de Facebook no soporta OpenID Connect. Tiene su propia versión de OAuth2. + +### OpenID (no "OpenID Connect") + +Hubo también una especificación "OpenID". Que intentaba resolver lo mismo que **OpenID Connect**, pero no estaba basada en OAuth2. + +Entonces, era un sistema completo adicional. + +No es muy popular o usado hoy en día. + +## OpenAPI + +OpenAPI (anteriormente conocido como Swagger) es la especificación abierta para construir APIs (ahora parte de la Linux Foundation). + +**FastAPI** se basa en **OpenAPI**. + +Eso es lo que hace posible tener múltiples interfaces de documentación interactiva automática, generación de código, etc. + +OpenAPI tiene una forma de definir múltiples "esquemas" de seguridad. + +Al usarlos, puedes aprovechar todas estas herramientas basadas en estándares, incluidos estos sistemas de documentación interactiva. + +OpenAPI define los siguientes esquemas de seguridad: + +* `apiKey`: una clave específica de la aplicación que puede provenir de: + * Un parámetro de query. + * Un header. + * Una cookie. +* `http`: sistemas de autenticación HTTP estándar, incluyendo: + * `bearer`: un header `Authorization` con un valor de `Bearer ` más un token. Esto se hereda de OAuth2. + * Autenticación básica HTTP. + * Digest HTTP, etc. +* `oauth2`: todas las formas de OAuth2 para manejar la seguridad (llamadas "flujos"). + * Varios de estos flujos son apropiados para construir un proveedor de autenticación OAuth 2.0 (como Google, Facebook, Twitter, GitHub, etc.): + * `implicit` + * `clientCredentials` + * `authorizationCode` + * Pero hay un "flujo" específico que puede usarse perfectamente para manejar la autenticación directamente en la misma aplicación: + * `password`: algunos de los próximos capítulos cubrirán ejemplos de esto. +* `openIdConnect`: tiene una forma de definir cómo descubrir automáticamente los datos de autenticación OAuth2. + * Este descubrimiento automático es lo que se define en la especificación de OpenID Connect. + +/// tip | Consejo + +Integrar otros proveedores de autenticación/autorización como Google, Facebook, Twitter, GitHub, etc. también es posible y relativamente fácil. + +El problema más complejo es construir un proveedor de autenticación/autorización como esos, pero **FastAPI** te da las herramientas para hacerlo fácilmente, mientras hace el trabajo pesado por ti. + +/// + +## Utilidades de **FastAPI** + +FastAPI proporciona varias herramientas para cada uno de estos esquemas de seguridad en el módulo `fastapi.security` que simplifican el uso de estos mecanismos de seguridad. + +En los siguientes capítulos verás cómo agregar seguridad a tu API usando esas herramientas proporcionadas por **FastAPI**. + +Y también verás cómo se integra automáticamente en el sistema de documentación interactiva. diff --git a/docs/es/docs/tutorial/security/oauth2-jwt.md b/docs/es/docs/tutorial/security/oauth2-jwt.md new file mode 100644 index 000000000..4ab9c8ca2 --- /dev/null +++ b/docs/es/docs/tutorial/security/oauth2-jwt.md @@ -0,0 +1,273 @@ +# OAuth2 con Password (y hashing), Bearer con tokens JWT + +Ahora que tenemos todo el flujo de seguridad, hagamos que la aplicación sea realmente segura, usando tokens JWT y hashing de contraseñas seguras. + +Este código es algo que puedes usar realmente en tu aplicación, guardar los hashes de las contraseñas en tu base de datos, etc. + +Vamos a empezar desde donde lo dejamos en el capítulo anterior e incrementarlo. + +## Acerca de JWT + +JWT significa "JSON Web Tokens". + +Es un estándar para codificar un objeto JSON en un string largo y denso sin espacios. Se ve así: + +``` +eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c +``` + +No está encriptado, por lo que cualquiera podría recuperar la información de los contenidos. + +Pero está firmado. Así que, cuando recibes un token que has emitido, puedes verificar que realmente lo emitiste. + +De esta manera, puedes crear un token con una expiración de, digamos, 1 semana. Y luego, cuando el usuario regresa al día siguiente con el token, sabes que el usuario todavía está registrado en tu sistema. + +Después de una semana, el token estará expirado y el usuario no estará autorizado y tendrá que iniciar sesión nuevamente para obtener un nuevo token. Y si el usuario (o un tercero) intenta modificar el token para cambiar la expiración, podrás descubrirlo, porque las firmas no coincidirían. + +Si quieres jugar con tokens JWT y ver cómo funcionan, revisa https://jwt.io. + +## Instalar `PyJWT` + +Necesitamos instalar `PyJWT` para generar y verificar los tokens JWT en Python. + +Asegúrate de crear un [entorno virtual](../../virtual-environments.md){.internal-link target=_blank}, activarlo y luego instalar `pyjwt`: + +
+ +```console +$ pip install pyjwt + +---> 100% +``` + +
+ +/// info | Información + +Si planeas usar algoritmos de firma digital como RSA o ECDSA, deberías instalar la dependencia del paquete de criptografía `pyjwt[crypto]`. + +Puedes leer más al respecto en la documentación de instalación de PyJWT. + +/// + +## Hashing de contraseñas + +"Hacer hashing" significa convertir algún contenido (una contraseña en este caso) en una secuencia de bytes (solo un string) que parece un galimatías. + +Siempre que pases exactamente el mismo contenido (exactamente la misma contraseña) obtienes exactamente el mismo galimatías. + +Pero no puedes convertir del galimatías de nuevo a la contraseña. + +### Por qué usar hashing de contraseñas + +Si tu base de datos es robada, el ladrón no tendrá las contraseñas en texto claro de tus usuarios, solo los hashes. + +Por lo tanto, el ladrón no podrá intentar usar esa contraseña en otro sistema (como muchos usuarios usan la misma contraseña en todas partes, esto sería peligroso). + +## Instalar `passlib` + +PassLib es un gran paquete de Python para manejar hashes de contraseñas. + +Soporta muchos algoritmos de hashing seguros y utilidades para trabajar con ellos. + +El algoritmo recomendado es "Bcrypt". + +Asegúrate de crear un [entorno virtual](../../virtual-environments.md){.internal-link target=_blank}, activarlo y luego instalar PassLib con Bcrypt: + +
+ +```console +$ pip install "passlib[bcrypt]" + +---> 100% +``` + +
+ +/// tip | Consejo + +Con `passlib`, incluso podrías configurarlo para poder leer contraseñas creadas por **Django**, un plug-in de seguridad de **Flask** u otros muchos. + +Así, podrías, por ejemplo, compartir los mismos datos de una aplicación de Django en una base de datos con una aplicación de FastAPI. O migrar gradualmente una aplicación de Django usando la misma base de datos. + +Y tus usuarios podrían iniciar sesión desde tu aplicación Django o desde tu aplicación **FastAPI**, al mismo tiempo. + +/// + +## Hash y verificación de contraseñas + +Importa las herramientas que necesitamos de `passlib`. + +Crea un "contexto" de PassLib. Este es el que se usará para hacer el hash y verificar las contraseñas. + +/// tip | Consejo + +El contexto de PassLib también tiene funcionalidad para usar diferentes algoritmos de hashing, incluidos los antiguos obsoletos solo para permitir verificarlos, etc. + +Por ejemplo, podrías usarlo para leer y verificar contraseñas generadas por otro sistema (como Django) pero hacer hash de cualquier contraseña nueva con un algoritmo diferente como Bcrypt. + +Y ser compatible con todos ellos al mismo tiempo. + +/// + +Crea una función de utilidad para hacer el hash de una contraseña que venga del usuario. + +Y otra utilidad para verificar si una contraseña recibida coincide con el hash almacenado. + +Y otra más para autenticar y devolver un usuario. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *} + +/// note | Nota + +Si revisas la nueva (falsa) base de datos `fake_users_db`, verás cómo se ve ahora la contraseña con hash: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. + +/// + +## Manejo de tokens JWT + +Importa los módulos instalados. + +Crea una clave secreta aleatoria que se usará para firmar los tokens JWT. + +Para generar una clave secreta segura al azar usa el comando: + +
+ +```console +$ openssl rand -hex 32 + +09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7 +``` + +
+ +Y copia el resultado a la variable `SECRET_KEY` (no uses la del ejemplo). + +Crea una variable `ALGORITHM` con el algoritmo usado para firmar el token JWT y configúralo a `"HS256"`. + +Crea una variable para la expiración del token. + +Define un Modelo de Pydantic que se usará en el endpoint de token para el response. + +Crea una función de utilidad para generar un nuevo token de acceso. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *} + +## Actualizar las dependencias + +Actualiza `get_current_user` para recibir el mismo token que antes, pero esta vez, usando tokens JWT. + +Decodifica el token recibido, verifícalo y devuelve el usuario actual. + +Si el token es inválido, devuelve un error HTTP de inmediato. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[90:107] *} + +## Actualizar la *path operation* `/token` + +Crea un `timedelta` con el tiempo de expiración del token. + +Crea un verdadero token de acceso JWT y devuélvelo. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *} + +### Detalles técnicos sobre el "sujeto" `sub` de JWT + +La especificación de JWT dice que hay una clave `sub`, con el sujeto del token. + +Es opcional usarlo, pero ahí es donde pondrías la identificación del usuario, por lo que lo estamos usando aquí. + +JWT podría ser usado para otras cosas aparte de identificar un usuario y permitirle realizar operaciones directamente en tu API. + +Por ejemplo, podrías identificar un "coche" o un "artículo de blog". + +Luego, podrías agregar permisos sobre esa entidad, como "conducir" (para el coche) o "editar" (para el blog). + +Y luego, podrías darle ese token JWT a un usuario (o bot), y ellos podrían usarlo para realizar esas acciones (conducir el coche, o editar el artículo del blog) sin siquiera necesitar tener una cuenta, solo con el token JWT que tu API generó para eso. + +Usando estas ideas, JWT puede ser utilizado para escenarios mucho más sofisticados. + +En esos casos, varias de esas entidades podrían tener el mismo ID, digamos `foo` (un usuario `foo`, un coche `foo`, y un artículo del blog `foo`). + +Entonces, para evitar colisiones de ID, cuando crees el token JWT para el usuario, podrías prefijar el valor de la clave `sub`, por ejemplo, con `username:`. Así, en este ejemplo, el valor de `sub` podría haber sido: `username:johndoe`. + +Lo importante a tener en cuenta es que la clave `sub` debería tener un identificador único a lo largo de toda la aplicación, y debería ser un string. + +## Revisa + +Ejecuta el servidor y ve a la documentación: http://127.0.0.1:8000/docs. + +Verás la interfaz de usuario como: + + + +Autoriza la aplicación de la misma manera que antes. + +Usando las credenciales: + +Usuario: `johndoe` +Contraseña: `secret` + +/// check | Revisa + +Observa que en ninguna parte del código está la contraseña en texto claro "`secret`", solo tenemos la versión con hash. + +/// + + + +Llama al endpoint `/users/me/`, obtendrás el response como: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false +} +``` + + + +Si abres las herramientas de desarrollador, podrías ver cómo los datos enviados solo incluyen el token, la contraseña solo se envía en la primera petición para autenticar al usuario y obtener ese token de acceso, pero no después: + + + +/// note | Nota + +Observa el header `Authorization`, con un valor que comienza con `Bearer `. + +/// + +## Uso avanzado con `scopes` + +OAuth2 tiene la noción de "scopes". + +Puedes usarlos para agregar un conjunto específico de permisos a un token JWT. + +Luego, puedes darle este token directamente a un usuario o a un tercero, para interactuar con tu API con un conjunto de restricciones. + +Puedes aprender cómo usarlos y cómo están integrados en **FastAPI** más adelante en la **Guía de Usuario Avanzada**. + +## Resumen + +Con lo que has visto hasta ahora, puedes configurar una aplicación **FastAPI** segura usando estándares como OAuth2 y JWT. + +En casi cualquier framework el manejo de la seguridad se convierte en un tema bastante complejo rápidamente. + +Muchos paquetes que lo simplifican tienen que hacer muchos compromisos con el modelo de datos, la base de datos y las funcionalidades disponibles. Y algunos de estos paquetes que simplifican las cosas demasiado en realidad tienen fallos de seguridad en el fondo. + +--- + +**FastAPI** no hace ningún compromiso con ninguna base de datos, modelo de datos o herramienta. + +Te da toda la flexibilidad para elegir aquellas que se ajusten mejor a tu proyecto. + +Y puedes usar directamente muchos paquetes bien mantenidos y ampliamente usados como `passlib` y `PyJWT`, porque **FastAPI** no requiere mecanismos complejos para integrar paquetes externos. + +Pero te proporciona las herramientas para simplificar el proceso tanto como sea posible sin comprometer la flexibilidad, la robustez o la seguridad. + +Y puedes usar e implementar protocolos seguros y estándar, como OAuth2 de una manera relativamente simple. + +Puedes aprender más en la **Guía de Usuario Avanzada** sobre cómo usar "scopes" de OAuth2, para un sistema de permisos más detallado, siguiendo estos mismos estándares. OAuth2 con scopes es el mecanismo utilizado por muchos grandes proveedores de autenticación, como Facebook, Google, GitHub, Microsoft, Twitter, etc. para autorizar aplicaciones de terceros para interactuar con sus APIs en nombre de sus usuarios. diff --git a/docs/es/docs/tutorial/security/simple-oauth2.md b/docs/es/docs/tutorial/security/simple-oauth2.md new file mode 100644 index 000000000..67449332f --- /dev/null +++ b/docs/es/docs/tutorial/security/simple-oauth2.md @@ -0,0 +1,289 @@ +# Simple OAuth2 con Password y Bearer + +Ahora vamos a construir a partir del capítulo anterior y agregar las partes faltantes para tener un flujo de seguridad completo. + +## Obtener el `username` y `password` + +Vamos a usar las utilidades de seguridad de **FastAPI** para obtener el `username` y `password`. + +OAuth2 especifica que cuando se utiliza el "password flow" (que estamos usando), el cliente/usuario debe enviar campos `username` y `password` como form data. + +Y la especificación dice que los campos deben llamarse así. Por lo que `user-name` o `email` no funcionarían. + +Pero no te preocupes, puedes mostrarlo como quieras a tus usuarios finales en el frontend. + +Y tus modelos de base de datos pueden usar cualquier otro nombre que desees. + +Pero para la *path operation* de inicio de sesión, necesitamos usar estos nombres para ser compatibles con la especificación (y poder, por ejemplo, utilizar el sistema de documentación integrada de la API). + +La especificación también establece que el `username` y `password` deben enviarse como form data (por lo que no hay JSON aquí). + +### `scope` + +La especificación también indica que el cliente puede enviar otro campo del formulario llamado "`scope`". + +El nombre del campo del formulario es `scope` (en singular), pero en realidad es un string largo con "scopes" separados por espacios. + +Cada "scope" es simplemente un string (sin espacios). + +Normalmente se utilizan para declarar permisos de seguridad específicos, por ejemplo: + +* `users:read` o `users:write` son ejemplos comunes. +* `instagram_basic` es usado por Facebook / Instagram. +* `https://www.googleapis.com/auth/drive` es usado por Google. + +/// info | Información + +En OAuth2 un "scope" es solo un string que declara un permiso específico requerido. + +No importa si tiene otros caracteres como `:` o si es una URL. + +Esos detalles son específicos de la implementación. + +Para OAuth2 son solo strings. + +/// + +## Código para obtener el `username` y `password` + +Ahora vamos a usar las utilidades proporcionadas por **FastAPI** para manejar esto. + +### `OAuth2PasswordRequestForm` + +Primero, importa `OAuth2PasswordRequestForm`, y úsalo como una dependencia con `Depends` en la *path operation* para `/token`: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *} + +`OAuth2PasswordRequestForm` es una dependencia de clase que declara un body de formulario con: + +* El `username`. +* El `password`. +* Un campo opcional `scope` como un string grande, compuesto por strings separados por espacios. +* Un `grant_type` opcional. + +/// tip | Consejo + +La especificación de OAuth2 en realidad *requiere* un campo `grant_type` con un valor fijo de `password`, pero `OAuth2PasswordRequestForm` no lo obliga. + +Si necesitas imponerlo, utiliza `OAuth2PasswordRequestFormStrict` en lugar de `OAuth2PasswordRequestForm`. + +/// + +* Un `client_id` opcional (no lo necesitamos para nuestro ejemplo). +* Un `client_secret` opcional (no lo necesitamos para nuestro ejemplo). + +/// info | Información + +`OAuth2PasswordRequestForm` no es una clase especial para **FastAPI** como lo es `OAuth2PasswordBearer`. + +`OAuth2PasswordBearer` hace que **FastAPI** sepa que es un esquema de seguridad. Así que se añade de esa manera a OpenAPI. + +Pero `OAuth2PasswordRequestForm` es solo una dependencia de clase que podrías haber escrito tú mismo, o podrías haber declarado parámetros de `Form` directamente. + +Pero como es un caso de uso común, se proporciona directamente por **FastAPI**, solo para facilitarlo. + +/// + +### Usa el form data + +/// tip | Consejo + +La instance de la clase de dependencia `OAuth2PasswordRequestForm` no tendrá un atributo `scope` con el string largo separado por espacios, en su lugar, tendrá un atributo `scopes` con la lista real de strings para cada scope enviado. + +No estamos usando `scopes` en este ejemplo, pero la funcionalidad está ahí si la necesitas. + +/// + +Ahora, obtén los datos del usuario desde la base de datos (falsa), usando el `username` del campo del form. + +Si no existe tal usuario, devolvemos un error diciendo "Incorrect username or password". + +Para el error, usamos la excepción `HTTPException`: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *} + +### Revisa el password + +En este punto tenemos los datos del usuario de nuestra base de datos, pero no hemos revisado el password. + +Primero pongamos esos datos en el modelo `UserInDB` de Pydantic. + +Nunca deberías guardar passwords en texto plano, así que, usaremos el sistema de hash de passwords (falso). + +Si los passwords no coinciden, devolvemos el mismo error. + +#### Hashing de passwords + +"Hacer hash" significa: convertir algún contenido (un password en este caso) en una secuencia de bytes (solo un string) que parece un galimatías. + +Siempre que pases exactamente el mismo contenido (exactamente el mismo password) obtienes exactamente el mismo galimatías. + +Pero no puedes convertir del galimatías al password. + +##### Por qué usar hashing de passwords + +Si tu base de datos es robada, el ladrón no tendrá los passwords en texto plano de tus usuarios, solo los hashes. + +Entonces, el ladrón no podrá intentar usar esos mismos passwords en otro sistema (como muchos usuarios usan el mismo password en todas partes, esto sería peligroso). + +{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *} + +#### Sobre `**user_dict` + +`UserInDB(**user_dict)` significa: + +*Pasa las claves y valores de `user_dict` directamente como argumentos clave-valor, equivalente a:* + +```Python +UserInDB( + username = user_dict["username"], + email = user_dict["email"], + full_name = user_dict["full_name"], + disabled = user_dict["disabled"], + hashed_password = user_dict["hashed_password"], +) +``` + +/// info | Información + +Para una explicación más completa de `**user_dict` revisa en [la documentación para **Extra Models**](../extra-models.md#about-user_indict){.internal-link target=_blank}. + +/// + +## Devolver el token + +El response del endpoint `token` debe ser un objeto JSON. + +Debe tener un `token_type`. En nuestro caso, como estamos usando tokens "Bearer", el tipo de token debe ser "`bearer`". + +Y debe tener un `access_token`, con un string que contenga nuestro token de acceso. + +Para este ejemplo simple, vamos a ser completamente inseguros y devolver el mismo `username` como el token. + +/// tip | Consejo + +En el próximo capítulo, verás una implementación segura real, con hashing de passwords y tokens JWT. + +Pero por ahora, enfoquémonos en los detalles específicos que necesitamos. + +/// + +{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *} + +/// tip | Consejo + +De acuerdo con la especificación, deberías devolver un JSON con un `access_token` y un `token_type`, igual que en este ejemplo. + +Esto es algo que tienes que hacer tú mismo en tu código, y asegurarte de usar esas claves JSON. + +Es casi lo único que tienes que recordar hacer correctamente tú mismo, para ser compatible con las especificaciones. + +Para el resto, **FastAPI** lo maneja por ti. + +/// + +## Actualizar las dependencias + +Ahora vamos a actualizar nuestras dependencias. + +Queremos obtener el `current_user` *solo* si este usuario está activo. + +Entonces, creamos una dependencia adicional `get_current_active_user` que a su vez utiliza `get_current_user` como dependencia. + +Ambas dependencias solo devolverán un error HTTP si el usuario no existe, o si está inactivo. + +Así que, en nuestro endpoint, solo obtendremos un usuario si el usuario existe, fue autenticado correctamente, y está activo: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *} + +/// info | Información + +El header adicional `WWW-Authenticate` con el valor `Bearer` que estamos devolviendo aquí también es parte de la especificación. + +Cualquier código de estado HTTP (error) 401 "UNAUTHORIZED" se supone que también debe devolver un header `WWW-Authenticate`. + +En el caso de tokens bearer (nuestro caso), el valor de ese header debe ser `Bearer`. + +De hecho, puedes omitir ese header extra y aún funcionaría. + +Pero se proporciona aquí para cumplir con las especificaciones. + +Además, podría haber herramientas que lo esperen y lo usen (ahora o en el futuro) y eso podría ser útil para ti o tus usuarios, ahora o en el futuro. + +Ese es el beneficio de los estándares... + +/// + +## Verlo en acción + +Abre la documentación interactiva: http://127.0.0.1:8000/docs. + +### Autenticar + +Haz clic en el botón "Authorize". + +Usa las credenciales: + +Usuario: `johndoe` + +Contraseña: `secret` + + + +Después de autenticarte en el sistema, lo verás así: + + + +### Obtener tus propios datos de usuario + +Ahora usa la operación `GET` con la path `/users/me`. + +Obtendrás los datos de tu usuario, como: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false, + "hashed_password": "fakehashedsecret" +} +``` + + + +Si haces clic en el icono de candado y cierras sesión, y luego intentas la misma operación nuevamente, obtendrás un error HTTP 401 de: + +```JSON +{ + "detail": "Not authenticated" +} +``` + +### Usuario inactivo + +Ahora prueba con un usuario inactivo, autentícate con: + +Usuario: `alice` + +Contraseña: `secret2` + +Y trata de usar la operación `GET` con la path `/users/me`. + +Obtendrás un error de "Usuario inactivo", como: + +```JSON +{ + "detail": "Inactive user" +} +``` + +## Recapitulación + +Ahora tienes las herramientas para implementar un sistema de seguridad completo basado en `username` y `password` para tu API. + +Usando estas herramientas, puedes hacer que el sistema de seguridad sea compatible con cualquier base de datos y con cualquier modelo de usuario o de datos. + +El único detalle que falta es que en realidad no es "seguro" aún. + +En el próximo capítulo verás cómo usar un paquete de hashing de passwords seguro y tokens JWT. diff --git a/docs/es/docs/tutorial/sql-databases.md b/docs/es/docs/tutorial/sql-databases.md new file mode 100644 index 000000000..68cc78603 --- /dev/null +++ b/docs/es/docs/tutorial/sql-databases.md @@ -0,0 +1,360 @@ +# Bases de Datos SQL (Relacionales) + +**FastAPI** no requiere que uses una base de datos SQL (relacional). Pero puedes utilizar **cualquier base de datos** que desees. + +Aquí veremos un ejemplo usando SQLModel. + +**SQLModel** está construido sobre SQLAlchemy y Pydantic. Fue creado por el mismo autor de **FastAPI** para ser la combinación perfecta para aplicaciones de FastAPI que necesiten usar **bases de datos SQL**. + +/// tip | Consejo + +Puedes usar cualquier otro paquete de bases de datos SQL o NoSQL que quieras (en algunos casos llamadas "ORMs"), FastAPI no te obliga a usar nada. 😎 + +/// + +Como SQLModel se basa en SQLAlchemy, puedes usar fácilmente **cualquier base de datos soportada** por SQLAlchemy (lo que las hace también soportadas por SQLModel), como: + +* PostgreSQL +* MySQL +* SQLite +* Oracle +* Microsoft SQL Server, etc. + +En este ejemplo, usaremos **SQLite**, porque utiliza un solo archivo y Python tiene soporte integrado. Así que puedes copiar este ejemplo y ejecutarlo tal cual. + +Más adelante, para tu aplicación en producción, es posible que desees usar un servidor de base de datos como **PostgreSQL**. + +/// tip | Consejo + +Hay un generador de proyectos oficial con **FastAPI** y **PostgreSQL** que incluye un frontend y más herramientas: https://github.com/fastapi/full-stack-fastapi-template + +/// + +Este es un tutorial muy simple y corto, si deseas aprender sobre bases de datos en general, sobre SQL o más funcionalidades avanzadas, ve a la documentación de SQLModel. + +## Instalar `SQLModel` + +Primero, asegúrate de crear tu [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, actívalo, y luego instala `sqlmodel`: + +
+ +```console +$ pip install sqlmodel +---> 100% +``` + +
+ +## Crear la App con un Solo Modelo + +Primero crearemos la versión más simple de la aplicación con un solo modelo de **SQLModel**. + +Más adelante la mejoraremos aumentando la seguridad y versatilidad con **múltiples modelos** a continuación. 🤓 + +### Crear Modelos + +Importa `SQLModel` y crea un modelo de base de datos: + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[1:11] hl[7:11] *} + +La clase `Hero` es muy similar a un modelo de Pydantic (de hecho, en el fondo, realmente *es un modelo de Pydantic*). + +Hay algunas diferencias: + +* `table=True` le dice a SQLModel que este es un *modelo de tabla*, que debe representar una **tabla** en la base de datos SQL, no es solo un *modelo de datos* (como lo sería cualquier otra clase regular de Pydantic). + +* `Field(primary_key=True)` le dice a SQLModel que `id` es la **clave primaria** en la base de datos SQL (puedes aprender más sobre claves primarias de SQL en la documentación de SQLModel). + + Al tener el tipo como `int | None`, SQLModel sabrá que esta columna debe ser un `INTEGER` en la base de datos SQL y que debe ser `NULLABLE`. + +* `Field(index=True)` le dice a SQLModel que debe crear un **índice SQL** para esta columna, lo que permitirá búsquedas más rápidas en la base de datos cuando se lean datos filtrados por esta columna. + + SQLModel sabrá que algo declarado como `str` será una columna SQL de tipo `TEXT` (o `VARCHAR`, dependiendo de la base de datos). + +### Crear un Engine + +Un `engine` de SQLModel (en el fondo, realmente es un `engine` de SQLAlchemy) es lo que **mantiene las conexiones** a la base de datos. + +Tendrías **un solo objeto `engine`** para todo tu código para conectar a la misma base de datos. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[14:18] hl[14:15,17:18] *} + +Usar `check_same_thread=False` permite a FastAPI usar la misma base de datos SQLite en diferentes hilos. Esto es necesario ya que **una sola request** podría usar **más de un hilo** (por ejemplo, en dependencias). + +No te preocupes, con la forma en que está estructurado el código, nos aseguraremos de usar **una sola *session* de SQLModel por request** más adelante, esto es realmente lo que intenta lograr el `check_same_thread`. + +### Crear las Tablas + +Luego añadimos una función que usa `SQLModel.metadata.create_all(engine)` para **crear las tablas** para todos los *modelos de tabla*. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[21:22] hl[21:22] *} + +### Crear una Dependencia de Session + +Una **`Session`** es lo que almacena los **objetos en memoria** y lleva un seguimiento de cualquier cambio necesario en los datos, luego **usa el `engine`** para comunicarse con la base de datos. + +Crearemos una **dependencia de FastAPI** con `yield` que proporcionará una nueva `Session` para cada request. Esto es lo que asegura que usemos una sola session por request. 🤓 + +Luego creamos una dependencia `Annotated` `SessionDep` para simplificar el resto del código que usará esta dependencia. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[25:30] hl[25:27,30] *} + +### Crear Tablas de Base de Datos al Arrancar + +Crearemos las tablas de la base de datos cuando arranque la aplicación. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[32:37] hl[35:37] *} + +Aquí creamos las tablas en un evento de inicio de la aplicación. + +Para producción probablemente usarías un script de migración que se ejecuta antes de iniciar tu aplicación. 🤓 + +/// tip | Consejo + +SQLModel tendrá utilidades de migración envolviendo Alembic, pero por ahora, puedes usar Alembic directamente. + +/// + +### Crear un Hero + +Debido a que cada modelo de SQLModel también es un modelo de Pydantic, puedes usarlo en las mismas **anotaciones de tipos** que podrías usar en modelos de Pydantic. + +Por ejemplo, si declaras un parámetro de tipo `Hero`, será leído desde el **JSON body**. + +De la misma manera, puedes declararlo como el **tipo de retorno** de la función, y luego la forma de los datos aparecerá en la interfaz automática de documentación de la API. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *} + + + +Aquí usamos la dependencia `SessionDep` (una `Session`) para añadir el nuevo `Hero` a la instance `Session`, comiteamos los cambios a la base de datos, refrescamos los datos en el `hero` y luego lo devolvemos. + +### Leer Heroes + +Podemos **leer** `Hero`s de la base de datos usando un `select()`. Podemos incluir un `limit` y `offset` para paginar los resultados. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[48:55] hl[51:52,54] *} + +### Leer Un Hero + +Podemos **leer** un único `Hero`. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[58:63] hl[60] *} + +### Eliminar un Hero + +También podemos **eliminar** un `Hero`. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[66:73] hl[71] *} + +### Ejecutar la App + +Puedes ejecutar la aplicación: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Luego dirígete a la interfaz de `/docs`, verás que **FastAPI** está usando estos **modelos** para **documentar** la API, y los usará para **serializar** y **validar** los datos también. + +
+ +
+ +## Actualizar la App con Múltiples Modelos + +Ahora vamos a **refactorizar** un poco esta aplicación para aumentar la **seguridad** y la **versatilidad**. + +Si revisas la aplicación anterior, en la interfaz verás que, hasta ahora, permite al cliente decidir el `id` del `Hero` a crear. 😱 + +No deberíamos permitir que eso suceda, podrían sobrescribir un `id` que ya tenemos asignado en la base de datos. Decidir el `id` debería ser tarea del **backend** o la **base de datos**, **no del cliente**. + +Además, creamos un `secret_name` para el héroe, pero hasta ahora, lo estamos devolviendo en todas partes, eso no es muy **secreto**... 😅 + +Arreglaremos estas cosas añadiendo unos **modelos extra**. Aquí es donde SQLModel brillará. ✨ + +### Crear Múltiples Modelos + +En **SQLModel**, cualquier clase de modelo que tenga `table=True` es un **modelo de tabla**. + +Y cualquier clase de modelo que no tenga `table=True` es un **modelo de datos**, estos son en realidad solo modelos de Pydantic (con un par de características extra pequeñas). 🤓 + +Con SQLModel, podemos usar **herencia** para **evitar duplicar** todos los campos en todos los casos. + +#### `HeroBase` - la clase base + +Comencemos con un modelo `HeroBase` que tiene todos los **campos que son compartidos** por todos los modelos: + +* `name` +* `age` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:9] hl[7:9] *} + +#### `Hero` - el *modelo de tabla* + +Luego, crearemos `Hero`, el *modelo de tabla* real, con los **campos extra** que no siempre están en los otros modelos: + +* `id` +* `secret_name` + +Debido a que `Hero` hereda de `HeroBase`, **también** tiene los **campos** declarados en `HeroBase`, por lo que todos los campos para `Hero` son: + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:14] hl[12:14] *} + +#### `HeroPublic` - el *modelo de datos* público + +A continuación, creamos un modelo `HeroPublic`, este es el que será **devuelto** a los clientes de la API. + +Tiene los mismos campos que `HeroBase`, por lo que no incluirá `secret_name`. + +Por fin, la identidad de nuestros héroes está protegida! 🥷 + +También vuelve a declarar `id: int`. Al hacer esto, estamos haciendo un **contrato** con los clientes de la API, para que siempre puedan esperar que el `id` esté allí y sea un `int` (nunca será `None`). + +/// tip | Consejo + +Tener el modelo de retorno asegurando que un valor siempre esté disponible y siempre sea `int` (no `None`) es muy útil para los clientes de la API, pueden escribir código mucho más simple teniendo esta certeza. + +Además, los **clientes generados automáticamente** tendrán interfaces más simples, para que los desarrolladores que se comuniquen con tu API puedan tener una experiencia mucho mejor trabajando con tu API. 😎 + +/// + +Todos los campos en `HeroPublic` son los mismos que en `HeroBase`, con `id` declarado como `int` (no `None`): + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *} + +#### `HeroCreate` - el *modelo de datos* para crear un héroe + +Ahora creamos un modelo `HeroCreate`, este es el que **validará** los datos de los clientes. + +Tiene los mismos campos que `HeroBase`, y también tiene `secret_name`. + +Ahora, cuando los clientes **crean un nuevo héroe**, enviarán el `secret_name`, se almacenará en la base de datos, pero esos nombres secretos no se devolverán en la API a los clientes. + +/// tip | Consejo + +Esta es la forma en la que manejarías **contraseñas**. Recíbelas, pero no las devuelvas en la API. + +También **hashea** los valores de las contraseñas antes de almacenarlos, **nunca los almacenes en texto plano**. + +/// + +Los campos de `HeroCreate` son: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:22] hl[21:22] *} + +#### `HeroUpdate` - el *modelo de datos* para actualizar un héroe + +No teníamos una forma de **actualizar un héroe** en la versión anterior de la aplicación, pero ahora con **múltiples modelos**, podemos hacerlo. 🎉 + +El *modelo de datos* `HeroUpdate` es algo especial, tiene **todos los mismos campos** que serían necesarios para crear un nuevo héroe, pero todos los campos son **opcionales** (todos tienen un valor por defecto). De esta forma, cuando actualices un héroe, puedes enviar solo los campos que deseas actualizar. + +Debido a que todos los **campos realmente cambian** (el tipo ahora incluye `None` y ahora tienen un valor por defecto de `None`), necesitamos **volver a declararlos**. + +Realmente no necesitamos heredar de `HeroBase` porque estamos volviendo a declarar todos los campos. Lo dejaré heredando solo por consistencia, pero esto no es necesario. Es más una cuestión de gusto personal. 🤷 + +Los campos de `HeroUpdate` son: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:28] hl[25:28] *} + +### Crear con `HeroCreate` y devolver un `HeroPublic` + +Ahora que tenemos **múltiples modelos**, podemos actualizar las partes de la aplicación que los usan. + +Recibimos en la request un *modelo de datos* `HeroCreate`, y a partir de él, creamos un *modelo de tabla* `Hero`. + +Este nuevo *modelo de tabla* `Hero` tendrá los campos enviados por el cliente, y también tendrá un `id` generado por la base de datos. + +Luego devolvemos el mismo *modelo de tabla* `Hero` tal cual desde la función. Pero como declaramos el `response_model` con el *modelo de datos* `HeroPublic`, **FastAPI** usará `HeroPublic` para validar y serializar los datos. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[56:62] hl[56:58] *} + +/// tip | Consejo + +Ahora usamos `response_model=HeroPublic` en lugar de la **anotación de tipo de retorno** `-> HeroPublic` porque el valor que estamos devolviendo en realidad *no* es un `HeroPublic`. + +Si hubiéramos declarado `-> HeroPublic`, tu editor y linter se quejarían (con razón) de que estás devolviendo un `Hero` en lugar de un `HeroPublic`. + +Al declararlo en `response_model` le estamos diciendo a **FastAPI** que haga lo suyo, sin interferir con las anotaciones de tipo y la ayuda de tu editor y otras herramientas. + +/// + +### Leer Heroes con `HeroPublic` + +Podemos hacer lo mismo que antes para **leer** `Hero`s, nuevamente, usamos `response_model=list[HeroPublic]` para asegurar que los datos se validen y serialicen correctamente. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[65:72] hl[65] *} + +### Leer Un Hero con `HeroPublic` + +Podemos **leer** un único héroe: + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[75:80] hl[77] *} + +### Actualizar un Hero con `HeroUpdate` + +Podemos **actualizar un héroe**. Para esto usamos una operación HTTP `PATCH`. + +Y en el código, obtenemos un `dict` con todos los datos enviados por el cliente, **solo los datos enviados por el cliente**, excluyendo cualquier valor que estaría allí solo por ser valores por defecto. Para hacerlo usamos `exclude_unset=True`. Este es el truco principal. 🪄 + +Luego usamos `hero_db.sqlmodel_update(hero_data)` para actualizar el `hero_db` con los datos de `hero_data`. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[83:93] hl[83:84,88:89] *} + +### Eliminar un Hero de Nuevo + +**Eliminar** un héroe se mantiene prácticamente igual. + +No satisfaremos el deseo de refactorizar todo en este punto. 😅 + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *} + +### Ejecutar la App de Nuevo + +Puedes ejecutar la aplicación de nuevo: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Si vas a la interfaz de `/docs` de la API, verás que ahora está actualizada, y no esperará recibir el `id` del cliente al crear un héroe, etc. + +
+ +
+ +## Resumen + +Puedes usar **SQLModel** para interactuar con una base de datos SQL y simplificar el código con *modelos de datos* y *modelos de tablas*. + +Puedes aprender mucho más en la documentación de **SQLModel**, hay un mini tutorial sobre el uso de SQLModel con **FastAPI**. 🚀 diff --git a/docs/es/docs/tutorial/static-files.md b/docs/es/docs/tutorial/static-files.md new file mode 100644 index 000000000..6aefecc4b --- /dev/null +++ b/docs/es/docs/tutorial/static-files.md @@ -0,0 +1,40 @@ +# Archivos Estáticos + +Puedes servir archivos estáticos automáticamente desde un directorio utilizando `StaticFiles`. + +## Usa `StaticFiles` + +* Importa `StaticFiles`. +* "Monta" una instance de `StaticFiles()` en un path específico. + +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} + +/// note | Detalles Técnicos + +También podrías usar `from starlette.staticfiles import StaticFiles`. + +**FastAPI** proporciona el mismo `starlette.staticfiles` como `fastapi.staticfiles` solo como una conveniencia para ti, el desarrollador. Pero en realidad viene directamente de Starlette. + +/// + +### Qué es "Montar" + +"Montar" significa agregar una aplicación completa "independiente" en un path específico, que luego se encargará de manejar todos los sub-paths. + +Esto es diferente a usar un `APIRouter`, ya que una aplicación montada es completamente independiente. El OpenAPI y la documentación de tu aplicación principal no incluirán nada de la aplicación montada, etc. + +Puedes leer más sobre esto en la [Guía de Usuario Avanzada](../advanced/index.md){.internal-link target=_blank}. + +## Detalles + +El primer `"/static"` se refiere al sub-path en el que esta "sub-aplicación" será "montada". Por lo tanto, cualquier path que comience con `"/static"` será manejado por ella. + +El `directory="static"` se refiere al nombre del directorio que contiene tus archivos estáticos. + +El `name="static"` le da un nombre que puede ser utilizado internamente por **FastAPI**. + +Todos estos parámetros pueden ser diferentes a "`static`", ajústalos según las necesidades y detalles específicos de tu propia aplicación. + +## Más info + +Para más detalles y opciones revisa la documentación de Starlette sobre Archivos Estáticos. diff --git a/docs/es/docs/tutorial/testing.md b/docs/es/docs/tutorial/testing.md new file mode 100644 index 000000000..62ad89d58 --- /dev/null +++ b/docs/es/docs/tutorial/testing.md @@ -0,0 +1,240 @@ +# Testing + +Gracias a Starlette, escribir pruebas para aplicaciones de **FastAPI** es fácil y agradable. + +Está basado en HTTPX, que a su vez está diseñado basado en Requests, por lo que es muy familiar e intuitivo. + +Con él, puedes usar pytest directamente con **FastAPI**. + +## Usando `TestClient` + +/// info | Información + +Para usar `TestClient`, primero instala `httpx`. + +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, activarlo y luego instalarlo, por ejemplo: + +```console +$ pip install httpx +``` + +/// + +Importa `TestClient`. + +Crea un `TestClient` pasándole tu aplicación de **FastAPI**. + +Crea funciones con un nombre que comience con `test_` (esta es la convención estándar de `pytest`). + +Usa el objeto `TestClient` de la misma manera que con `httpx`. + +Escribe declaraciones `assert` simples con las expresiones estándar de Python que necesites revisar (otra vez, estándar de `pytest`). + +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} + +/// tip | Consejo + +Nota que las funciones de prueba son `def` normales, no `async def`. + +Y las llamadas al cliente también son llamadas normales, sin usar `await`. + +Esto te permite usar `pytest` directamente sin complicaciones. + +/// + +/// note | Nota Técnica + +También podrías usar `from starlette.testclient import TestClient`. + +**FastAPI** proporciona el mismo `starlette.testclient` como `fastapi.testclient` solo por conveniencia para ti, el desarrollador. Pero proviene directamente de Starlette. + +/// + +/// tip | Consejo + +Si quieres llamar a funciones `async` en tus pruebas además de enviar solicitudes a tu aplicación FastAPI (por ejemplo, funciones asincrónicas de bases de datos), echa un vistazo a las [Pruebas Asincrónicas](../advanced/async-tests.md){.internal-link target=_blank} en el tutorial avanzado. + +/// + +## Separando pruebas + +En una aplicación real, probablemente tendrías tus pruebas en un archivo diferente. + +Y tu aplicación de **FastAPI** también podría estar compuesta de varios archivos/módulos, etc. + +### Archivo de aplicación **FastAPI** + +Digamos que tienes una estructura de archivos como se describe en [Aplicaciones Más Grandes](bigger-applications.md){.internal-link target=_blank}: + +``` +. +├── app +│   ├── __init__.py +│   └── main.py +``` + +En el archivo `main.py` tienes tu aplicación de **FastAPI**: + +{* ../../docs_src/app_testing/main.py *} + +### Archivo de prueba + +Entonces podrías tener un archivo `test_main.py` con tus pruebas. Podría estar en el mismo paquete de Python (el mismo directorio con un archivo `__init__.py`): + +``` hl_lines="5" +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Debido a que este archivo está en el mismo paquete, puedes usar importaciones relativas para importar el objeto `app` desde el módulo `main` (`main.py`): + +{* ../../docs_src/app_testing/test_main.py hl[3] *} + +...y tener el código para las pruebas tal como antes. + +## Pruebas: ejemplo extendido + +Ahora extiende este ejemplo y añade más detalles para ver cómo escribir pruebas para diferentes partes. + +### Archivo de aplicación **FastAPI** extendido + +Continuemos con la misma estructura de archivos que antes: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Digamos que ahora el archivo `main.py` con tu aplicación de **FastAPI** tiene algunas otras **path operations**. + +Tiene una operación `GET` que podría devolver un error. + +Tiene una operación `POST` que podría devolver varios errores. + +Ambas *path operations* requieren un `X-Token` header. + +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/app_testing/app_b_an/main.py!} +``` + +//// + +//// tab | Python 3.10+ sin Anotar + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +```Python +{!> ../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ sin Anotar + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +```Python +{!> ../../docs_src/app_testing/app_b/main.py!} +``` + +//// + +### Archivo de prueba extendido + +Podrías entonces actualizar `test_main.py` con las pruebas extendidas: + +{* ../../docs_src/app_testing/app_b/test_main.py *} + +Cada vez que necesites que el cliente pase información en el request y no sepas cómo, puedes buscar (Googlear) cómo hacerlo en `httpx`, o incluso cómo hacerlo con `requests`, dado que el diseño de HTTPX está basado en el diseño de Requests. + +Luego simplemente haces lo mismo en tus pruebas. + +Por ejemplo: + +* Para pasar un parámetro de *path* o *query*, añádelo a la URL misma. +* Para pasar un cuerpo JSON, pasa un objeto de Python (por ejemplo, un `dict`) al parámetro `json`. +* Si necesitas enviar *Form Data* en lugar de JSON, usa el parámetro `data` en su lugar. +* Para pasar *headers*, usa un `dict` en el parámetro `headers`. +* Para *cookies*, un `dict` en el parámetro `cookies`. + +Para más información sobre cómo pasar datos al backend (usando `httpx` o el `TestClient`) revisa la documentación de HTTPX. + +/// info | Información + +Ten en cuenta que el `TestClient` recibe datos que pueden ser convertidos a JSON, no modelos de Pydantic. + +Si tienes un modelo de Pydantic en tu prueba y quieres enviar sus datos a la aplicación durante las pruebas, puedes usar el `jsonable_encoder` descrito en [Codificador Compatible con JSON](encoder.md){.internal-link target=_blank}. + +/// + +## Ejecútalo + +Después de eso, solo necesitas instalar `pytest`. + +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, activarlo y luego instalarlo, por ejemplo: + +
+ +```console +$ pip install pytest + +---> 100% +``` + +
+ +Detectará los archivos y pruebas automáticamente, ejecutará las mismas y te reportará los resultados. + +Ejecuta las pruebas con: + +
+ +```console +$ pytest + +================ test session starts ================ +platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 +rootdir: /home/user/code/superawesome-cli/app +plugins: forked-1.1.3, xdist-1.31.0, cov-2.8.1 +collected 6 items + +---> 100% + +test_main.py ...... [100%] + +================= 1 passed in 0.03s ================= +``` + +
diff --git a/docs/es/docs/virtual-environments.md b/docs/es/docs/virtual-environments.md new file mode 100644 index 000000000..71d450e09 --- /dev/null +++ b/docs/es/docs/virtual-environments.md @@ -0,0 +1,842 @@ +# Entornos Virtuales + +Cuando trabajas en proyectos de Python probablemente deberías usar un **entorno virtual** (o un mecanismo similar) para aislar los paquetes que instalas para cada proyecto. + +/// info | Información + +Si ya sabes sobre entornos virtuales, cómo crearlos y usarlos, podrías querer saltar esta sección. 🤓 + +/// + +/// tip | Consejo + +Un **entorno virtual** es diferente de una **variable de entorno**. + +Una **variable de entorno** es una variable en el sistema que puede ser usada por programas. + +Un **entorno virtual** es un directorio con algunos archivos en él. + +/// + +/// info | Información + +Esta página te enseñará cómo usar **entornos virtuales** y cómo funcionan. + +Si estás listo para adoptar una **herramienta que gestiona todo** por ti (incluyendo la instalación de Python), prueba uv. + +/// + +## Crea un Proyecto + +Primero, crea un directorio para tu proyecto. + +Lo que normalmente hago es crear un directorio llamado `code` dentro de mi directorio de usuario. + +Y dentro de eso creo un directorio por proyecto. + +
+ +```console +// Ve al directorio principal +$ cd +// Crea un directorio para todos tus proyectos de código +$ mkdir code +// Entra en ese directorio de código +$ cd code +// Crea un directorio para este proyecto +$ mkdir awesome-project +// Entra en ese directorio del proyecto +$ cd awesome-project +``` + +
+ +## Crea un Entorno Virtual + +Cuando empiezas a trabajar en un proyecto de Python **por primera vez**, crea un entorno virtual **dentro de tu proyecto**. + +/// tip | Consejo + +Solo necesitas hacer esto **una vez por proyecto**, no cada vez que trabajas. + +/// + +//// tab | `venv` + +Para crear un entorno virtual, puedes usar el módulo `venv` que viene con Python. + +
+ +```console +$ python -m venv .venv +``` + +
+ +/// details | Qué significa ese comando + +* `python`: usa el programa llamado `python` +* `-m`: llama a un módulo como un script, indicaremos cuál módulo a continuación +* `venv`: usa el módulo llamado `venv` que normalmente viene instalado con Python +* `.venv`: crea el entorno virtual en el nuevo directorio `.venv` + +/// + +//// + +//// tab | `uv` + +Si tienes instalado `uv`, puedes usarlo para crear un entorno virtual. + +
+ +```console +$ uv venv +``` + +
+ +/// tip | Consejo + +Por defecto, `uv` creará un entorno virtual en un directorio llamado `.venv`. + +Pero podrías personalizarlo pasando un argumento adicional con el nombre del directorio. + +/// + +//// + +Ese comando crea un nuevo entorno virtual en un directorio llamado `.venv`. + +/// details | `.venv` u otro nombre + +Podrías crear el entorno virtual en un directorio diferente, pero hay una convención de llamarlo `.venv`. + +/// + +## Activa el Entorno Virtual + +Activa el nuevo entorno virtual para que cualquier comando de Python que ejecutes o paquete que instales lo utilicen. + +/// tip | Consejo + +Haz esto **cada vez** que inicies una **nueva sesión de terminal** para trabajar en el proyecto. + +/// + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +O si usas Bash para Windows (por ejemplo, Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +/// tip | Consejo + +Cada vez que instales un **nuevo paquete** en ese entorno, **activa** el entorno de nuevo. + +Esto asegura que si usas un programa de **terminal (CLI)** instalado por ese paquete, uses el de tu entorno virtual y no cualquier otro que podría estar instalado globalmente, probablemente con una versión diferente a la que necesitas. + +/// + +## Verifica que el Entorno Virtual esté Activo + +Verifica que el entorno virtual esté activo (el comando anterior funcionó). + +/// tip | Consejo + +Esto es **opcional**, pero es una buena forma de **revisar** que todo está funcionando como se esperaba y estás usando el entorno virtual que pretendes. + +/// + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +Si muestra el binario de `python` en `.venv/bin/python`, dentro de tu proyecto (en este caso `awesome-project`), entonces funcionó. 🎉 + +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +Si muestra el binario de `python` en `.venv\Scripts\python`, dentro de tu proyecto (en este caso `awesome-project`), entonces funcionó. 🎉 + +//// + +## Actualiza `pip` + +/// tip | Consejo + +Si usas `uv` usarías eso para instalar cosas en lugar de `pip`, por lo que no necesitas actualizar `pip`. 😎 + +/// + +Si estás usando `pip` para instalar paquetes (viene por defecto con Python), deberías **actualizarlo** a la última versión. + +Muchos errores exóticos al instalar un paquete se resuelven simplemente actualizando `pip` primero. + +/// tip | Consejo + +Normalmente harías esto **una vez**, justo después de crear el entorno virtual. + +/// + +Asegúrate de que el entorno virtual esté activo (con el comando anterior) y luego ejecuta: + +
+ +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
+ +## Añade `.gitignore` + +Si estás usando **Git** (deberías), añade un archivo `.gitignore` para excluir todo en tu `.venv` de Git. + +/// tip | Consejo + +Si usaste `uv` para crear el entorno virtual, ya lo hizo por ti, puedes saltarte este paso. 😎 + +/// + +/// tip | Consejo + +Haz esto **una vez**, justo después de crear el entorno virtual. + +/// + +
+ +```console +$ echo "*" > .venv/.gitignore +``` + +
+ +/// details | Qué significa ese comando + +* `echo "*"`: "imprimirá" el texto `*` en el terminal (la siguiente parte cambia eso un poco) +* `>`: cualquier cosa impresa en el terminal por el comando a la izquierda de `>` no debería imprimirse, sino escribirse en el archivo que va a la derecha de `>` +* `.gitignore`: el nombre del archivo donde debería escribirse el texto + +Y `*` para Git significa "todo". Así que, ignorará todo en el directorio `.venv`. + +Ese comando creará un archivo `.gitignore` con el contenido: + +```gitignore +* +``` + +/// + +## Instala Paquetes + +Después de activar el entorno, puedes instalar paquetes en él. + +/// tip | Consejo + +Haz esto **una vez** al instalar o actualizar los paquetes que necesita tu proyecto. + +Si necesitas actualizar una versión o agregar un nuevo paquete, **harías esto de nuevo**. + +/// + +### Instala Paquetes Directamente + +Si tienes prisa y no quieres usar un archivo para declarar los requisitos de paquetes de tu proyecto, puedes instalarlos directamente. + +/// tip | Consejo + +Es una (muy) buena idea poner los paquetes y las versiones que necesita tu programa en un archivo (por ejemplo, `requirements.txt` o `pyproject.toml`). + +/// + +//// tab | `pip` + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +Si tienes `uv`: + +
+ +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
+ +//// + +### Instala desde `requirements.txt` + +Si tienes un `requirements.txt`, ahora puedes usarlo para instalar sus paquetes. + +//// tab | `pip` + +
+ +```console +$ pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +Si tienes `uv`: + +
+ +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +/// details | `requirements.txt` + +Un `requirements.txt` con algunos paquetes podría verse así: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## Ejecuta Tu Programa + +Después de activar el entorno virtual, puedes ejecutar tu programa, y usará el Python dentro de tu entorno virtual con los paquetes que instalaste allí. + +
+ +```console +$ python main.py + +Hello World +``` + +
+ +## Configura Tu Editor + +Probablemente usarías un editor, asegúrate de configurarlo para que use el mismo entorno virtual que creaste (probablemente lo autodetectará) para que puedas obtener autocompletado y errores en línea. + +Por ejemplo: + +* VS Code +* PyCharm + +/// tip | Consejo + +Normalmente solo tendrías que hacer esto **una vez**, cuando crees el entorno virtual. + +/// + +## Desactiva el Entorno Virtual + +Una vez que hayas terminado de trabajar en tu proyecto, puedes **desactivar** el entorno virtual. + +
+ +```console +$ deactivate +``` + +
+ +De esta manera, cuando ejecutes `python` no intentará ejecutarse desde ese entorno virtual con los paquetes instalados allí. + +## Listo para Trabajar + +Ahora estás listo para empezar a trabajar en tu proyecto. + +/// tip | Consejo + +¿Quieres entender todo lo anterior? + +Continúa leyendo. 👇🤓 + +/// + +## Por qué Entornos Virtuales + +Para trabajar con FastAPI necesitas instalar Python. + +Después de eso, necesitarías **instalar** FastAPI y cualquier otro **paquete** que desees usar. + +Para instalar paquetes normalmente usarías el comando `pip` que viene con Python (o alternativas similares). + +Sin embargo, si solo usas `pip` directamente, los paquetes se instalarían en tu **entorno global de Python** (la instalación global de Python). + +### El Problema + +Entonces, ¿cuál es el problema de instalar paquetes en el entorno global de Python? + +En algún momento, probablemente terminarás escribiendo muchos programas diferentes que dependen de **diferentes paquetes**. Y algunos de estos proyectos en los que trabajas dependerán de **diferentes versiones** del mismo paquete. 😱 + +Por ejemplo, podrías crear un proyecto llamado `philosophers-stone`, este programa depende de otro paquete llamado **`harry`, usando la versión `1`**. Así que, necesitas instalar `harry`. + +```mermaid +flowchart LR + stone(philosophers-stone) -->|requires| harry-1[harry v1] +``` + +Luego, en algún momento después, creas otro proyecto llamado `prisoner-of-azkaban`, y este proyecto también depende de `harry`, pero este proyecto necesita **`harry` versión `3`**. + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3] +``` + +Pero ahora el problema es, si instalas los paquetes globalmente (en el entorno global) en lugar de en un **entorno virtual local**, tendrás que elegir qué versión de `harry` instalar. + +Si deseas ejecutar `philosophers-stone` necesitarás primero instalar `harry` versión `1`, por ejemplo con: + +
+ +```console +$ pip install "harry==1" +``` + +
+ +Y entonces terminarías con `harry` versión `1` instalada en tu entorno global de Python. + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -->|requires| harry-1 + end +``` + +Pero luego si deseas ejecutar `prisoner-of-azkaban`, necesitarás desinstalar `harry` versión `1` e instalar `harry` versión `3` (o simplemente instalar la versión `3` automáticamente desinstalaría la versión `1`). + +
+ +```console +$ pip install "harry==3" +``` + +
+ +Y entonces terminarías con `harry` versión `3` instalada en tu entorno global de Python. + +Y si intentas ejecutar `philosophers-stone` de nuevo, hay una posibilidad de que **no funcione** porque necesita `harry` versión `1`. + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --> |requires| harry-3 + end +``` + +/// tip | Consejo + +Es muy común en los paquetes de Python intentar lo mejor para **evitar romper cambios** en **nuevas versiones**, pero es mejor estar seguro e instalar nuevas versiones intencionalmente y cuando puedas ejecutar las pruebas para verificar que todo está funcionando correctamente. + +/// + +Ahora, imagina eso con **muchos** otros **paquetes** de los que dependen todos tus **proyectos**. Eso es muy difícil de manejar. Y probablemente terminarías ejecutando algunos proyectos con algunas **versiones incompatibles** de los paquetes, y sin saber por qué algo no está funcionando. + +Además, dependiendo de tu sistema operativo (por ejemplo, Linux, Windows, macOS), podría haber venido con Python ya instalado. Y en ese caso probablemente tenía algunos paquetes preinstalados con algunas versiones específicas **necesitadas por tu sistema**. Si instalas paquetes en el entorno global de Python, podrías terminar **rompiendo** algunos de los programas que vinieron con tu sistema operativo. + +## Dónde se Instalan los Paquetes + +Cuando instalas Python, crea algunos directorios con algunos archivos en tu computadora. + +Algunos de estos directorios son los encargados de tener todos los paquetes que instalas. + +Cuando ejecutas: + +
+ +```console +// No ejecutes esto ahora, solo es un ejemplo 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
+ +Eso descargará un archivo comprimido con el código de FastAPI, normalmente desde PyPI. + +También **descargará** archivos para otros paquetes de los que depende FastAPI. + +Luego, **extraerá** todos esos archivos y los pondrá en un directorio en tu computadora. + +Por defecto, pondrá esos archivos descargados y extraídos en el directorio que viene con tu instalación de Python, eso es el **entorno global**. + +## Qué son los Entornos Virtuales + +La solución a los problemas de tener todos los paquetes en el entorno global es usar un **entorno virtual para cada proyecto** en el que trabajas. + +Un entorno virtual es un **directorio**, muy similar al global, donde puedes instalar los paquetes para un proyecto. + +De esta manera, cada proyecto tendrá su propio entorno virtual (directorio `.venv`) con sus propios paquetes. + +```mermaid +flowchart TB + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) --->|requires| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --->|requires| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## Qué Significa Activar un Entorno Virtual + +Cuando activas un entorno virtual, por ejemplo con: + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +O si usas Bash para Windows (por ejemplo, Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +Ese comando creará o modificará algunas [variables de entorno](environment-variables.md){.internal-link target=_blank} que estarán disponibles para los siguientes comandos. + +Una de esas variables es la variable `PATH`. + +/// tip | Consejo + +Puedes aprender más sobre la variable de entorno `PATH` en la sección [Variables de Entorno](environment-variables.md#path-environment-variable){.internal-link target=_blank}. + +/// + +Activar un entorno virtual agrega su path `.venv/bin` (en Linux y macOS) o `.venv\Scripts` (en Windows) a la variable de entorno `PATH`. + +Digamos que antes de activar el entorno, la variable `PATH` se veía así: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +Eso significa que el sistema buscaría programas en: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +Eso significa que el sistema buscaría programas en: + +* `C:\Windows\System32` + +//// + +Después de activar el entorno virtual, la variable `PATH` se vería algo así: + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Eso significa que el sistema ahora comenzará a buscar primero los programas en: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +antes de buscar en los otros directorios. + +Así que, cuando escribas `python` en el terminal, el sistema encontrará el programa Python en + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +y utilizará ese. + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +Eso significa que el sistema ahora comenzará a buscar primero los programas en: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +antes de buscar en los otros directorios. + +Así que, cuando escribas `python` en el terminal, el sistema encontrará el programa Python en + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +y utilizará ese. + +//// + +Un detalle importante es que pondrá el path del entorno virtual al **comienzo** de la variable `PATH`. El sistema lo encontrará **antes** que cualquier otro Python disponible. De esta manera, cuando ejecutes `python`, utilizará el Python **del entorno virtual** en lugar de cualquier otro `python` (por ejemplo, un `python` de un entorno global). + +Activar un entorno virtual también cambia un par de otras cosas, pero esta es una de las cosas más importantes que hace. + +## Verificando un Entorno Virtual + +Cuando revisas si un entorno virtual está activo, por ejemplo con: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +//// + +Eso significa que el programa `python` que se utilizará es el que está **en el entorno virtual**. + +Usas `which` en Linux y macOS y `Get-Command` en Windows PowerShell. + +La forma en que funciona ese comando es que irá y revisará la variable de entorno `PATH`, pasando por **cada path en orden**, buscando el programa llamado `python`. Una vez que lo encuentre, te **mostrará el path** a ese programa. + +La parte más importante es que cuando llamas a `python`, ese es el exacto "`python`" que será ejecutado. + +Así que, puedes confirmar si estás en el entorno virtual correcto. + +/// tip | Consejo + +Es fácil activar un entorno virtual, obtener un Python, y luego **ir a otro proyecto**. + +Y el segundo proyecto **no funcionaría** porque estás usando el **Python incorrecto**, de un entorno virtual para otro proyecto. + +Es útil poder revisar qué `python` se está usando. 🤓 + +/// + +## Por qué Desactivar un Entorno Virtual + +Por ejemplo, podrías estar trabajando en un proyecto `philosophers-stone`, **activar ese entorno virtual**, instalar paquetes y trabajar con ese entorno. + +Y luego quieres trabajar en **otro proyecto** `prisoner-of-azkaban`. + +Vas a ese proyecto: + +
+ +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
+ +Si no desactivas el entorno virtual para `philosophers-stone`, cuando ejecutes `python` en el terminal, intentará usar el Python de `philosophers-stone`. + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// Error importando sirius, no está instalado 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
+ +Pero si desactivas el entorno virtual y activas el nuevo para `prisoner-of-askaban` entonces cuando ejecutes `python` utilizará el Python del entorno virtual en `prisoner-of-azkaban`. + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +// No necesitas estar en el directorio antiguo para desactivar, puedes hacerlo donde sea que estés, incluso después de ir al otro proyecto 😎 +$ deactivate + +// Activa el entorno virtual en prisoner-of-azkaban/.venv 🚀 +$ source .venv/bin/activate + +// Ahora cuando ejecutes python, encontrará el paquete sirius instalado en este entorno virtual ✨ +$ python main.py + +I solemnly swear 🐺 +``` + +
+ +## Alternativas + +Esta es una guía simple para comenzar y enseñarte cómo funciona todo **por debajo**. + +Hay muchas **alternativas** para gestionar entornos virtuales, dependencias de paquetes (requisitos), proyectos. + +Una vez que estés listo y quieras usar una herramienta para **gestionar todo el proyecto**, dependencias de paquetes, entornos virtuales, etc. Te sugeriría probar uv. + +`uv` puede hacer muchas cosas, puede: + +* **Instalar Python** por ti, incluyendo diferentes versiones +* Gestionar el **entorno virtual** para tus proyectos +* Instalar **paquetes** +* Gestionar **dependencias y versiones** de paquetes para tu proyecto +* Asegurarse de que tengas un conjunto **exacto** de paquetes y versiones para instalar, incluidas sus dependencias, para que puedas estar seguro de que puedes ejecutar tu proyecto en producción exactamente igual que en tu computadora mientras desarrollas, esto se llama **locking** +* Y muchas otras cosas + +## Conclusión + +Si leíste y comprendiste todo esto, ahora **sabes mucho más** sobre entornos virtuales que muchos desarrolladores por ahí. 🤓 + +Conocer estos detalles probablemente te será útil en el futuro cuando estés depurando algo que parece complejo, pero sabrás **cómo funciona todo por debajo**. 😎 From e2f6e5f6fcabd789b105308b04da10e9c6055177 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 30 Dec 2024 18:28:14 +0000 Subject: [PATCH 605/932] =?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 [skip ci] --- 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 c62f551e1..e7e297af4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Translations +* 🌐 Add new Spanish translations for all docs with new LLM-assisted system using PydanticAI. PR [#13122](https://github.com/fastapi/fastapi/pull/13122) by [@tiangolo](https://github.com/tiangolo). * 🌐 Update existing Spanish translations using the new LLM-assisted system using PydanticAI. PR [#13118](https://github.com/fastapi/fastapi/pull/13118) by [@tiangolo](https://github.com/tiangolo). * 🌐 Update Chinese translation for `docs/zh/docs/advanced/security/oauth2-scopes.md`. PR [#13110](https://github.com/fastapi/fastapi/pull/13110) by [@ChenPu2002](https://github.com/ChenPu2002). * 🌐 Add Indonesian translation for `docs/id/docs/tutorial/path-params.md`. PR [#13086](https://github.com/fastapi/fastapi/pull/13086) by [@gerry-sabar](https://github.com/gerry-sabar). From acd9c4e1aac6888c462e21dc7f25f1f7d5c228ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 30 Dec 2024 18:46:43 +0000 Subject: [PATCH 606/932] =?UTF-8?q?=F0=9F=94=A8=20Add=20internal=20scripts?= =?UTF-8?q?=20to=20generate=20language=20translations=20with=20PydanticAI,?= =?UTF-8?q?=20include=20Spanish=20prompt=20(#13123)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/es/llm-prompt.md | 148 +++++++++++++++++++++++++++++++ requirements-translations.txt | 1 + scripts/translate.py | 162 ++++++++++++++++++++++++++++++++++ 3 files changed, 311 insertions(+) create mode 100644 docs/es/llm-prompt.md create mode 100644 requirements-translations.txt create mode 100644 scripts/translate.py diff --git a/docs/es/llm-prompt.md b/docs/es/llm-prompt.md new file mode 100644 index 000000000..3340dbc99 --- /dev/null +++ b/docs/es/llm-prompt.md @@ -0,0 +1,148 @@ +Translate to Spanish (español). + +Use the informal grammar (use "tú" instead of "usted"). + +For instructions or titles in imperative, keep them in imperative, for example "Edit it" to "Edítalo". + +There are special blocks of notes, tips and others that look like: + +/// note + +To translate it, keep the same line and add the translation after a vertical bar: + +/// note | Nota + +Some examples: + +Source: + +/// tip + +Result: + +/// tip | Consejo + +Source: + +/// details | Preview + +Result: + +/// details | Vista previa + +Source: + +/// warning + +Result: + +/// warning | Advertencia + +Source: + +/// info + +Result: + +/// info | Información + +Source: + +/// note | Technical Details + +Result: + +/// note | Detalles Técnicos + +--- + +For the next terms, use the following translations: + +* framework: framework (do not translate to "marco") +* performance: rendimiento +* program (verb): programar +* code (verb): programar +* type hints: anotaciones de tipos +* type annotations: anotaciones de tipos +* autocomplete: autocompletado +* completion (in the context of autocompletion): autocompletado +* feature: funcionalidad +* sponsor: sponsor +* host (in a podcast): host +* request (as in HTTP request): request +* response (as in HTTP response): response +* path operation function: path operation function (do not translate to "función de operación de ruta") +* path operation: path operation (do not translate to "operación de ruta") +* path (as in URL path): path (do not translate to "ruta") +* query (as in URL query): query (do not translate to "consulta") +* cookie (as in HTTP cookie): cookie +* header (as in HTTP header): header +* form (as in HTML form): formulario +* type checks: chequeo de tipos +* parse: parse +* parsing: parsing +* marshall: marshall +* library: paquete (do not translate to "biblioteca" or "librería") +* instance: instance (do not translate to "instancia") +* scratch the surface: tocar los conceptos básicos +* string: string +* bug: bug +* docs: documentación (do not translate to "documentos") +* cheat sheet: cheat sheet (do not translate to "chuleta") +* key (as in key-value pair, dictionary key): clave +* array (as in JSON array): array +* API key: API key (do not translate to "clave API") +* 100% test coverage: cobertura de tests del 100% +* back and forth: de un lado a otro +* I/O (as in "input and output"): I/O (do not translate to "E/S") +* Machine Learning: Machine Learning (do not translate to "Aprendizaje Automático") +* Deep Learning: Deep Learning (do not translate to "Aprendizaje Profundo") +* callback hell: callback hell (do not translate to "infierno de callbacks") +* tip: Consejo (do not translate to "tip") +* check: Revisa (do not translate to "chequea" or "comprobación) +* Cross-Origin Resource Sharing: Cross-Origin Resource Sharing (do not translate to "Compartición de Recursos de Origen Cruzado") +* Release Notes: Release Notes (do not translate to "Notas de la Versión") +* Semantic Versioning: Semantic Versioning (do not translate to "Versionado Semántico") +* dependable: dependable (do not translate to "confiable" or "fiable") +* list (as in Python list): list +* context manager: context manager (do not translate to "gestor de contexto" or "administrador de contexto") +* a little bit: un poquito +* graph (data structure, as in "dependency graph"): grafo (do not translate to "gráfico") +* form data: form data (do not translate to "datos de formulario" or "datos de form") +* import (as in code import): import (do not translate to "importación") +* JSON Schema: JSON Schema (do not translate to "Esquema JSON") +* embed: embeber (do not translate to "incrustar") +* request body: request body (do not translate to "cuerpo de la petición") +* response body: response body (do not translate to "cuerpo de la respuesta") +* cross domain: cross domain (do not translate to "dominio cruzado") +* cross origin: cross origin (do not translate to "origen cruzado") +* plugin: plugin (do not translate to "complemento" or "extensión") +* plug-in: plug-in (do not translate to "complemento" or "extensión") +* plug-ins: plug-ins (do not translate to "complementos" or "extensiones") +* full stack: full stack (do not translate to "pila completa") +* full-stack: full-stack (do not translate to "de pila completa") +* stack: stack (do not translate to "pila") +* loop (as in async loop): loop (do not translate to "bucle" or "ciclo") +* hard dependencies: dependencias obligatorias (do not translate to "dependencias duras") +* locking: locking (do not translate to "bloqueo") +* testing (as in software testing): escribir pruebas (do not translate to "probar") +* code base: code base (do not translate to "base de código") +* default: por defecto (do not translate to "predeterminado") +* default values: valores por defecto (do not translate to "valores predeterminados") +* media type: media type (do not translate to "tipo de medio") +* instantiate: crear un instance (do not translate to "instanciar") +* OAuth2 Scopes: Scopes de OAuth2 (do not translate to "Alcances de OAuth2") +* on the fly: sobre la marcha (do not translate to "al vuelo") +* terminal: terminal (femenine, as in "la terminal") +* terminals: terminales (plural femenine, as in "las terminales") +* lifespan: lifespan (do not translate to "vida útil" or "tiempo de vida") +* unload: quitar de memoria (do not translate to "descargar") +* mount (noun): mount (do not translate to "montura") +* mount (verb): montar +* statement (as in code statement): statement (do not translate to "declaración" or "sentencia") +* worker process: worker process (do not translate to "proceso trabajador" or "proceso de trabajo") +* worker processes: worker processes (do not translate to "procesos trabajadores" or "procesos de trabajo") +* worker: worker (do not translate to "trabajador") +* load balancer: load balancer (do not translate to "balanceador de carga") +* load balance: load balance (do not translate to "balancear carga") +* self hosting: self hosting (do not translate to "auto alojamiento") diff --git a/requirements-translations.txt b/requirements-translations.txt new file mode 100644 index 000000000..a8f8a02d7 --- /dev/null +++ b/requirements-translations.txt @@ -0,0 +1 @@ +pydantic-ai==0.0.15 diff --git a/scripts/translate.py b/scripts/translate.py new file mode 100644 index 000000000..ce11b3877 --- /dev/null +++ b/scripts/translate.py @@ -0,0 +1,162 @@ +from functools import lru_cache +from pathlib import Path +from typing import Iterable + +import typer +import yaml +from pydantic_ai import Agent + +non_translated_sections = ( + "reference/", + "release-notes.md", + "fastapi-people.md", + "external-links.md", + "newsletter.md", + "management-tasks.md", + "management.md", + "contributing.md", +) + + +general_prompt = """ +For technical terms in English that don't have a common translation term use the original term in English. + +For code snippets or fragments, surrounded by backticks (`), don't translate the content, keep the original in English. For example, `list`, `dict`, keep them as is. + +The content is written in markdown, write the translation in markdown as well. Don't add triple backticks (`) around the generated translation content. + +When there's an example of code, the console or a terminal, normally surrounded by triple backticks and a keyword like "console" or "bash" (e.g. ```console), do not translate the content, keep the original in English. + +The original content will be surrounded by triple percentage signs (%) and you should translate it to the target language. Do not include the triple percentage signs in the translation. +""" + + +@lru_cache +def get_langs() -> dict[str, str]: + return yaml.safe_load(Path("docs/language_names.yml").read_text()) + + +def generate_lang_path(*, lang: str, path: Path) -> Path: + en_docs_path = Path("docs/en/docs") + assert str(path).startswith( + str(en_docs_path) + ), f"Path must be inside {en_docs_path}" + lang_docs_path = Path(f"docs/{lang}/docs") + out_path = Path(str(path).replace(str(en_docs_path), str(lang_docs_path))) + return out_path + + +def translate_page(*, lang: str, path: Path) -> None: + langs = get_langs() + language = langs[lang] + lang_path = Path(f"docs/{lang}") + lang_path.mkdir(exist_ok=True) + lang_prompt_path = lang_path / "llm-prompt.md" + assert lang_prompt_path.exists(), f"Prompt file not found: {lang_prompt_path}" + lang_prompt_content = lang_prompt_path.read_text() + + en_docs_path = Path("docs/en/docs") + assert str(path).startswith( + str(en_docs_path) + ), f"Path must be inside {en_docs_path}" + out_path = generate_lang_path(lang=lang, path=path) + out_path.parent.mkdir(parents=True, exist_ok=True) + original_content = path.read_text() + old_translation: str | None = None + if out_path.exists(): + old_translation = out_path.read_text() + agent = Agent("openai:gpt-4o") + + prompt_segments = [ + lang_prompt_content, + general_prompt, + ] + if old_translation: + prompt_segments.extend( + [ + "There's an existing previous translation for this content that is probably outdated with old content or old instructions.", + "Update the translation given your current instructions and the original content.", + "If you have instructions to translate specific terms or phrases in a specific way, please follow those instructions instead of keeping the old and outdated content.", + "Previous translation:", + f"%%%\n{old_translation}%%%", + ] + ) + prompt_segments.extend( + [ + f"Translate to {language} ({lang}).", + "Original content:", + f"%%%\n{original_content}%%%", + ] + ) + prompt = "\n\n".join(prompt_segments) + + result = agent.run_sync(prompt) + out_content = f"{result.data.strip()}\n" + out_path.write_text(out_content) + + +def iter_paths_to_translate() -> Iterable[Path]: + """ + Iterate on the markdown files to translate in order of priority. + """ + first_dirs = [ + Path("docs/en/docs/learn"), + Path("docs/en/docs/tutorial"), + Path("docs/en/docs/advanced"), + Path("docs/en/docs/about"), + Path("docs/en/docs/how-to"), + ] + first_parent = Path("docs/en/docs") + yield from first_parent.glob("*.md") + for dir_path in first_dirs: + yield from dir_path.rglob("*.md") + first_dirs_str = tuple(str(d) for d in first_dirs) + for path in Path("docs/en/docs").rglob("*.md"): + if str(path).startswith(first_dirs_str): + continue + if path.parent == first_parent: + continue + yield path + + +def translate_all(lang: str) -> None: + paths_to_process: list[Path] = [] + for path in iter_paths_to_translate(): + if str(path).replace("docs/en/docs/", "").startswith(non_translated_sections): + continue + paths_to_process.append(path) + print("Original paths:") + for p in paths_to_process: + print(f" - {p}") + print(f"Total original paths: {len(paths_to_process)}") + missing_paths: list[Path] = [] + skipped_paths: list[Path] = [] + for p in paths_to_process: + lang_path = generate_lang_path(lang=lang, path=p) + if lang_path.exists(): + skipped_paths.append(p) + continue + missing_paths.append(p) + print("Paths to skip:") + for p in skipped_paths: + print(f" - {p}") + print(f"Total paths to skip: {len(skipped_paths)}") + print("Paths to process:") + for p in missing_paths: + print(f" - {p}") + print(f"Total paths to process: {len(missing_paths)}") + for p in missing_paths: + print(f"Translating: {p}") + translate_page(lang="es", path=p) + print(f"Done translating: {p}") + + +def main(*, lang: str, path: Path = None) -> None: + if path: + translate_page(lang=lang, path=path) + else: + translate_all(lang=lang) + + +if __name__ == "__main__": + typer.run(main) From d4b6f1d1f656243ed2bcdbc2bd235bbf53073938 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 30 Dec 2024 18:47:07 +0000 Subject: [PATCH 607/932] =?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 [skip ci] --- 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 e7e297af4..e04dae9c4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -61,6 +61,7 @@ hide: ### Internal +* 🔨 Add internal scripts to generate language translations with PydanticAI, include Spanish prompt. PR [#13123](https://github.com/fastapi/fastapi/pull/13123) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump astral-sh/setup-uv from 4 to 5. PR [#13096](https://github.com/fastapi/fastapi/pull/13096) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Update sponsors: rename CryptAPI to BlockBee. PR [#13078](https://github.com/fastapi/fastapi/pull/13078) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump pypa/gh-action-pypi-publish from 1.12.2 to 1.12.3. PR [#13055](https://github.com/fastapi/fastapi/pull/13055) by [@dependabot[bot]](https://github.com/apps/dependabot). From db9da09f725831d75a0c3f632a64c0624d483204 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 30 Dec 2024 18:59:59 +0000 Subject: [PATCH 608/932] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20typo=20in=20?= =?UTF-8?q?`docs/en/docs/virtual-environments.md`=20(#13124)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/virtual-environments.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/virtual-environments.md b/docs/en/docs/virtual-environments.md index fcc72fbe7..b75be18c3 100644 --- a/docs/en/docs/virtual-environments.md +++ b/docs/en/docs/virtual-environments.md @@ -748,7 +748,7 @@ C:\Users\user\code\awesome-project\.venv\Scripts\python That means that the `python` program that will be used is the one **in the virtual environment**. -you use `which` in Linux and macOS and `Get-Command` in Windows PowerShell. +You use `which` in Linux and macOS and `Get-Command` in Windows PowerShell. The way that command works is that it will go and check in the `PATH` environment variable, going through **each path in order**, looking for the program called `python`. Once it finds it, it will **show you the path** to that program. From 1d50bad4555b951d5fa48eb8787fd5c39ed7effb Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 30 Dec 2024 19:00:23 +0000 Subject: [PATCH 609/932] =?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 [skip ci] --- 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 e04dae9c4..7d999e4ba 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏️ Fix typo in `docs/en/docs/virtual-environments.md`. PR [#13124](https://github.com/fastapi/fastapi/pull/13124) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix error in `docs/en/docs/contributing.md`. PR [#12899](https://github.com/fastapi/fastapi/pull/12899) by [@kingsubin](https://github.com/kingsubin). * 📝 Minor corrections in `docs/en/docs/tutorial/sql-databases.md`. PR [#13081](https://github.com/fastapi/fastapi/pull/13081) by [@alv2017](https://github.com/alv2017). * 📝 Update includes in `docs/ru/docs/tutorial/query-param-models.md`. PR [#12994](https://github.com/fastapi/fastapi/pull/12994) by [@alejsdev](https://github.com/alejsdev). From 324c3ba095d11be65cf98cb4b821b0c530625b67 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 1 Jan 2025 17:18:26 +0000 Subject: [PATCH 610/932] =?UTF-8?q?=E2=AC=86=20Bump=20mkdocs-macros-plugin?= =?UTF-8?q?=20from=201.0.5=20to=201.3.7=20(#13133)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [mkdocs-macros-plugin](https://github.com/fralau/mkdocs_macros_plugin) from 1.0.5 to 1.3.7. - [Release notes](https://github.com/fralau/mkdocs_macros_plugin/releases) - [Changelog](https://github.com/fralau/mkdocs-macros-plugin/blob/master/CHANGELOG.md) - [Commits](https://github.com/fralau/mkdocs_macros_plugin/compare/v1.0.5...v1.3.7) --- updated-dependencies: - dependency-name: mkdocs-macros-plugin dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs.txt b/requirements-docs.txt index bb11f01c6..fc1259e55 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -15,5 +15,5 @@ mkdocstrings[python]==0.26.1 griffe-typingdoc==0.2.7 # For griffe, it formats with black black==24.10.0 -mkdocs-macros-plugin==1.0.5 +mkdocs-macros-plugin==1.3.7 markdown-include-variants==0.0.3 From 05b62724e07b2b5e80411439121b9acb87e5aaf0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 1 Jan 2025 17:18:48 +0000 Subject: [PATCH 611/932] =?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 [skip ci] --- 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 7d999e4ba..1b9284a35 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -62,6 +62,7 @@ hide: ### Internal +* ⬆ Bump mkdocs-macros-plugin from 1.0.5 to 1.3.7. PR [#13133](https://github.com/fastapi/fastapi/pull/13133) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔨 Add internal scripts to generate language translations with PydanticAI, include Spanish prompt. PR [#13123](https://github.com/fastapi/fastapi/pull/13123) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump astral-sh/setup-uv from 4 to 5. PR [#13096](https://github.com/fastapi/fastapi/pull/13096) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Update sponsors: rename CryptAPI to BlockBee. PR [#13078](https://github.com/fastapi/fastapi/pull/13078) by [@tiangolo](https://github.com/tiangolo). From 55ba3220f85493a006e35ad518b699157dd524a6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 1 Jan 2025 17:19:08 +0000 Subject: [PATCH 612/932] =?UTF-8?q?=E2=AC=86=20Bump=20inline-snapshot=20fr?= =?UTF-8?q?om=200.14.0=20to=200.18.1=20(#13132)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [inline-snapshot](https://github.com/15r10nk/inline-snapshot) from 0.14.0 to 0.18.1. - [Release notes](https://github.com/15r10nk/inline-snapshot/releases) - [Changelog](https://github.com/15r10nk/inline-snapshot/blob/main/CHANGELOG.md) - [Commits](https://github.com/15r10nk/inline-snapshot/compare/v0.14.0...0.18.1) --- updated-dependencies: - dependency-name: inline-snapshot dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-tests.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-tests.txt b/requirements-tests.txt index b607998a3..5be052307 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -10,7 +10,7 @@ anyio[trio] >=3.2.1,<4.0.0 PyJWT==2.8.0 pyyaml >=5.3.1,<7.0.0 passlib[bcrypt] >=1.7.2,<2.0.0 -inline-snapshot==0.14.0 +inline-snapshot==0.18.1 # types types-ujson ==5.10.0.20240515 types-orjson ==3.6.2 From ad294d4d1ed650cf0a0cfd8d3a550b4c83c9e47b Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 1 Jan 2025 17:19:34 +0000 Subject: [PATCH 613/932] =?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 [skip ci] --- 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 1b9284a35..d39e15e9c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -62,6 +62,7 @@ hide: ### Internal +* ⬆ Bump inline-snapshot from 0.14.0 to 0.18.1. PR [#13132](https://github.com/fastapi/fastapi/pull/13132) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump mkdocs-macros-plugin from 1.0.5 to 1.3.7. PR [#13133](https://github.com/fastapi/fastapi/pull/13133) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔨 Add internal scripts to generate language translations with PydanticAI, include Spanish prompt. PR [#13123](https://github.com/fastapi/fastapi/pull/13123) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump astral-sh/setup-uv from 4 to 5. PR [#13096](https://github.com/fastapi/fastapi/pull/13096) by [@dependabot[bot]](https://github.com/apps/dependabot). From 274d3d9bd07a3d8c30f1e6f339f3612225263251 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 1 Jan 2025 17:26:52 +0000 Subject: [PATCH 614/932] =?UTF-8?q?=E2=AC=86=20Bump=20markdown-include-var?= =?UTF-8?q?iants=20from=200.0.3=20to=200.0.4=20(#13129)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [markdown-include-variants](https://github.com/tiangolo/markdown-include-variants) from 0.0.3 to 0.0.4. - [Release notes](https://github.com/tiangolo/markdown-include-variants/releases) - [Changelog](https://github.com/tiangolo/markdown-include-variants/blob/main/release-notes.md) - [Commits](https://github.com/tiangolo/markdown-include-variants/compare/0.0.3...0.0.4) --- updated-dependencies: - dependency-name: markdown-include-variants dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs.txt b/requirements-docs.txt index fc1259e55..6f391675a 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -16,4 +16,4 @@ griffe-typingdoc==0.2.7 # For griffe, it formats with black black==24.10.0 mkdocs-macros-plugin==1.3.7 -markdown-include-variants==0.0.3 +markdown-include-variants==0.0.4 From dd649ff81464e5c3a2dd25b092f30c424db7586c Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 1 Jan 2025 17:27:23 +0000 Subject: [PATCH 615/932] =?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 [skip ci] --- 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 d39e15e9c..5a7f3b8f7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -62,6 +62,7 @@ hide: ### Internal +* ⬆ Bump markdown-include-variants from 0.0.3 to 0.0.4. PR [#13129](https://github.com/fastapi/fastapi/pull/13129) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump inline-snapshot from 0.14.0 to 0.18.1. PR [#13132](https://github.com/fastapi/fastapi/pull/13132) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump mkdocs-macros-plugin from 1.0.5 to 1.3.7. PR [#13133](https://github.com/fastapi/fastapi/pull/13133) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔨 Add internal scripts to generate language translations with PydanticAI, include Spanish prompt. PR [#13123](https://github.com/fastapi/fastapi/pull/13123) by [@tiangolo](https://github.com/tiangolo). From b59885c9d5692613db145965c72042070fdcfa94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 2 Jan 2025 17:03:21 +0000 Subject: [PATCH 616/932] =?UTF-8?q?=F0=9F=91=B7=20Add=20new=20GitHub=20Act?= =?UTF-8?q?ion=20to=20update=20contributors,=20translators,=20and=20transl?= =?UTF-8?q?ation=20reviewers=20(#13136)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/contributors.yml | 53 +++++ docs/en/data/contributors.yml | 0 docs/en/data/skip_users.yml | 5 + docs/en/data/translation_reviewers.yml | 0 docs/en/data/translators.yml | 0 docs/en/docs/fastapi-people.md | 56 +++-- docs/en/mkdocs.yml | 4 + requirements-github-actions.txt | 1 + scripts/contributors.py | 315 +++++++++++++++++++++++++ 9 files changed, 413 insertions(+), 21 deletions(-) create mode 100644 .github/workflows/contributors.yml create mode 100644 docs/en/data/contributors.yml create mode 100644 docs/en/data/skip_users.yml create mode 100644 docs/en/data/translation_reviewers.yml create mode 100644 docs/en/data/translators.yml create mode 100644 scripts/contributors.py diff --git a/.github/workflows/contributors.yml b/.github/workflows/contributors.yml new file mode 100644 index 000000000..87abfe3a1 --- /dev/null +++ b/.github/workflows/contributors.yml @@ -0,0 +1,53 @@ +name: FastAPI People Contributors + +on: + schedule: + - cron: "0 3 1 * *" + workflow_dispatch: + inputs: + debug_enabled: + description: "Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)" + required: false + default: "false" + +env: + UV_SYSTEM_PYTHON: 1 + +jobs: + job: + if: github.repository_owner == 'fastapi' + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Setup uv + uses: astral-sh/setup-uv@v5 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - name: Install Dependencies + run: uv pip install -r requirements-github-actions.txt + # Allow debugging with tmate + - name: Setup tmate session + uses: mxschmitt/action-tmate@v3 + if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} + with: + limit-access-to-actor: true + env: + GITHUB_TOKEN: ${{ secrets.FASTAPI_PR_TOKEN }} + - name: FastAPI People Contributors + run: python ./scripts/contributors.py + env: + GITHUB_TOKEN: ${{ secrets.FASTAPI_PR_TOKEN }} diff --git a/docs/en/data/contributors.yml b/docs/en/data/contributors.yml new file mode 100644 index 000000000..e69de29bb diff --git a/docs/en/data/skip_users.yml b/docs/en/data/skip_users.yml new file mode 100644 index 000000000..cf24003af --- /dev/null +++ b/docs/en/data/skip_users.yml @@ -0,0 +1,5 @@ +- tiangolo +- codecov +- github-actions +- pre-commit-ci +- dependabot diff --git a/docs/en/data/translation_reviewers.yml b/docs/en/data/translation_reviewers.yml new file mode 100644 index 000000000..e69de29bb diff --git a/docs/en/data/translators.yml b/docs/en/data/translators.yml new file mode 100644 index 000000000..e69de29bb diff --git a/docs/en/docs/fastapi-people.md b/docs/en/docs/fastapi-people.md index bf7954449..ffc579b10 100644 --- a/docs/en/docs/fastapi-people.md +++ b/docs/en/docs/fastapi-people.md @@ -13,15 +13,13 @@ Hey! 👋 This is me: -{% if people %}
{% for user in people.maintainers %} -
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
+
@{{ contributors.tiangolo.login }}
Answers: {{ user.answers }}
Pull Requests: {{ contributors.tiangolo.count }}
{% endfor %}
-{% endif %} I'm the creator of **FastAPI**. You can read more about that in [Help FastAPI - Get Help - Connect with the author](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. @@ -84,7 +82,6 @@ You can see the **FastAPI Experts** for: These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last month. 🤓 -{% if people %}
{% for user in people.last_month_experts[:10] %} @@ -92,13 +89,11 @@ These are the users that have been [helping others the most with questions in Gi {% endfor %}
-{% endif %} ### FastAPI Experts - 3 Months These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last 3 months. 😎 -{% if people %}
{% for user in people.three_months_experts[:10] %} @@ -106,13 +101,11 @@ These are the users that have been [helping others the most with questions in Gi {% endfor %}
-{% endif %} ### FastAPI Experts - 6 Months These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last 6 months. 🧐 -{% if people %}
{% for user in people.six_months_experts[:10] %} @@ -120,13 +113,11 @@ These are the users that have been [helping others the most with questions in Gi {% endfor %}
-{% endif %} ### FastAPI Experts - 1 Year These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last year. 🧑‍🔬 -{% if people %}
{% for user in people.one_year_experts[:20] %} @@ -134,7 +125,6 @@ These are the users that have been [helping others the most with questions in Gi {% endfor %}
-{% endif %} ### FastAPI Experts - All Time @@ -142,7 +132,6 @@ Here are the all time **FastAPI Experts**. 🤓🤯 These are the users that have [helped others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} through *all time*. 🧙 -{% if people %}
{% for user in people.experts[:50] %} @@ -150,7 +139,6 @@ These are the users that have [helped others the most with questions in GitHub]( {% endfor %}
-{% endif %} ## Top Contributors @@ -158,19 +146,42 @@ Here are the **Top Contributors**. 👷 These users have [created the most Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} that have been *merged*. -They have contributed source code, documentation, translations, etc. 📦 +They have contributed source code, documentation, etc. 📦 -{% if people %}
-{% for user in people.top_contributors[:50] %} +{% for user in (contributors.values() | list)[:50] %} + +{% if user.login not in skip_users %}
@{{ user.login }}
Pull Requests: {{ user.count }}
+ +{% endif %} + {% endfor %}
+ +There are hundreds of other contributors, you can see them all in the FastAPI GitHub Contributors page. 👷 + +## Top Translators + +These are the **Top Translators**. 🌐 + +These users have created the most Pull Requests with [translations to other languages](contributing.md#translations){.internal-link target=_blank} that have been *merged*. + +
+ +{% for user in (translators.values() | list)[:50] %} + +{% if user.login not in skip_users %} + +
@{{ user.login }}
Translations: {{ user.count }}
+ {% endif %} -There are many other contributors (more than a hundred), you can see them all in the FastAPI GitHub Contributors page. 👷 +{% endfor %} + +
## Top Translation Reviewers @@ -178,15 +189,18 @@ These users are the **Top Translation Reviewers**. 🕵️ I only speak a few languages (and not very well 😅). So, the reviewers are the ones that have the [**power to approve translations**](contributing.md#translations){.internal-link target=_blank} of the documentation. Without them, there wouldn't be documentation in several other languages. -{% if people %}
-{% for user in people.top_translations_reviewers[:50] %} +{% for user in (translation_reviewers.values() | list)[:50] %} + +{% if user.login not in skip_users %}
@{{ user.login }}
Reviews: {{ user.count }}
+ +{% endif %} + {% endfor %}
-{% endif %} ## Sponsors @@ -251,7 +265,7 @@ The main intention of this page is to highlight the effort of the community to h Especially including efforts that are normally less visible, and in many cases more arduous, like helping others with questions and reviewing Pull Requests with translations. -The data is calculated each month, you can read the source code here. +The data is calculated each month, you can read the source code here. Here I'm also highlighting contributions from sponsors. diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 6443b290a..f2abf7f6b 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -65,6 +65,10 @@ plugins: - external_links: ../en/data/external_links.yml - github_sponsors: ../en/data/github_sponsors.yml - people: ../en/data/people.yml + - contributors: ../en/data/contributors.yml + - translators: ../en/data/translators.yml + - translation_reviewers: ../en/data/translation_reviewers.yml + - skip_users: ../en/data/skip_users.yml - members: ../en/data/members.yml - sponsors_badge: ../en/data/sponsors_badge.yml - sponsors: ../en/data/sponsors.yml diff --git a/requirements-github-actions.txt b/requirements-github-actions.txt index a6dace544..920aefea6 100644 --- a/requirements-github-actions.txt +++ b/requirements-github-actions.txt @@ -2,4 +2,5 @@ PyGithub>=2.3.0,<3.0.0 pydantic>=2.5.3,<3.0.0 pydantic-settings>=2.1.0,<3.0.0 httpx>=0.27.0,<0.28.0 +pyyaml >=5.3.1,<7.0.0 smokeshow diff --git a/scripts/contributors.py b/scripts/contributors.py new file mode 100644 index 000000000..251558de7 --- /dev/null +++ b/scripts/contributors.py @@ -0,0 +1,315 @@ +import logging +import secrets +import subprocess +from collections import Counter +from datetime import datetime +from pathlib import Path +from typing import Any + +import httpx +import yaml +from github import Github +from pydantic import BaseModel, SecretStr +from pydantic_settings import BaseSettings + +github_graphql_url = "https://api.github.com/graphql" + + +prs_query = """ +query Q($after: String) { + repository(name: "fastapi", owner: "fastapi") { + pullRequests(first: 100, after: $after) { + edges { + cursor + node { + number + labels(first: 100) { + nodes { + name + } + } + author { + login + avatarUrl + url + } + title + createdAt + lastEditedAt + updatedAt + state + reviews(first:100) { + nodes { + author { + login + avatarUrl + url + } + state + } + } + } + } + } + } +} +""" + + +class Author(BaseModel): + login: str + avatarUrl: str + url: str + + +class LabelNode(BaseModel): + name: str + + +class Labels(BaseModel): + nodes: list[LabelNode] + + +class ReviewNode(BaseModel): + author: Author | None = None + state: str + + +class Reviews(BaseModel): + nodes: list[ReviewNode] + + +class PullRequestNode(BaseModel): + number: int + labels: Labels + author: Author | None = None + title: str + createdAt: datetime + lastEditedAt: datetime | None = None + updatedAt: datetime | None = None + state: str + reviews: Reviews + + +class PullRequestEdge(BaseModel): + cursor: str + node: PullRequestNode + + +class PullRequests(BaseModel): + edges: list[PullRequestEdge] + + +class PRsRepository(BaseModel): + pullRequests: PullRequests + + +class PRsResponseData(BaseModel): + repository: PRsRepository + + +class PRsResponse(BaseModel): + data: PRsResponseData + + +class Settings(BaseSettings): + github_token: SecretStr + github_repository: str + httpx_timeout: int = 30 + + +def get_graphql_response( + *, + settings: Settings, + query: str, + after: str | None = None, +) -> dict[str, Any]: + headers = {"Authorization": f"token {settings.github_token.get_secret_value()}"} + variables = {"after": after} + response = httpx.post( + github_graphql_url, + headers=headers, + timeout=settings.httpx_timeout, + json={"query": query, "variables": variables, "operationName": "Q"}, + ) + if response.status_code != 200: + logging.error(f"Response was not 200, after: {after}") + logging.error(response.text) + raise RuntimeError(response.text) + data = response.json() + if "errors" in data: + logging.error(f"Errors in response, after: {after}") + logging.error(data["errors"]) + logging.error(response.text) + raise RuntimeError(response.text) + return data + + +def get_graphql_pr_edges( + *, settings: Settings, after: str | None = None +) -> list[PullRequestEdge]: + data = get_graphql_response(settings=settings, query=prs_query, after=after) + graphql_response = PRsResponse.model_validate(data) + return graphql_response.data.repository.pullRequests.edges + + +def get_pr_nodes(settings: Settings) -> list[PullRequestNode]: + pr_nodes: list[PullRequestNode] = [] + pr_edges = get_graphql_pr_edges(settings=settings) + + while pr_edges: + for edge in pr_edges: + pr_nodes.append(edge.node) + last_edge = pr_edges[-1] + pr_edges = get_graphql_pr_edges(settings=settings, after=last_edge.cursor) + return pr_nodes + + +class ContributorsResults(BaseModel): + contributors: Counter[str] + translation_reviewers: Counter[str] + translators: Counter[str] + authors: dict[str, Author] + + +def get_contributors(pr_nodes: list[PullRequestNode]) -> ContributorsResults: + contributors = Counter[str]() + translation_reviewers = Counter[str]() + translators = Counter[str]() + authors: dict[str, Author] = {} + + for pr in pr_nodes: + if pr.author: + authors[pr.author.login] = pr.author + is_lang = False + for label in pr.labels.nodes: + if label.name == "lang-all": + is_lang = True + break + for review in pr.reviews.nodes: + if review.author: + authors[review.author.login] = review.author + if is_lang: + translation_reviewers[review.author.login] += 1 + if pr.state == "MERGED" and pr.author: + if is_lang: + translators[pr.author.login] += 1 + else: + contributors[pr.author.login] += 1 + return ContributorsResults( + contributors=contributors, + translation_reviewers=translation_reviewers, + translators=translators, + authors=authors, + ) + + +def get_users_to_write( + *, + counter: Counter[str], + authors: dict[str, Author], + min_count: int = 2, +) -> dict[str, Any]: + users: dict[str, Any] = {} + for user, count in counter.most_common(): + if count >= min_count: + author = authors[user] + users[user] = { + "login": user, + "count": count, + "avatarUrl": author.avatarUrl, + "url": author.url, + } + return users + + +def update_content(*, content_path: Path, new_content: Any) -> bool: + old_content = content_path.read_text(encoding="utf-8") + + new_content = yaml.dump(new_content, sort_keys=False, width=200, allow_unicode=True) + if old_content == new_content: + logging.info(f"The content hasn't changed for {content_path}") + return False + content_path.write_text(new_content, encoding="utf-8") + logging.info(f"Updated {content_path}") + return True + + +def main() -> None: + logging.basicConfig(level=logging.INFO) + settings = Settings() + logging.info(f"Using config: {settings.model_dump_json()}") + g = Github(settings.github_token.get_secret_value()) + repo = g.get_repo(settings.github_repository) + + pr_nodes = get_pr_nodes(settings=settings) + contributors_results = get_contributors(pr_nodes=pr_nodes) + authors = contributors_results.authors + + top_contributors = get_users_to_write( + counter=contributors_results.contributors, + authors=authors, + ) + + top_translators = get_users_to_write( + counter=contributors_results.translators, + authors=authors, + ) + top_translations_reviewers = get_users_to_write( + counter=contributors_results.translation_reviewers, + authors=authors, + ) + + # For local development + # contributors_path = Path("../docs/en/data/contributors.yml") + contributors_path = Path("./docs/en/data/contributors.yml") + # translators_path = Path("../docs/en/data/translators.yml") + translators_path = Path("./docs/en/data/translators.yml") + # translation_reviewers_path = Path("../docs/en/data/translation_reviewers.yml") + translation_reviewers_path = Path("./docs/en/data/translation_reviewers.yml") + + updated = [ + update_content(content_path=contributors_path, new_content=top_contributors), + update_content(content_path=translators_path, new_content=top_translators), + update_content( + content_path=translation_reviewers_path, + new_content=top_translations_reviewers, + ), + ] + + if not any(updated): + logging.info("The data hasn't changed, finishing.") + return + + logging.info("Setting up GitHub Actions git user") + subprocess.run(["git", "config", "user.name", "github-actions"], check=True) + subprocess.run( + ["git", "config", "user.email", "github-actions@github.com"], check=True + ) + branch_name = f"fastapi-people-contributors-{secrets.token_hex(4)}" + logging.info(f"Creating a new branch {branch_name}") + subprocess.run(["git", "checkout", "-b", branch_name], check=True) + logging.info("Adding updated file") + subprocess.run( + [ + "git", + "add", + str(contributors_path), + str(translators_path), + str(translation_reviewers_path), + ], + check=True, + ) + logging.info("Committing updated file") + message = "👥 Update FastAPI People - Contributors and Translators" + subprocess.run(["git", "commit", "-m", message], check=True) + logging.info("Pushing branch") + subprocess.run(["git", "push", "origin", branch_name], check=True) + logging.info("Creating PR") + pr = repo.create_pull(title=message, body=message, base="master", head=branch_name) + logging.info(f"Created PR: {pr.number}") + logging.info("Finished") + + +if __name__ == "__main__": + main() From af7db9b95d9f33cee42b111000ded55317404b93 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 2 Jan 2025 17:03:46 +0000 Subject: [PATCH 617/932] =?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 [skip ci] --- 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 5a7f3b8f7..2efe67ff8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 👷 Add new GitHub Action to update contributors, translators, and translation reviewers. PR [#13136](https://github.com/fastapi/fastapi/pull/13136) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix typo in `docs/en/docs/virtual-environments.md`. PR [#13124](https://github.com/fastapi/fastapi/pull/13124) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix error in `docs/en/docs/contributing.md`. PR [#12899](https://github.com/fastapi/fastapi/pull/12899) by [@kingsubin](https://github.com/kingsubin). * 📝 Minor corrections in `docs/en/docs/tutorial/sql-databases.md`. PR [#13081](https://github.com/fastapi/fastapi/pull/13081) by [@alv2017](https://github.com/alv2017). From 2d210f7313d85ef63d150593e765281667dadd55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 2 Jan 2025 17:22:30 +0000 Subject: [PATCH 618/932] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e=20-=20Contributors=20and=20Translators=20(#13145)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions --- docs/en/data/contributors.yml | 505 ++++++++ docs/en/data/translation_reviewers.yml | 1645 ++++++++++++++++++++++++ docs/en/data/translators.yml | 490 +++++++ 3 files changed, 2640 insertions(+) diff --git a/docs/en/data/contributors.yml b/docs/en/data/contributors.yml index e69de29bb..f679d7286 100644 --- a/docs/en/data/contributors.yml +++ b/docs/en/data/contributors.yml @@ -0,0 +1,505 @@ +tiangolo: + login: tiangolo + count: 697 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo +dependabot: + login: dependabot + count: 89 + avatarUrl: https://avatars.githubusercontent.com/in/29110?v=4 + url: https://github.com/apps/dependabot +github-actions: + login: github-actions + count: 26 + avatarUrl: https://avatars.githubusercontent.com/in/15368?v=4 + url: https://github.com/apps/github-actions +Kludex: + login: Kludex + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 + url: https://github.com/Kludex +pre-commit-ci: + login: pre-commit-ci + count: 22 + avatarUrl: https://avatars.githubusercontent.com/in/68672?v=4 + url: https://github.com/apps/pre-commit-ci +alejsdev: + login: alejsdev + count: 21 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 + url: https://github.com/alejsdev +dmontagu: + login: dmontagu + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 + url: https://github.com/dmontagu +euri10: + login: euri10 + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/1104190?u=321a2e953e6645a7d09b732786c7a8061e0f8a8b&v=4 + url: https://github.com/euri10 +kantandane: + login: kantandane + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/3978368?u=cccc199291f991a73b1ebba5abc735a948e0bd16&v=4 + url: https://github.com/kantandane +nilslindemann: + login: nilslindemann + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 + url: https://github.com/nilslindemann +zhaohan-dong: + login: zhaohan-dong + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/65422392?u=8260f8781f50248410ebfa4c9bf70e143fe5c9f2&v=4 + url: https://github.com/zhaohan-dong +mariacamilagl: + login: mariacamilagl + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 + url: https://github.com/mariacamilagl +handabaldeep: + login: handabaldeep + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/12239103?u=6c39ef15d14c6d5211f5dd775cc4842f8d7f2f3a&v=4 + url: https://github.com/handabaldeep +vishnuvskvkl: + login: vishnuvskvkl + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/84698110?u=8af5de0520dd4fa195f53c2850a26f57c0f6bc64&v=4 + url: https://github.com/vishnuvskvkl +alissadb: + login: alissadb + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/96190409?u=be42d85938c241be781505a5a872575be28b2906&v=4 + url: https://github.com/alissadb +wshayes: + login: wshayes + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 + url: https://github.com/wshayes +samuelcolvin: + login: samuelcolvin + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/4039449?u=42eb3b833047c8c4b4f647a031eaef148c16d93f&v=4 + url: https://github.com/samuelcolvin +waynerv: + login: waynerv + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 + url: https://github.com/waynerv +svlandeg: + login: svlandeg + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 + url: https://github.com/svlandeg +krishnamadhavan: + login: krishnamadhavan + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/31798870?u=950693b28f3ae01105fd545c046e46ca3d31ab06&v=4 + url: https://github.com/krishnamadhavan +jekirl: + login: jekirl + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/2546697?u=a027452387d85bd4a14834e19d716c99255fb3b7&v=4 + url: https://github.com/jekirl +hitrust: + login: hitrust + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/3360631?u=5fa1f475ad784d64eb9666bdd43cc4d285dcc773&v=4 + url: https://github.com/hitrust +adriangb: + login: adriangb + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 + url: https://github.com/adriangb +iudeen: + login: iudeen + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen +philipokiokio: + login: philipokiokio + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/55271518?u=d30994d339aaaf1f6bf1b8fc810132016fbd4fdc&v=4 + url: https://github.com/philipokiokio +AlexWendland: + login: AlexWendland + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/3949212?u=c4c0c615e0ea33d00bfe16b779cf6ebc0f58071c&v=4 + url: https://github.com/AlexWendland +divums: + login: divums + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/1397556?v=4 + url: https://github.com/divums +prostomarkeloff: + login: prostomarkeloff + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/28061158?u=6918e39a1224194ba636e897461a02a20126d7ad&v=4 + url: https://github.com/prostomarkeloff +nsidnev: + login: nsidnev + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4 + url: https://github.com/nsidnev +pawamoy: + login: pawamoy + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4 + url: https://github.com/pawamoy +patrickmckenna: + login: patrickmckenna + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/3589536?u=53aef07250d226d35e526768e26891964907b41a&v=4 + url: https://github.com/patrickmckenna +hukkin: + login: hukkin + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/3275109?u=77bb83759127965eacbfe67e2ca983066e964fde&v=4 + url: https://github.com/hukkin +marcosmmb: + login: marcosmmb + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/6181089?u=b8567a842b38c5570c315b2b7ca766fa7be6721e&v=4 + url: https://github.com/marcosmmb +Serrones: + login: Serrones + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/22691749?u=4795b880e13ca33a73e52fc0ef7dc9c60c8fce47&v=4 + url: https://github.com/Serrones +uriyyo: + login: uriyyo + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/32038156?u=a27b65a9ec3420586a827a0facccbb8b6df1ffb3&v=4 + url: https://github.com/uriyyo +amacfie: + login: amacfie + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 + url: https://github.com/amacfie +rkbeatss: + login: rkbeatss + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/23391143?u=56ab6bff50be950fa8cae5cf736f2ae66e319ff3&v=4 + url: https://github.com/rkbeatss +asheux: + login: asheux + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/22955146?u=4553ebf5b5a7c7fe031a46182083aa224faba2e1&v=4 + url: https://github.com/asheux +n25a: + login: n25a + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/49960770?u=7d8a6d5f0a75a5e9a865a2527edfd48895ea27ae&v=4 + url: https://github.com/n25a +ghandic: + login: ghandic + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/23500353?u=e2e1d736f924d9be81e8bfc565b6d8836ba99773&v=4 + url: https://github.com/ghandic +TeoZosa: + login: TeoZosa + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/13070236?u=96fdae85800ef85dcfcc4b5f8281dc8778c8cb7d&v=4 + url: https://github.com/TeoZosa +graingert: + login: graingert + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/413772?u=64b77b6aa405c68a9c6bcf45f84257c66eea5f32&v=4 + url: https://github.com/graingert +ShahriyarR: + login: ShahriyarR + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/3852029?u=c9a1691e5ebdc94cbf543086099a6ed705cdb873&v=4 + url: https://github.com/ShahriyarR +jaystone776: + login: jaystone776 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/11191137?u=299205a95e9b6817a43144a48b643346a5aac5cc&v=4 + url: https://github.com/jaystone776 +zanieb: + login: zanieb + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/2586601?u=e5c86f7ff3b859e7e183187ac2b17fd6ee32b3ab&v=4 + url: https://github.com/zanieb +MicaelJarniac: + login: MicaelJarniac + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/19514231?u=158c91874ea98d6e9e6f0c6db37ee2ce60c55ff2&v=4 + url: https://github.com/MicaelJarniac +papb: + login: papb + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/20914054?u=890511fae7ea90d887e2a65ce44a1775abba38d5&v=4 + url: https://github.com/papb +gitworkflows: + login: gitworkflows + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/118260833?v=4 + url: https://github.com/gitworkflows +Nimitha-jagadeesha: + login: Nimitha-jagadeesha + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/58389915?v=4 + url: https://github.com/Nimitha-jagadeesha +lucaromagnoli: + login: lucaromagnoli + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/38782977?u=e66396859f493b4ddcb3a837a1b2b2039c805417&v=4 + url: https://github.com/lucaromagnoli +salmantec: + login: salmantec + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/41512228?u=443551b893ff2425c59d5d021644f098cf7c68d5&v=4 + url: https://github.com/salmantec +OCE1960: + login: OCE1960 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/45076670?u=0e9a44712b92ffa89ddfbaa83c112f3f8e1d68e2&v=4 + url: https://github.com/OCE1960 +hamidrasti: + login: hamidrasti + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/43915620?v=4 + url: https://github.com/hamidrasti +kkinder: + login: kkinder + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1115018?u=c5e90284a9f5c5049eae1bb029e3655c7dc913ed&v=4 + url: https://github.com/kkinder +kabirkhan: + login: kabirkhan + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/13891834?u=e0eabf792376443ac853e7dca6f550db4166fe35&v=4 + url: https://github.com/kabirkhan +zamiramir: + login: zamiramir + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/40475662?u=e58ef61034e8d0d6a312cc956fb09b9c3332b449&v=4 + url: https://github.com/zamiramir +trim21: + login: trim21 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/13553903?u=3cadf0f02095c9621aa29df6875f53a80ca4fbfb&v=4 + url: https://github.com/trim21 +koxudaxi: + login: koxudaxi + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/630670?u=507d8577b4b3670546b449c4c2ccbc5af40d72f7&v=4 + url: https://github.com/koxudaxi +pablogamboa: + login: pablogamboa + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/12892536?u=326a57059ee0c40c4eb1b38413957236841c631b&v=4 + url: https://github.com/pablogamboa +dconathan: + login: dconathan + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/15098095?v=4 + url: https://github.com/dconathan +Jamim: + login: Jamim + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/5607572?u=0cf3027bec78ba4f0b89802430c136bc69847d7a&v=4 + url: https://github.com/Jamim +svalouch: + login: svalouch + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/54674660?v=4 + url: https://github.com/svalouch +frankie567: + login: frankie567 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=c159fe047727aedecbbeeaa96a1b03ceb9d39add&v=4 + url: https://github.com/frankie567 +marier-nico: + login: marier-nico + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/30477068?u=c7df6af853c8f4163d1517814f3e9a0715c82713&v=4 + url: https://github.com/marier-nico +Dustyposa: + login: Dustyposa + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 + url: https://github.com/Dustyposa +aviramha: + login: aviramha + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/41201924?u=6883cc4fc13a7b2e60d4deddd4be06f9c5287880&v=4 + url: https://github.com/aviramha +iwpnd: + login: iwpnd + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/6152183?u=ec59396e9437fff488791c5ecdf6d23f1f1ebf3a&v=4 + url: https://github.com/iwpnd +raphaelauv: + login: raphaelauv + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 + url: https://github.com/raphaelauv +windson: + login: windson + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1826682?u=8b28dcd716c46289f191f8828e01d74edd058bef&v=4 + url: https://github.com/windson +sm-Fifteen: + login: sm-Fifteen + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 + url: https://github.com/sm-Fifteen +sattosan: + login: sattosan + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/20574756?u=b0d8474d2938189c6954423ae8d81d91013f80a8&v=4 + url: https://github.com/sattosan +michaeloliverx: + login: michaeloliverx + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/55017335?u=e606eb5cc397c07523be47637b1ee796904fbb59&v=4 + url: https://github.com/michaeloliverx +voegtlel: + login: voegtlel + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/5764745?u=db8df3d70d427928ab6d7dbfc395a4a7109c1d1b&v=4 + url: https://github.com/voegtlel +HarshaLaxman: + login: HarshaLaxman + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/19939186?u=a112f38b0f6b4d4402dc8b51978b5a0b2e5c5970&v=4 + url: https://github.com/HarshaLaxman +RunningIkkyu: + login: RunningIkkyu + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4 + url: https://github.com/RunningIkkyu +cassiobotaro: + login: cassiobotaro + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=a08022b191ddbd0a6159b2981d9d878b6d5bb71f&v=4 + url: https://github.com/cassiobotaro +chenl: + login: chenl + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1677651?u=c618508eaad6d596cea36c8ea784b424288f6857&v=4 + url: https://github.com/chenl +retnikt: + login: retnikt + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4 + url: https://github.com/retnikt +yankeexe: + login: yankeexe + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/13623913?u=f970e66421775a8d3cdab89c0c752eaead186f6d&v=4 + url: https://github.com/yankeexe +patrickkwang: + login: patrickkwang + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1263870?u=4bf74020e15be490f19ef8322a76eec882220b96&v=4 + url: https://github.com/patrickkwang +victorphoenix3: + login: victorphoenix3 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/48182195?u=e4875bd088623cb4ddeb7be194ec54b453aff035&v=4 + url: https://github.com/victorphoenix3 +davidefiocco: + login: davidefiocco + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/4547987?v=4 + url: https://github.com/davidefiocco +adriencaccia: + login: adriencaccia + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/19605940?u=980b0b366a02791a5600b2e9f9ac2037679acaa8&v=4 + url: https://github.com/adriencaccia +jamescurtin: + login: jamescurtin + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/10189269?u=0b491fc600ca51f41cf1d95b49fa32a3eba1de57&v=4 + url: https://github.com/jamescurtin +jmriebold: + login: jmriebold + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/6983392?u=4efdc97bf2422dcc7e9ff65b9ff80087c8eb2a20&v=4 + url: https://github.com/jmriebold +nukopy: + login: nukopy + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/42367320?u=6061be0bd060506f6d564a8df3ae73fab048cdfe&v=4 + url: https://github.com/nukopy +imba-tjd: + login: imba-tjd + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/24759802?u=01e901a4fe004b4b126549d3ff1c4000fe3720b5&v=4 + url: https://github.com/imba-tjd +paxcodes: + login: paxcodes + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/13646646?u=e7429cc7ab11211ef762f4cd3efea7db6d9ef036&v=4 + url: https://github.com/paxcodes +kaustubhgupta: + login: kaustubhgupta + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/43691873?u=8dd738718ac7ffad4ef31e86b5d780a1141c695d&v=4 + url: https://github.com/kaustubhgupta +wakabame: + login: wakabame + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/35513518?u=41ef6b0a55076e5c540620d68fb006e386c2ddb0&v=4 + url: https://github.com/wakabame +nzig: + login: nzig + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/7372858?u=e769add36ed73c778cdb136eb10bf96b1e119671&v=4 + url: https://github.com/nzig +yezz123: + login: yezz123 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=d7062cbc6eb7671d5dc9cc0e32a24ae335e0f225&v=4 + url: https://github.com/yezz123 +musicinmybrain: + login: musicinmybrain + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/6898909?u=9010312053e7141383b9bdf538036c7f37fbaba0&v=4 + url: https://github.com/musicinmybrain +softwarebloat: + login: softwarebloat + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/16540684?v=4 + url: https://github.com/softwarebloat +Lancetnik: + login: Lancetnik + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/44573917?u=f9a18be7324333daf9cc314c35c3051f0a20a7a6&v=4 + url: https://github.com/Lancetnik +yogabonito: + login: yogabonito + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/7026269?v=4 + url: https://github.com/yogabonito +s111d: + login: s111d + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/4954856?v=4 + url: https://github.com/s111d +estebanx64: + login: estebanx64 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +tamird: + login: tamird + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1535036?v=4 + url: https://github.com/tamird +rabinlamadong: + login: rabinlamadong + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/170439781?v=4 + url: https://github.com/rabinlamadong +AyushSinghal1794: + login: AyushSinghal1794 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/89984761?v=4 + url: https://github.com/AyushSinghal1794 diff --git a/docs/en/data/translation_reviewers.yml b/docs/en/data/translation_reviewers.yml index e69de29bb..6cc09a7c1 100644 --- a/docs/en/data/translation_reviewers.yml +++ b/docs/en/data/translation_reviewers.yml @@ -0,0 +1,1645 @@ +s111d: + login: s111d + count: 147 + avatarUrl: https://avatars.githubusercontent.com/u/4954856?v=4 + url: https://github.com/s111d +Xewus: + login: Xewus + count: 139 + avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 + url: https://github.com/Xewus +ceb10n: + login: ceb10n + count: 108 + avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 + url: https://github.com/ceb10n +tokusumi: + login: tokusumi + count: 104 + avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 + url: https://github.com/tokusumi +hasansezertasan: + login: hasansezertasan + count: 95 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan +hard-coders: + login: hard-coders + count: 92 + avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 + url: https://github.com/hard-coders +AlertRED: + login: AlertRED + count: 81 + avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 + url: https://github.com/AlertRED +sodaMelon: + login: sodaMelon + count: 81 + avatarUrl: https://avatars.githubusercontent.com/u/66295123?u=be939db90f1119efee9e6110cc05066ff1f40f00&v=4 + url: https://github.com/sodaMelon +nazarepiedady: + login: nazarepiedady + count: 78 + avatarUrl: https://avatars.githubusercontent.com/u/31008635?u=8dc25777dc9cb51fb0dbba2f137988953d330b78&v=4 + url: https://github.com/nazarepiedady +Alexandrhub: + login: Alexandrhub + count: 68 + avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 + url: https://github.com/Alexandrhub +waynerv: + login: waynerv + count: 63 + avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 + url: https://github.com/waynerv +cassiobotaro: + login: cassiobotaro + count: 61 + avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=a08022b191ddbd0a6159b2981d9d878b6d5bb71f&v=4 + url: https://github.com/cassiobotaro +mattwang44: + login: mattwang44 + count: 58 + avatarUrl: https://avatars.githubusercontent.com/u/24987826?u=58e37fb3927b9124b458945ac4c97aa0f1062d85&v=4 + url: https://github.com/mattwang44 +Laineyzhang55: + login: Laineyzhang55 + count: 48 + avatarUrl: https://avatars.githubusercontent.com/u/59285379?v=4 + url: https://github.com/Laineyzhang55 +Kludex: + login: Kludex + count: 47 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 + url: https://github.com/Kludex +komtaki: + login: komtaki + count: 45 + avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 + url: https://github.com/komtaki +alperiox: + login: alperiox + count: 42 + avatarUrl: https://avatars.githubusercontent.com/u/34214152?u=2c5acad3461d4dbc2d48371ba86cac56ae9b25cc&v=4 + url: https://github.com/alperiox +tiangolo: + login: tiangolo + count: 40 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo +Winand: + login: Winand + count: 40 + avatarUrl: https://avatars.githubusercontent.com/u/53390?u=bb0e71a2fc3910a8e0ee66da67c33de40ea695f8&v=4 + url: https://github.com/Winand +solomein-sv: + login: solomein-sv + count: 38 + avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=789927ee09cfabd752d3bd554fa6baf4850d2777&v=4 + url: https://github.com/solomein-sv +JavierSanchezCastro: + login: JavierSanchezCastro + count: 38 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +stlucasgarcia: + login: stlucasgarcia + count: 36 + avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=c22d8850e9dc396a8820766a59837f967e14f9a0&v=4 + url: https://github.com/stlucasgarcia +SwftAlpc: + login: SwftAlpc + count: 36 + avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 + url: https://github.com/SwftAlpc +nilslindemann: + login: nilslindemann + count: 35 + avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 + url: https://github.com/nilslindemann +rjNemo: + login: rjNemo + count: 34 + avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 + url: https://github.com/rjNemo +codingjenny: + login: codingjenny + count: 34 + avatarUrl: https://avatars.githubusercontent.com/u/103817302?u=3a042740dc0ff58615da0d8679230966fd7693e8&v=4 + url: https://github.com/codingjenny +akarev0: + login: akarev0 + count: 33 + avatarUrl: https://avatars.githubusercontent.com/u/53393089?u=6e528bb4789d56af887ce6fe237bea4010885406&v=4 + url: https://github.com/akarev0 +romashevchenko: + login: romashevchenko + count: 32 + avatarUrl: https://avatars.githubusercontent.com/u/132477732?v=4 + url: https://github.com/romashevchenko +wdh99: + login: wdh99 + count: 31 + avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 + url: https://github.com/wdh99 +alv2017: + login: alv2017 + count: 31 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 +LorhanSohaky: + login: LorhanSohaky + count: 30 + avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 + url: https://github.com/LorhanSohaky +alejsdev: + login: alejsdev + count: 30 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 + url: https://github.com/alejsdev +black-redoc: + login: black-redoc + count: 29 + avatarUrl: https://avatars.githubusercontent.com/u/18581590?u=7b6336166d0797fbbd44ea70c1c3ecadfc89af9e&v=4 + url: https://github.com/black-redoc +pedabraham: + login: pedabraham + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/16860088?u=abf922a7b920bf8fdb7867d8b43e091f1e796178&v=4 + url: https://github.com/pedabraham +Smlep: + login: Smlep + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/16785985?u=ffe99fa954c8e774ef1117e58d34aece92051e27&v=4 + url: https://github.com/Smlep +dedkot01: + login: dedkot01 + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/26196675?u=e2966887124e67932853df4f10f86cb526edc7b0&v=4 + url: https://github.com/dedkot01 +hsuanchi: + login: hsuanchi + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/24913710?u=0b094ae292292fee093818e37ceb645c114d2bff&v=4 + url: https://github.com/hsuanchi +dpinezich: + login: dpinezich + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/3204540?u=a2e1465e3ee10d537614d513589607eddefde09f&v=4 + url: https://github.com/dpinezich +maoyibo: + login: maoyibo + count: 27 + avatarUrl: https://avatars.githubusercontent.com/u/7887703?v=4 + url: https://github.com/maoyibo +0417taehyun: + login: 0417taehyun + count: 27 + avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4 + url: https://github.com/0417taehyun +BilalAlpaslan: + login: BilalAlpaslan + count: 26 + avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 + url: https://github.com/BilalAlpaslan +junah201: + login: junah201 + count: 26 + avatarUrl: https://avatars.githubusercontent.com/u/75025529?u=2451c256e888fa2a06bcfc0646d09b87ddb6a945&v=4 + url: https://github.com/junah201 +Vincy1230: + login: Vincy1230 + count: 26 + avatarUrl: https://avatars.githubusercontent.com/u/81342412?u=ab5e256a4077a4a91f3f9cd2115ba80780454cbe&v=4 + url: https://github.com/Vincy1230 +zy7y: + login: zy7y + count: 25 + avatarUrl: https://avatars.githubusercontent.com/u/67154681?u=5d634834cc514028ea3f9115f7030b99a1f4d5a4&v=4 + url: https://github.com/zy7y +mycaule: + login: mycaule + count: 25 + avatarUrl: https://avatars.githubusercontent.com/u/6161385?u=e3cec75bd6d938a0d73fae0dc5534d1ab2ed1b0e&v=4 + url: https://github.com/mycaule +Aruelius: + login: Aruelius + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/25380989?u=574f8cfcda3ea77a3f81884f6b26a97068e36a9d&v=4 + url: https://github.com/Aruelius +OzgunCaglarArslan: + login: OzgunCaglarArslan + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/86166426?v=4 + url: https://github.com/OzgunCaglarArslan +sh0nk: + login: sh0nk + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 + url: https://github.com/sh0nk +axel584: + login: axel584 + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 + url: https://github.com/axel584 +wisderfin: + login: wisderfin + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/77553770?u=94478d3e1ef7d36d70479c5bd35d8de28b071c10&v=4 + url: https://github.com/wisderfin +rostik1410: + login: rostik1410 + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4 + url: https://github.com/rostik1410 +AGolicyn: + login: AGolicyn + count: 21 + avatarUrl: https://avatars.githubusercontent.com/u/86262613?u=3c21606ab8d210a061a1673decff1e7d5592b380&v=4 + url: https://github.com/AGolicyn +Attsun1031: + login: Attsun1031 + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/1175560?v=4 + url: https://github.com/Attsun1031 +ycd: + login: ycd + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 + url: https://github.com/ycd +delhi09: + login: delhi09 + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4 + url: https://github.com/delhi09 +rogerbrinkmann: + login: rogerbrinkmann + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/5690226?v=4 + url: https://github.com/rogerbrinkmann +DevDae: + login: DevDae + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/87962045?u=08e10fa516e844934f4b3fc7c38b33c61697e4a1&v=4 + url: https://github.com/DevDae +svlandeg: + login: svlandeg + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 + url: https://github.com/svlandeg +sattosan: + login: sattosan + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/20574756?u=b0d8474d2938189c6954423ae8d81d91013f80a8&v=4 + url: https://github.com/sattosan +ComicShrimp: + login: ComicShrimp + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=d2fbf412e7730183ce91686ca48d4147e1b7dc74&v=4 + url: https://github.com/ComicShrimp +mezgoodle: + login: mezgoodle + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/41520940?u=e871bc26734eb2436d98c19c3fb57a4773e13c24&v=4 + url: https://github.com/mezgoodle +simatheone: + login: simatheone + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/78508673?u=1b9658d9ee0bde33f56130dd52275493ddd38690&v=4 + url: https://github.com/simatheone +ivan-abc: + login: ivan-abc + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 + url: https://github.com/ivan-abc +bezaca: + login: bezaca + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/69092910?u=4ac58eab99bd37d663f3d23551df96d4fbdbf760&v=4 + url: https://github.com/bezaca +lbmendes: + login: lbmendes + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/80999926?u=646619e2f07ac5a7c3f65fe7834197461a4fff9f&v=4 + url: https://github.com/lbmendes +spacesphere: + login: spacesphere + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/34628304?u=cde91f6002dd33156e1bf8005f11a7a3ed76b790&v=4 + url: https://github.com/spacesphere +panko: + login: panko + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/1569515?u=a84a5d255621ed82f8e1ca052f5f2eeb75997da2&v=4 + url: https://github.com/panko +jeison-araya: + login: jeison-araya + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/57369279?u=17001e68af7d8e5b8c343e5e9df4050f419998d5&v=4 + url: https://github.com/jeison-araya +Limsunoh: + login: Limsunoh + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/90311848?u=f456e0c5709fd50c8cd2898b551558eda14e5f21&v=4 + url: https://github.com/Limsunoh +yanever: + login: yanever + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/21978760?v=4 + url: https://github.com/yanever +mastizada: + login: mastizada + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/1975818?u=0751a06d7271c8bf17cb73b1b845644ab4d2c6dc&v=4 + url: https://github.com/mastizada +JaeHyuckSa: + login: JaeHyuckSa + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/104830931?v=4 + url: https://github.com/JaeHyuckSa +Jedore: + login: Jedore + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/17944025?u=81d503e1c800eb666b3861ca47a3a773bbc3f539&v=4 + url: https://github.com/Jedore +Joao-Pedro-P-Holanda: + login: Joao-Pedro-P-Holanda + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/110267046?u=331bd016326dac4cf3df4848f6db2dbbf8b5f978&v=4 + url: https://github.com/Joao-Pedro-P-Holanda +kim-sangah: + login: kim-sangah + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/173775778?v=4 + url: https://github.com/kim-sangah +PandaHun: + login: PandaHun + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/13096845?u=646eba44db720e37d0dbe8e98e77ab534ea78a20&v=4 + url: https://github.com/PandaHun +dukkee: + login: dukkee + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/36825394?u=ccfd86e6a4f2d093dad6f7544cc875af67fa2df8&v=4 + url: https://github.com/dukkee +mkdir700: + login: mkdir700 + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/56359329?u=0ba13427420e7f6e4c83947736de247326f2c292&v=4 + url: https://github.com/mkdir700 +BORA040126: + login: BORA040126 + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/88664069?u=98e382727a485971e04aaa7c873d9a75a17ee3be&v=4 + url: https://github.com/BORA040126 +mattkoehne: + login: mattkoehne + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/80362153?u=6e1439582715693407b86182eb66263bb578a761&v=4 + url: https://github.com/mattkoehne +jovicon: + login: jovicon + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/21287303?u=b049eac3e51a4c0473c2efe66b4d28a7d8f2b572&v=4 + url: https://github.com/jovicon +izaguerreiro: + login: izaguerreiro + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/2241504?v=4 + url: https://github.com/izaguerreiro +jburckel: + login: jburckel + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/11768758?u=044462e4130e086a0621f4abb45f0d7a289ab7fa&v=4 + url: https://github.com/jburckel +peidrao: + login: peidrao + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/32584628?u=64c634bb10381905038ff7faf3c8c3df47fb799a&v=4 + url: https://github.com/peidrao +impocode: + login: impocode + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/109408819?u=9cdfc5ccb31a2094c520f41b6087012fa9048982&v=4 + url: https://github.com/impocode +wesinalves: + login: wesinalves + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/13563128?u=9eb17ed50645dd684bfec47e75dba4e9772ec9c1&v=4 + url: https://github.com/wesinalves +NastasiaSaby: + login: NastasiaSaby + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/8245071?u=b3afd005f9e4bf080c219ef61a592b3a8004b764&v=4 + url: https://github.com/NastasiaSaby +oandersonmagalhaes: + login: oandersonmagalhaes + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/83456692?v=4 + url: https://github.com/oandersonmagalhaes +batlopes: + login: batlopes + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/33462923?u=0fb3d7acb316764616f11e4947faf080e49ad8d9&v=4 + url: https://github.com/batlopes +Lenclove: + login: Lenclove + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/32355298?u=d0065e01650c63c2b2413f42d983634b2ea85481&v=4 + url: https://github.com/Lenclove +joonas-yoon: + login: joonas-yoon + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/9527681?u=0166d22ef4749e617c6516e79f833cd8d73f1949&v=4 + url: https://github.com/joonas-yoon +baseplate-admin: + login: baseplate-admin + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/61817579?u=ce4c268fa949ae9a0290996e7949195302055812&v=4 + url: https://github.com/baseplate-admin +KaniKim: + login: KaniKim + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=296dbdd490e0eb96e3d45a2608c065603b17dc31&v=4 + url: https://github.com/KaniKim +andersonrocha0: + login: andersonrocha0 + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/22346169?u=93a1359c8c5461d894802c0cc65bcd09217e7a02&v=4 + url: https://github.com/andersonrocha0 +kwang1215: + login: kwang1215 + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/74170199?u=2a63ff6692119dde3f5e5693365b9fcd6f977b08&v=4 + url: https://github.com/kwang1215 +AdrianDeAnda: + login: AdrianDeAnda + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/1024932?u=b2ea249c6b41ddf98679c8d110d0f67d4a3ebf93&v=4 + url: https://github.com/AdrianDeAnda +blt232018: + login: blt232018 + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/43393471?u=172b0e0391db1aa6c1706498d6dfcb003c8a4857&v=4 + url: https://github.com/blt232018 +NinaHwang: + login: NinaHwang + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/79563565?u=241f2cb6d38a2d379536608a8ea5a22ed4b1a3ea&v=4 + url: https://github.com/NinaHwang +glsglsgls: + login: glsglsgls + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/76133879?v=4 + url: https://github.com/glsglsgls +codespearhead: + login: codespearhead + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/72931357?u=0fce6b82219b604d58adb614a761556425579cb5&v=4 + url: https://github.com/codespearhead +emrhnsyts: + login: emrhnsyts + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/42899027?u=ad26798e3f8feed2041c5dd5f87e58933d6c3283&v=4 + url: https://github.com/emrhnsyts +Lufa1u: + login: Lufa1u + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/112495876?u=087658920ed9e74311597bdd921d8d2de939d276&v=4 + url: https://github.com/Lufa1u +KNChiu: + login: KNChiu + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/36751646?v=4 + url: https://github.com/KNChiu +mariacamilagl: + login: mariacamilagl + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 + url: https://github.com/mariacamilagl +ryuckel: + login: ryuckel + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/36391432?u=094eec0cfddd5013f76f31e55e56147d78b19553&v=4 + url: https://github.com/ryuckel +umitkaanusta: + login: umitkaanusta + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/53405015?v=4 + url: https://github.com/umitkaanusta +kty4119: + login: kty4119 + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/49435654?v=4 + url: https://github.com/kty4119 +RobotToI: + login: RobotToI + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/44951382?u=e41dbc19191ce7abed86694b1a44ea0523e1c60e&v=4 + url: https://github.com/RobotToI +fcrozetta: + login: fcrozetta + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/8006246?u=fa2a743e803de2c3a84d3ed8042faefed16c5e43&v=4 + url: https://github.com/fcrozetta +sUeharaE4: + login: sUeharaE4 + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/44468359?v=4 + url: https://github.com/sUeharaE4 +Ernilia: + login: Ernilia + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/125735800?u=13bfaac417a53fd5b5cf992efea363ca72598813&v=4 + url: https://github.com/Ernilia +socket-socket: + login: socket-socket + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/121552599?u=104df6503242e8d762fe293e7036f7260f245d49&v=4 + url: https://github.com/socket-socket +nick-cjyx9: + login: nick-cjyx9 + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/119087246?u=c35aab03f082430be8a1edd80f5625b44819a0d8&v=4 + url: https://github.com/nick-cjyx9 +waketzheng: + login: waketzheng + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/35413830?u=df19e4fd5bb928e7d086e053ef26a46aad23bf84&v=4 + url: https://github.com/waketzheng +lucasbalieiro: + login: lucasbalieiro + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/37416577?u=5a395a69384e7fa0f9840ea32ef963d3f1cd9da4&v=4 + url: https://github.com/lucasbalieiro +RunningIkkyu: + login: RunningIkkyu + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4 + url: https://github.com/RunningIkkyu +JulianMaurin: + login: JulianMaurin + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/63545168?u=b7d15ac865268cbefc2d739e2f23d9aeeac1a622&v=4 + url: https://github.com/JulianMaurin +JeongHyeongKim: + login: JeongHyeongKim + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/26577800?u=fe653349051c0acf62cd984e74c4ff60ca8d2cb6&v=4 + url: https://github.com/JeongHyeongKim +arthurio: + login: arthurio + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/950449?u=76b997138273ce5e1990b971c4f27c9aff979fd5&v=4 + url: https://github.com/arthurio +mahone3297: + login: mahone3297 + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/1701379?u=20588ff0e456d13e8017333eb237595d11410234&v=4 + url: https://github.com/mahone3297 +eVery1337: + login: eVery1337 + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/84917945?u=7af243f05ecfba59191199a70d8ba365c1327768&v=4 + url: https://github.com/eVery1337 +aykhans: + login: aykhans + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/88669260?u=798da457cc3276d3c6dd7fd628d0005ad8b298cc&v=4 + url: https://github.com/aykhans +riroan: + login: riroan + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/33053284?u=2d18e3771506ee874b66d6aa2b3b1107fd95c38f&v=4 + url: https://github.com/riroan +yodai-yodai: + login: yodai-yodai + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/7031039?u=4f3593f5931892b931a745cfab846eff6e9332e7&v=4 + url: https://github.com/yodai-yodai +marcelomarkus: + login: marcelomarkus + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/20115018?u=dda090ce9160ef0cd2ff69b1e5ea741283425cba&v=4 + url: https://github.com/marcelomarkus +JoaoGustavoRogel: + login: JoaoGustavoRogel + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/29525510?u=1dd3096c6c2be2576fd5e818b1be15b2c9768aa5&v=4 + url: https://github.com/JoaoGustavoRogel +Zhongheng-Cheng: + login: Zhongheng-Cheng + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/95612344?u=a0f7730a3cc7486827965e01a119ad610bda4b0a&v=4 + url: https://github.com/Zhongheng-Cheng +dimaqq: + login: dimaqq + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/662249?u=15313dec91bae789685e4abb3c2152251de41948&v=4 + url: https://github.com/dimaqq +julianofischer: + login: julianofischer + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/158303?u=d91662eb949d4cc7368831cf37a5cdfd90b7010c&v=4 + url: https://github.com/julianofischer +bnzone: + login: bnzone + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/39371503?u=c16f00c41d88479fa2d57b0d7d233b758eacce2d&v=4 + url: https://github.com/bnzone +ChuyuChoyeon: + login: ChuyuChoyeon + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/129537877?u=f0c76f3327817a8b86b422d62e04a34bf2827f2b&v=4 + url: https://github.com/ChuyuChoyeon +shamosishen: + login: shamosishen + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/9498321?u=c83c20c79e019a0b555a125adf20fc4fb7a882c8&v=4 + url: https://github.com/shamosishen +mertssmnoglu: + login: mertssmnoglu + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/61623638?u=59dd885b68ff1832f9ab3b4a4446896358c23442&v=4 + url: https://github.com/mertssmnoglu +KimJoonSeo: + login: KimJoonSeo + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/17760162?u=a58cdc77ae1c069a64166f7ecc4d42eecfd9a468&v=4 + url: https://github.com/KimJoonSeo +camigomezdev: + login: camigomezdev + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/16061815?u=25b5ebc042fff53fa03dc107ded10e36b1b7a5b9&v=4 + url: https://github.com/camigomezdev +gitgernit: + login: gitgernit + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/129539613?u=d04f10143ab32c93f563ea14bf242d1d2bc991b0&v=4 + url: https://github.com/gitgernit +Serrones: + login: Serrones + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/22691749?u=4795b880e13ca33a73e52fc0ef7dc9c60c8fce47&v=4 + url: https://github.com/Serrones +israteneda: + login: israteneda + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/20668624?u=67574648f89019d1c73b16a6a009da659557f9e5&v=4 + url: https://github.com/israteneda +krocdort: + login: krocdort + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/34248814?v=4 + url: https://github.com/krocdort +anthonycepeda: + login: anthonycepeda + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 + url: https://github.com/anthonycepeda +vitumenezes: + login: vitumenezes + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/9680878?u=e7c6865aec49c3c94b8c8edc1198d1eac3e50b26&v=4 + url: https://github.com/vitumenezes +fabioueno: + login: fabioueno + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/14273852?u=edd700982b16317ac6ebfd24c47bc0029b21d360&v=4 + url: https://github.com/fabioueno +cfraboulet: + login: cfraboulet + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/62244267?u=ed0e286ba48fa1dafd64a08e50f3364b8e12df34&v=4 + url: https://github.com/cfraboulet +HiemalBeryl: + login: HiemalBeryl + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/63165207?u=276f4af2829baf28b912c718675852bfccb0e7b4&v=4 + url: https://github.com/HiemalBeryl +pablocm83: + login: pablocm83 + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/28315068?u=3310fbb05bb8bfc50d2c48b6cb64ac9ee4a14549&v=4 + url: https://github.com/pablocm83 +d2a-raudenaerde: + login: d2a-raudenaerde + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/5213150?v=4 + url: https://github.com/d2a-raudenaerde +deniscapeto: + login: deniscapeto + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/12864353?u=dbc20c5c1171feab5df4db46488b675d53cb5b07&v=4 + url: https://github.com/deniscapeto +bsab: + login: bsab + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/9799799?u=c4a09b1abb794cd8280c4793d43d0e2eb963ecda&v=4 + url: https://github.com/bsab +ArcLightSlavik: + login: ArcLightSlavik + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4 + url: https://github.com/ArcLightSlavik +Cajuteq: + login: Cajuteq + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/26676532?u=8ee0422981810e51480855de1c0d67b6b79cd3f2&v=4 + url: https://github.com/Cajuteq +emmrichard: + login: emmrichard + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/1328018?u=8114d8fc0e8e42a092e4283013a1c54b792c466b&v=4 + url: https://github.com/emmrichard +wakabame: + login: wakabame + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/35513518?u=41ef6b0a55076e5c540620d68fb006e386c2ddb0&v=4 + url: https://github.com/wakabame +mawassk: + login: mawassk + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/84179197?v=4 + url: https://github.com/mawassk +diogoduartec: + login: diogoduartec + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/31852339?u=7514a5f05fcbeccc62f8c5dc25879efeb1ef9335&v=4 + url: https://github.com/diogoduartec +aqcool: + login: aqcool + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/52229895?v=4 + url: https://github.com/aqcool +'1320555911': + login: '1320555911' + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/58590086?u=6d8f4fbf08d5ac72c1c895892c461c5e0b013dc3&v=4 + url: https://github.com/1320555911 +mcthesw: + login: mcthesw + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/61224072?u=82a1b106298348f060c3f4f39817e0cae5ce2b7c&v=4 + url: https://github.com/mcthesw +xzmeng: + login: xzmeng + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/40202897?v=4 + url: https://github.com/xzmeng +negadive: + login: negadive + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/47322392?u=c1be2e9b9b346b4a77d9157da2a5739ab25ce0f8&v=4 + url: https://github.com/negadive +mbroton: + login: mbroton + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/50829834?u=a48610bf1bffaa9c75d03228926e2eb08a2e24ee&v=4 + url: https://github.com/mbroton +Kirilex: + login: Kirilex + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/100281552?v=4 + url: https://github.com/Kirilex +Mordson: + login: Mordson + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/39025897?u=b94ea96ef35bbe43bc85359cfb31d28ac16d470c&v=4 + url: https://github.com/Mordson +arunppsg: + login: arunppsg + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/26398753?v=4 + url: https://github.com/arunppsg +dimastbk: + login: dimastbk + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/3132181?u=66587398d43466a1dc75c238df5f048e0afc77ed&v=4 + url: https://github.com/dimastbk +lordqyxz: + login: lordqyxz + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/31722468?u=974553c0ba53526d9be7e9876544283291be3b0d&v=4 + url: https://github.com/lordqyxz +dudyaosuplayer: + login: dudyaosuplayer + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/62661898?u=7864cc5f01b1c845ae8ad49acf45dec6faca0c57&v=4 + url: https://github.com/dudyaosuplayer +talhaumer: + login: talhaumer + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/46643702?u=5d1fd7057ea9534fb3221931b809a3d750157212&v=4 + url: https://github.com/talhaumer +bankofsardine: + login: bankofsardine + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/44944207?u=0368e1b698ffab6bf29e202f9fd2dddd352429f1&v=4 + url: https://github.com/bankofsardine +rsip22: + login: rsip22 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/16676222?v=4 + url: https://github.com/rsip22 +jessicapaz: + login: jessicapaz + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/20428941?u=6ffdaab5a85bf77a2d8870dade5e53555f34577b&v=4 + url: https://github.com/jessicapaz +mohsen-mahmoodi: + login: mohsen-mahmoodi + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/2872586?u=9274b3b13d8a992dba29b162fee48473a0fa142d&v=4 + url: https://github.com/mohsen-mahmoodi +jeesang7: + login: jeesang7 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/30719956?u=35fc8bca04d32d3c4ce085956f0636b959ba30f6&v=4 + url: https://github.com/jeesang7 +TemaSpb: + login: TemaSpb + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/20205738?u=d7dce0718720a7107803a573d628d8dd3d5c2fb4&v=4 + url: https://github.com/TemaSpb +BugLight: + login: BugLight + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/13618366?u=57572e544e40c2a491db5bf7255bd24886d2cb09&v=4 + url: https://github.com/BugLight +0x4Dark: + login: 0x4Dark + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/7569289?v=4 + url: https://github.com/0x4Dark +Wuerike: + login: Wuerike + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/35462243?u=80c753dedf4a78db12ef66316dbdebbe6d84a2b9&v=4 + url: https://github.com/Wuerike +jvmazagao: + login: jvmazagao + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/22477816?u=f3b2d503b53e6ec8c808f0601b756a063a07f06e&v=4 + url: https://github.com/jvmazagao +cun3yt: + login: cun3yt + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/24409240?u=39f651cdcc4991fb9fef5bbd9e9503db2174ac13&v=4 + url: https://github.com/cun3yt +aminkhani: + login: aminkhani + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/51851950?u=051896c4933816bc61d11091d887f6e8dfd1d27b&v=4 + url: https://github.com/aminkhani +nifadyev: + login: nifadyev + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/36514612?u=e101da8641d5a09901d2155255a93f8ab3d9c468&v=4 + url: https://github.com/nifadyev +LaurEars: + login: LaurEars + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/4914725?v=4 + url: https://github.com/LaurEars +Chushine: + login: Chushine + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/135534400?v=4 + url: https://github.com/Chushine +frwl404: + login: frwl404 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/42642656?u=572a5a33762e07eaa6ebd58d9d773abdb1de41c3&v=4 + url: https://github.com/frwl404 +esrefzeki: + login: esrefzeki + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/54935247?u=193cf5a169ca05fc54995a4dceabc82c7dc6e5ea&v=4 + url: https://github.com/esrefzeki +dtleal: + login: dtleal + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/31096951?v=4 + url: https://github.com/dtleal +art3xa: + login: art3xa + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/92092049?v=4 + url: https://github.com/art3xa +SamuelBFavarin: + login: SamuelBFavarin + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/17628602?u=5aac13ae492fa9a86e397a70803ac723dba2efe7&v=4 + url: https://github.com/SamuelBFavarin +takacs: + login: takacs + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/44911031?u=f6c6b70b3ba86ceb93b0f9bcab609bf9328b2305&v=4 + url: https://github.com/takacs +anton2yakovlev: + login: anton2yakovlev + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/44229180?u=bdd445ba99074b378e7298d23c4bf6d707d2c282&v=4 + url: https://github.com/anton2yakovlev +ILoveSorasakiHina: + login: ILoveSorasakiHina + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/114038930?u=3d3ed8dc3bf57e641d1b26badee5bc79ef34f25b&v=4 + url: https://github.com/ILoveSorasakiHina +devluisrodrigues: + login: devluisrodrigues + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/103431660?u=d9674a3249edc4601d2c712cdebf899918503c3a&v=4 + url: https://github.com/devluisrodrigues +timothy-jeong: + login: timothy-jeong + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/53824764?u=659311b6f6aeb0fbb8b527723fd4c83642f04327&v=4 + url: https://github.com/timothy-jeong +lpdswing: + login: lpdswing + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/20874036?u=7a4fc3e4d0719e37b305deb7af234a7b63200787&v=4 + url: https://github.com/lpdswing +SepehrRasouli: + login: SepehrRasouli + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/81516241?u=3987e880c77d653dd85963302150e07bb7c0ef99&v=4 + url: https://github.com/SepehrRasouli +Zxilly: + login: Zxilly + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/31370133?u=122e23d6e974614736be606e4ea816f45e7745f8&v=4 + url: https://github.com/Zxilly +eavv: + login: eavv + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/18273429?u=c05e8b4ea62810ee7889ca049e510cdd0a66fd26&v=4 + url: https://github.com/eavv +AlexandreBiguet: + login: AlexandreBiguet + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/1483079?u=ff926455cd4cab03c6c49441aa5dc2b21df3e266&v=4 + url: https://github.com/AlexandreBiguet +FelipeSilva93: + login: FelipeSilva93 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/66804965?u=e7cb4b580e46f2e04ecb4cd4d7a12acdddd3c6c1&v=4 + url: https://github.com/FelipeSilva93 +bas-baskara: + login: bas-baskara + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/41407847?u=cdabfaff7481c3323f24a76d9350393b964f2b89&v=4 + url: https://github.com/bas-baskara +odiseo0: + login: odiseo0 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 + url: https://github.com/odiseo0 +eryknn: + login: eryknn + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/87120651?v=4 + url: https://github.com/eryknn +personage-hub: + login: personage-hub + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/76659786?v=4 + url: https://github.com/personage-hub +aminalaee: + login: aminalaee + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/19784933?u=2f45a312b73e7fb29f3b6f8676e5be6f7220da25&v=4 + url: https://github.com/aminalaee +erfan-rfmhr: + login: erfan-rfmhr + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/98986056?u=6c4f9218fe5bb04780dd92bfced360c55e2009f0&v=4 + url: https://github.com/erfan-rfmhr +Scorpionchiques: + login: Scorpionchiques + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/15703294?v=4 + url: https://github.com/Scorpionchiques +heysaeid: + login: heysaeid + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/63112273?u=5397ead391319a147a18b70cc04d1a334f235ef3&v=4 + url: https://github.com/heysaeid +Yois4101: + login: Yois4101 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/119609381?v=4 + url: https://github.com/Yois4101 +tamtam-fitness: + login: tamtam-fitness + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/62091034?u=8da19a6bd3d02f5d6ba30c7247d5b46c98dd1403&v=4 + url: https://github.com/tamtam-fitness +mpmeleshko: + login: mpmeleshko + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/34425664?v=4 + url: https://github.com/mpmeleshko +SonnyYou: + login: SonnyYou + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/18657569?v=4 + url: https://github.com/SonnyYou +matiasbertani: + login: matiasbertani + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/65260383?u=d5edd86a6e2ab4fb1aab7751931fe045a963afd7&v=4 + url: https://github.com/matiasbertani +javillegasna: + login: javillegasna + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/38879192?u=df9ab0d628f8c1f1c849db7b3c0939337f42c3f1&v=4 + url: https://github.com/javillegasna +9zimin9: + login: 9zimin9 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/174453744?v=4 + url: https://github.com/9zimin9 +tyronedamasceno: + login: tyronedamasceno + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/12273721?u=913bca6bab96d9416ad8c9874c80de0833782050&v=4 + url: https://github.com/tyronedamasceno +LikoIlya: + login: LikoIlya + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/15039930?v=4 + url: https://github.com/LikoIlya +ss-o-furda: + login: ss-o-furda + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/56111536?u=d2326baa464a3778c280ed85fd14c00f87eb1080&v=4 + url: https://github.com/ss-o-furda +Frans06: + login: Frans06 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/5842109?u=77529d5517ae80438249b1a45f2d59372a31a212&v=4 + url: https://github.com/Frans06 +Jefidev: + login: Jefidev + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/9964497?u=1da6eee587a8b425ca4afbfdfc6c3a639fe85d02&v=4 + url: https://github.com/Jefidev +Xaraxx: + login: Xaraxx + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/29824698?u=dde2e233e22bb5ca1f8bb0c6e353ccd0d06e6066&v=4 + url: https://github.com/Xaraxx +Suyoung789: + login: Suyoung789 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/31277231?u=744bd3e641413e19bfad6b06a90bb0887c3f9332&v=4 + url: https://github.com/Suyoung789 +akagaeng: + login: akagaeng + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/17076841?u=9ada2eb6a33dc705ba96d58f802c787dea3859b8&v=4 + url: https://github.com/akagaeng +phamquanganh31101998: + login: phamquanganh31101998 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/43257497?u=36fa4ee689415d869a98453083a7c4213d2136ee&v=4 + url: https://github.com/phamquanganh31101998 +peebbv6364: + login: peebbv6364 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/26784747?u=75583df215ee01a5cd2dc646aecb81e7dbd33d06&v=4 + url: https://github.com/peebbv6364 +mrparalon: + login: mrparalon + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/19637629?u=6339508ceb665717cae862a4d33816ac874cbb8f&v=4 + url: https://github.com/mrparalon +creyD: + login: creyD + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/15138480?u=51cd2873cd93807beb578af8e23975856fdbc945&v=4 + url: https://github.com/creyD +zhoonit: + login: zhoonit + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/17230883?u=698cb26dcce4770374b592aad3b7489e91c07fc6&v=4 + url: https://github.com/zhoonit +Sefank: + login: Sefank + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/12670778?u=ca16995c68a82cabc7435c54ac0564930f62dd59&v=4 + url: https://github.com/Sefank +RuslanTer: + login: RuslanTer + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/48125303?v=4 + url: https://github.com/RuslanTer +FedorGN: + login: FedorGN + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/66411909?u=1c6734e92f50c7d66f130ef7d394e72b53770fe6&v=4 + url: https://github.com/FedorGN +rafsaf: + login: rafsaf + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=5fe59a56e1f2f9ccd8005d71752a8276f133ae1a&v=4 + url: https://github.com/rafsaf +frnsimoes: + login: frnsimoes + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/66239468?u=771c4b0c403a42ccf2676ac987ac4999e5ad09bc&v=4 + url: https://github.com/frnsimoes +lieryan: + login: lieryan + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/1006989?v=4 + url: https://github.com/lieryan +ValeryVal: + login: ValeryVal + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/85856176?v=4 + url: https://github.com/ValeryVal +chesstrian: + login: chesstrian + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/3923412?u=8ea9bea6cfb5e6c64dc81be65ac2a9aaf23c5d47&v=4 + url: https://github.com/chesstrian +PabloEmidio: + login: PabloEmidio + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/69937719?u=f4d04cb78da68bb93a641f0b793ff665162e712a&v=4 + url: https://github.com/PabloEmidio +PraveenNanda124: + login: PraveenNanda124 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/116082827?u=b40c4f23c191692e88f676dc3bf33fc7f315edd4&v=4 + url: https://github.com/PraveenNanda124 +guites: + login: guites + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/71985299?u=5dab5eb82b0a67fe709fc893f47a423df4de5d46&v=4 + url: https://github.com/guites +Junhyung21: + login: Junhyung21 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/138214497?u=66377988eaad4f57004decb183f396560407a73f&v=4 + url: https://github.com/Junhyung21 +rinaatt: + login: rinaatt + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/6111202?u=9f62ebd2a72879db54d0b51c07c1d1e7203a4813&v=4 + url: https://github.com/rinaatt +Slijeff: + login: Slijeff + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/31459252?u=083776331690bbcf427766071e33ac28bb8d271d&v=4 + url: https://github.com/Slijeff +GeorchW: + login: GeorchW + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/8687777?u=ae4160f1d88f32692760003f3be9b5fc40a6e00d&v=4 + url: https://github.com/GeorchW +Vlad0395: + login: Vlad0395 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/37487589?u=57dc6660b9904cc0bc59b73569bbfb1ac871a4a1&v=4 + url: https://github.com/Vlad0395 +bisibuka: + login: bisibuka + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/221887?v=4 + url: https://github.com/bisibuka +aimasheraz1: + login: aimasheraz1 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/132935019?v=4 + url: https://github.com/aimasheraz1 +whysage: + login: whysage + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/67018871?u=a05d63a1b315dcf56a4c0dda3c0ca84ce3d6c87f&v=4 + url: https://github.com/whysage +Chake9928: + login: Chake9928 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/62596047?u=7aa2c0aad46911934ce3d22f83a895d05fa54e09&v=4 + url: https://github.com/Chake9928 +qaerial: + login: qaerial + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/41595550?v=4 + url: https://github.com/qaerial +bluefish6: + login: bluefish6 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/3324881?u=d107f6d0017927191644829fb845a8ceb8ac20ee&v=4 + url: https://github.com/bluefish6 +Sion99: + login: Sion99 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/82511301?v=4 + url: https://github.com/Sion99 +EpsilonRationes: + login: EpsilonRationes + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/148639079?v=4 + url: https://github.com/EpsilonRationes +SametEmin: + login: SametEmin + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/115692383?u=bda9052f698e50b0df6657fb9436d07e8496fe2f&v=4 + url: https://github.com/SametEmin +fhabers21: + login: fhabers21 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/58401847?v=4 + url: https://github.com/fhabers21 +kohiry: + login: kohiry + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/57669492?u=f6ab0a062740261e882879269a41a47788c84043&v=4 + url: https://github.com/kohiry +arynoot: + login: arynoot + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/73756088?v=4 + url: https://github.com/arynoot +GDemay: + login: GDemay + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/7033942?u=bbdcb4e2a67df4ec9caa2440362d8cebc44d65e8&v=4 + url: https://github.com/GDemay +maxscheijen: + login: maxscheijen + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/47034840?u=eb98f37882528ea349ca4e5255fa64ac3fef0294&v=4 + url: https://github.com/maxscheijen +celestywang: + login: celestywang + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/184830753?v=4 + url: https://github.com/celestywang +ilhamfadillah: + login: ilhamfadillah + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/20577838?u=c56192cf99b55affcaad408b240259c62e633450&v=4 + url: https://github.com/ilhamfadillah +blaisep: + login: blaisep + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/254456?u=97d584b7c0a6faf583aa59975df4f993f671d121&v=4 + url: https://github.com/blaisep +SirTelemak: + login: SirTelemak + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4 + url: https://github.com/SirTelemak +ovezovs: + login: ovezovs + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/44060682?u=9cb4d738b15e64157cb65afbe2e31bd0c8f3f6e6&v=4 + url: https://github.com/ovezovs +neatek: + login: neatek + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/3075678?u=3001e778e4aa0bf6d3142d09f0b9d13b2c55066f&v=4 + url: https://github.com/neatek +sprytnyk: + login: sprytnyk + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/16718258?u=4893ea96bfebfbdbde8abd9e06851eca12b01bc9&v=4 + url: https://github.com/sprytnyk +wfpinedar: + login: wfpinedar + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/5309214?u=4af7b6b3907b015699a9994d0808137dd68f7658&v=4 + url: https://github.com/wfpinedar +italopenaforte: + login: italopenaforte + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/7786881?u=e64a8f24b1ba95eb82f283be8ab90892e40c5465&v=4 + url: https://github.com/italopenaforte +hackerneocom: + login: hackerneocom + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/67042948?u=ca365045bd261cec5a64059aa23cf80065148c3c&v=4 + url: https://github.com/hackerneocom +dmas-at-wiris: + login: dmas-at-wiris + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/24917162?u=0df147936a375b4b64232c650de31a227a6b59a0&v=4 + url: https://github.com/dmas-at-wiris +TorhamDev: + login: TorhamDev + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/87639984?u=07e5429fbd9c5d63c5ca55a0f31ef541216f0ce6&v=4 + url: https://github.com/TorhamDev +jaystone776: + login: jaystone776 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/11191137?u=299205a95e9b6817a43144a48b643346a5aac5cc&v=4 + url: https://github.com/jaystone776 +AaronDewes: + login: AaronDewes + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/67546953?v=4 + url: https://github.com/AaronDewes +kunansy: + login: kunansy + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/20476946?u=d8321cd00787d5ee29bfdd8ff6fde23ad783a581&v=4 + url: https://github.com/kunansy +TimorChow: + login: TimorChow + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/18365403?u=bcbb357be0a447bc682a161932eab5032cede4af&v=4 + url: https://github.com/TimorChow +ataberkciftlikli: + login: ataberkciftlikli + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/64265169?v=4 + url: https://github.com/ataberkciftlikli +leandrodesouzadev: + login: leandrodesouzadev + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/85115541?u=4eb25f43f1fe23727d61e986cf83b73b86e2a95a&v=4 + url: https://github.com/leandrodesouzadev +dutkiewicz: + login: dutkiewicz + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/6649846?u=e941be6e1ab2ffdf41cea227a73f0ffbef20628f&v=4 + url: https://github.com/dutkiewicz +mirusu400: + login: mirusu400 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/25397908?u=deda776115e4ee6f76fa526bb5127bd1a6c4b231&v=4 + url: https://github.com/mirusu400 +its0x08: + login: its0x08 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/15280042?u=d7c2058f29d4e8fbdae09b194e04c5e410350211&v=4 + url: https://github.com/its0x08 +lindsayzhou: + login: lindsayzhou + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/23748021?u=4db169ce262b69aa7292f82b785436544f69fb88&v=4 + url: https://github.com/lindsayzhou +0xflotus: + login: 0xflotus + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/26602940?u=3c52ce6393bb547c97e6380ccdee03e0c64152c6&v=4 + url: https://github.com/0xflotus +peacekimjapan: + login: peacekimjapan + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/33534175?u=e4219bcebc3773a7068cc34c3eb268ef77cec31b&v=4 + url: https://github.com/peacekimjapan +jonatasoli: + login: jonatasoli + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4 + url: https://github.com/jonatasoli +tyzh-dev: + login: tyzh-dev + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/51972581?u=ba3882da7c009918a8e2d6b9ead31c89f09c922d&v=4 + url: https://github.com/tyzh-dev +WaFeeAL: + login: WaFeeAL + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/45145188?u=db2de8c186073d95693279dcf085fcebffab57d0&v=4 + url: https://github.com/WaFeeAL +emp7yhead: + login: emp7yhead + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/20521260?u=9494c74cb9e1601d734b1f2726e292e257777d98&v=4 + url: https://github.com/emp7yhead +BartoszCki: + login: BartoszCki + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/17833351?u=40025e1182c32a9664834baec268dadad127703d&v=4 + url: https://github.com/BartoszCki +hakancelikdev: + login: hakancelikdev + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/19157033?u=095ea8e0af1de642edd92e5f806c70359e00c977&v=4 + url: https://github.com/hakancelikdev +KaterinaSolovyeva: + login: KaterinaSolovyeva + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/85114725?u=1fe81463cb6b1fd01ac047172fa4895e2a3cecaa&v=4 + url: https://github.com/KaterinaSolovyeva +zhanymkanov: + login: zhanymkanov + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/22341602?u=aa1c47285a4f5692d165ccb2a441c5553f23ef83&v=4 + url: https://github.com/zhanymkanov +felipebpl: + login: felipebpl + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/62957465?u=3c05f0f358b9575503c03122daefb115b6ac1414&v=4 + url: https://github.com/felipebpl +iudeen: + login: iudeen + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen +dwisulfahnur: + login: dwisulfahnur + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/12431528?v=4 + url: https://github.com/dwisulfahnur +ayr-ton: + login: ayr-ton + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1090517?u=5cf70a0e0f0dbf084e074e494aa94d7c91a46ba6&v=4 + url: https://github.com/ayr-ton +raphaelauv: + login: raphaelauv + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 + url: https://github.com/raphaelauv +Fahad-Md-Kamal: + login: Fahad-Md-Kamal + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/34704464?u=84abea85e59c30b2e3bc700ae42424f3fe704332&v=4 + url: https://github.com/Fahad-Md-Kamal +zxcq544: + login: zxcq544 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/5781268?u=25959ea03803742c3b28220b27fc07923a491dcb&v=4 + url: https://github.com/zxcq544 +AlexandrMaltsevYDX: + login: AlexandrMaltsevYDX + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/109986802?u=ed275d72bfcdb4d15abdd54e7be026adbb9ca098&v=4 + url: https://github.com/AlexandrMaltsevYDX +realFranco: + login: realFranco + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/45880759?u=22fea3007d3e2d4c8c82d6ccfbde71454c4c6dd8&v=4 + url: https://github.com/realFranco +piaria: + login: piaria + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/110835535?u=5af3d56254faa05bbca4258a46c5723489480f90&v=4 + url: https://github.com/piaria +mojtabapaso: + login: mojtabapaso + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/121169359?u=ced1d5ad673bcd9e949ebf967a4ab50185637443&v=4 + url: https://github.com/mojtabapaso +eghbalpoorMH: + login: eghbalpoorMH + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/36267498?v=4 + url: https://github.com/eghbalpoorMH +Tiazen: + login: Tiazen + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/16170159?u=0ce5e32f76e3f10733c8f25d97db9e31b753838c&v=4 + url: https://github.com/Tiazen +jfunez: + login: jfunez + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/805749?v=4 + url: https://github.com/jfunez +s-rigaud: + login: s-rigaud + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/46346622?u=eee0adaa9fdff9e312d52526fbd4020dd6860c27&v=4 + url: https://github.com/s-rigaud +Artem4es: + login: Artem4es + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/110793967?u=0f9d4e80e055adc1aa8b548e951f6b4989fa2e78&v=4 + url: https://github.com/Artem4es +sulemanhelp: + login: sulemanhelp + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/22400366?u=3e8e68750655c7f5b2e0ba1d54f5779ee526707d&v=4 + url: https://github.com/sulemanhelp +theRealNonso: + login: theRealNonso + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/29557286?u=6f062680edccfeb4c802daf3b1d8b2a9e21ae013&v=4 + url: https://github.com/theRealNonso +AhsanSheraz: + login: AhsanSheraz + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/51913596?u=08e31cacb3048be30722c94010ddd028f3fdbec4&v=4 + url: https://github.com/AhsanSheraz +HealerNguyen: + login: HealerNguyen + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/29653304?u=6ab095689054c63b1f4ceb26dd66847450225c87&v=4 + url: https://github.com/HealerNguyen +isulim: + login: isulim + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/30448496?u=44c47838defa48a16606b895dce08890fca8482f&v=4 + url: https://github.com/isulim +siavashyj: + login: siavashyj + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/43583410?u=562005ddc7901cd27a1219a118a2363817b14977&v=4 + url: https://github.com/siavashyj +DevSpace88: + login: DevSpace88 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/102557040?u=6b356e3e1b9b6bc6a208b363988d4089ef94193f&v=4 + url: https://github.com/DevSpace88 +Yum-git: + login: Yum-git + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/56100888?u=7c6ae21af081488b5fb703ab096fb1926025fd50&v=4 + url: https://github.com/Yum-git +oubush: + login: oubush + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/7489099?u=c86448bc61f5e7f03a1f14a768beeb09c33899d4&v=4 + url: https://github.com/oubush +KAZAMA-DREAM: + login: KAZAMA-DREAM + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/73453137?u=5108c757a3842733a448d9a16cdc65d82899eee1&v=4 + url: https://github.com/KAZAMA-DREAM +aprilcoskun: + login: aprilcoskun + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/17393603?u=18177d5bdba3a4567b8664587c882fb734e5fa09&v=4 + url: https://github.com/aprilcoskun +zhiquanchi: + login: zhiquanchi + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/29973289?u=744c74bc2635f839235ec32a0a934c5cef9a156d&v=4 + url: https://github.com/zhiquanchi +Jamim: + login: Jamim + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/5607572?u=0cf3027bec78ba4f0b89802430c136bc69847d7a&v=4 + url: https://github.com/Jamim +alvinkhalil: + login: alvinkhalil + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/84583022?u=ab0eeb9ce6ffe93fd9bb23daf782b9867b864149&v=4 + url: https://github.com/alvinkhalil +leylaeminova: + login: leylaeminova + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/100516839?u=35a9ce14bb86d7d7faa25d432f61dec2984cb818&v=4 + url: https://github.com/leylaeminova +UN-9BOT: + login: UN-9BOT + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/111110804?u=39e158937ed795972c2d0400fc521c50e9bfb9e7&v=4 + url: https://github.com/UN-9BOT +gustavoprezoto: + login: gustavoprezoto + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/62812585?u=2e936a0c6a2f11ecf3a735ebd33386100bcfebf8&v=4 + url: https://github.com/gustavoprezoto +johnny630: + login: johnny630 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/2870590?v=4 + url: https://github.com/johnny630 +JCTrapero: + login: JCTrapero + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/109148166?u=bea607a04058176c4c2ae0d7c2e9ec647ccef002&v=4 + url: https://github.com/JCTrapero +ZhibangYue: + login: ZhibangYue + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/93324586?u=20fb23e3718e0364bb217966470d35e0637dd4fe&v=4 + url: https://github.com/ZhibangYue +saeye: + login: saeye + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/62229734?v=4 + url: https://github.com/saeye +Heumhub: + login: Heumhub + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/173761521?v=4 + url: https://github.com/Heumhub +logan2d5: + login: logan2d5 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/146642263?u=dbd6621f8b0330d6919f6a7131277b92e26fbe87&v=4 + url: https://github.com/logan2d5 +RyaWcksn: + login: RyaWcksn + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/42831964?u=0cb4265faf3e3425a89e59b6fddd3eb2de180af0&v=4 + url: https://github.com/RyaWcksn +gerry-sabar: + login: gerry-sabar + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1120123?v=4 + url: https://github.com/gerry-sabar diff --git a/docs/en/data/translators.yml b/docs/en/data/translators.yml index e69de29bb..7b199dc08 100644 --- a/docs/en/data/translators.yml +++ b/docs/en/data/translators.yml @@ -0,0 +1,490 @@ +nilslindemann: + login: nilslindemann + count: 120 + avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 + url: https://github.com/nilslindemann +jaystone776: + login: jaystone776 + count: 46 + avatarUrl: https://avatars.githubusercontent.com/u/11191137?u=299205a95e9b6817a43144a48b643346a5aac5cc&v=4 + url: https://github.com/jaystone776 +tokusumi: + login: tokusumi + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 + url: https://github.com/tokusumi +SwftAlpc: + login: SwftAlpc + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 + url: https://github.com/SwftAlpc +hasansezertasan: + login: hasansezertasan + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan +ceb10n: + login: ceb10n + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 + url: https://github.com/ceb10n +waynerv: + login: waynerv + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 + url: https://github.com/waynerv +AlertRED: + login: AlertRED + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 + url: https://github.com/AlertRED +hard-coders: + login: hard-coders + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 + url: https://github.com/hard-coders +codingjenny: + login: codingjenny + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/103817302?u=3a042740dc0ff58615da0d8679230966fd7693e8&v=4 + url: https://github.com/codingjenny +Xewus: + login: Xewus + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 + url: https://github.com/Xewus +Joao-Pedro-P-Holanda: + login: Joao-Pedro-P-Holanda + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/110267046?u=331bd016326dac4cf3df4848f6db2dbbf8b5f978&v=4 + url: https://github.com/Joao-Pedro-P-Holanda +Smlep: + login: Smlep + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/16785985?u=ffe99fa954c8e774ef1117e58d34aece92051e27&v=4 + url: https://github.com/Smlep +marcelomarkus: + login: marcelomarkus + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/20115018?u=dda090ce9160ef0cd2ff69b1e5ea741283425cba&v=4 + url: https://github.com/marcelomarkus +KaniKim: + login: KaniKim + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=296dbdd490e0eb96e3d45a2608c065603b17dc31&v=4 + url: https://github.com/KaniKim +Vincy1230: + login: Vincy1230 + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/81342412?u=ab5e256a4077a4a91f3f9cd2115ba80780454cbe&v=4 + url: https://github.com/Vincy1230 +rjNemo: + login: rjNemo + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 + url: https://github.com/rjNemo +xzmeng: + login: xzmeng + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/40202897?v=4 + url: https://github.com/xzmeng +pablocm83: + login: pablocm83 + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/28315068?u=3310fbb05bb8bfc50d2c48b6cb64ac9ee4a14549&v=4 + url: https://github.com/pablocm83 +Zhongheng-Cheng: + login: Zhongheng-Cheng + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/95612344?u=a0f7730a3cc7486827965e01a119ad610bda4b0a&v=4 + url: https://github.com/Zhongheng-Cheng +batlopes: + login: batlopes + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/33462923?u=0fb3d7acb316764616f11e4947faf080e49ad8d9&v=4 + url: https://github.com/batlopes +lucasbalieiro: + login: lucasbalieiro + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/37416577?u=5a395a69384e7fa0f9840ea32ef963d3f1cd9da4&v=4 + url: https://github.com/lucasbalieiro +Alexandrhub: + login: Alexandrhub + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 + url: https://github.com/Alexandrhub +Serrones: + login: Serrones + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/22691749?u=4795b880e13ca33a73e52fc0ef7dc9c60c8fce47&v=4 + url: https://github.com/Serrones +RunningIkkyu: + login: RunningIkkyu + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4 + url: https://github.com/RunningIkkyu +Attsun1031: + login: Attsun1031 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/1175560?v=4 + url: https://github.com/Attsun1031 +NinaHwang: + login: NinaHwang + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/79563565?u=241f2cb6d38a2d379536608a8ea5a22ed4b1a3ea&v=4 + url: https://github.com/NinaHwang +tiangolo: + login: tiangolo + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo +rostik1410: + login: rostik1410 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4 + url: https://github.com/rostik1410 +komtaki: + login: komtaki + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 + url: https://github.com/komtaki +JulianMaurin: + login: JulianMaurin + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/63545168?u=b7d15ac865268cbefc2d739e2f23d9aeeac1a622&v=4 + url: https://github.com/JulianMaurin +stlucasgarcia: + login: stlucasgarcia + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=c22d8850e9dc396a8820766a59837f967e14f9a0&v=4 + url: https://github.com/stlucasgarcia +ComicShrimp: + login: ComicShrimp + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=d2fbf412e7730183ce91686ca48d4147e1b7dc74&v=4 + url: https://github.com/ComicShrimp +BilalAlpaslan: + login: BilalAlpaslan + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 + url: https://github.com/BilalAlpaslan +axel584: + login: axel584 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 + url: https://github.com/axel584 +tamtam-fitness: + login: tamtam-fitness + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/62091034?u=8da19a6bd3d02f5d6ba30c7247d5b46c98dd1403&v=4 + url: https://github.com/tamtam-fitness +Limsunoh: + login: Limsunoh + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/90311848?u=f456e0c5709fd50c8cd2898b551558eda14e5f21&v=4 + url: https://github.com/Limsunoh +kwang1215: + login: kwang1215 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/74170199?u=2a63ff6692119dde3f5e5693365b9fcd6f977b08&v=4 + url: https://github.com/kwang1215 +jfunez: + login: jfunez + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/805749?v=4 + url: https://github.com/jfunez +ycd: + login: ycd + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 + url: https://github.com/ycd +mariacamilagl: + login: mariacamilagl + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 + url: https://github.com/mariacamilagl +maoyibo: + login: maoyibo + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/7887703?v=4 + url: https://github.com/maoyibo +blt232018: + login: blt232018 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/43393471?u=172b0e0391db1aa6c1706498d6dfcb003c8a4857&v=4 + url: https://github.com/blt232018 +magiskboy: + login: magiskboy + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/13352088?u=18b6d672523f9e9d98401f31dd50e28bb27d826f&v=4 + url: https://github.com/magiskboy +luccasmmg: + login: luccasmmg + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/11317382?u=65099a5a0d492b89119471f8a7014637cc2e04da&v=4 + url: https://github.com/luccasmmg +lbmendes: + login: lbmendes + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/80999926?u=646619e2f07ac5a7c3f65fe7834197461a4fff9f&v=4 + url: https://github.com/lbmendes +Zssaer: + login: Zssaer + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/45691504?u=4c0c195f25cb5ac6af32acfb0ab35427682938d2&v=4 + url: https://github.com/Zssaer +wdh99: + login: wdh99 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 + url: https://github.com/wdh99 +ChuyuChoyeon: + login: ChuyuChoyeon + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/129537877?u=f0c76f3327817a8b86b422d62e04a34bf2827f2b&v=4 + url: https://github.com/ChuyuChoyeon +ivan-abc: + login: ivan-abc + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 + url: https://github.com/ivan-abc +mojtabapaso: + login: mojtabapaso + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/121169359?u=ced1d5ad673bcd9e949ebf967a4ab50185637443&v=4 + url: https://github.com/mojtabapaso +hsuanchi: + login: hsuanchi + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/24913710?u=0b094ae292292fee093818e37ceb645c114d2bff&v=4 + url: https://github.com/hsuanchi +alejsdev: + login: alejsdev + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 + url: https://github.com/alejsdev +riroan: + login: riroan + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/33053284?u=2d18e3771506ee874b66d6aa2b3b1107fd95c38f&v=4 + url: https://github.com/riroan +nayeonkinn: + login: nayeonkinn + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/98254573?u=64a75ac99b320d4935eff8d1fceea9680fa07473&v=4 + url: https://github.com/nayeonkinn +pe-brian: + login: pe-brian + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/1783138?u=7e6242eb9e85bcf673fa88bbac9dd6dc3f03b1b5&v=4 + url: https://github.com/pe-brian +maxscheijen: + login: maxscheijen + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/47034840?u=eb98f37882528ea349ca4e5255fa64ac3fef0294&v=4 + url: https://github.com/maxscheijen +ilacftemp: + login: ilacftemp + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/159066669?v=4 + url: https://github.com/ilacftemp +devluisrodrigues: + login: devluisrodrigues + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/103431660?u=d9674a3249edc4601d2c712cdebf899918503c3a&v=4 + url: https://github.com/devluisrodrigues +devfernandoa: + login: devfernandoa + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/28360583?u=c4308abd62e8847c9e572e1bb9fe6b9dc9ef8e50&v=4 + url: https://github.com/devfernandoa +kim-sangah: + login: kim-sangah + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/173775778?v=4 + url: https://github.com/kim-sangah +9zimin9: + login: 9zimin9 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/174453744?v=4 + url: https://github.com/9zimin9 +nahyunkeem: + login: nahyunkeem + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/174440096?u=e12401d492eee58570f8914d0872b52e421a776e&v=4 + url: https://github.com/nahyunkeem +alv2017: + login: alv2017 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 +izaguerreiro: + login: izaguerreiro + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/2241504?v=4 + url: https://github.com/izaguerreiro +Xaraxx: + login: Xaraxx + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/29824698?u=dde2e233e22bb5ca1f8bb0c6e353ccd0d06e6066&v=4 + url: https://github.com/Xaraxx +sh0nk: + login: sh0nk + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 + url: https://github.com/sh0nk +dukkee: + login: dukkee + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/36825394?u=ccfd86e6a4f2d093dad6f7544cc875af67fa2df8&v=4 + url: https://github.com/dukkee +oandersonmagalhaes: + login: oandersonmagalhaes + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/83456692?v=4 + url: https://github.com/oandersonmagalhaes +leandrodesouzadev: + login: leandrodesouzadev + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/85115541?u=4eb25f43f1fe23727d61e986cf83b73b86e2a95a&v=4 + url: https://github.com/leandrodesouzadev +kty4119: + login: kty4119 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/49435654?v=4 + url: https://github.com/kty4119 +ASpathfinder: + login: ASpathfinder + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/31813636?u=2090bd1b7abb65cfeff0c618f99f11afa82c0548&v=4 + url: https://github.com/ASpathfinder +jujumilk3: + login: jujumilk3 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/41659814?u=538f7dfef03b59f25e43f10d59a31c19ef538a0c&v=4 + url: https://github.com/jujumilk3 +ayr-ton: + login: ayr-ton + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1090517?u=5cf70a0e0f0dbf084e074e494aa94d7c91a46ba6&v=4 + url: https://github.com/ayr-ton +KdHyeon0661: + login: KdHyeon0661 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/20253352?u=5ae1aae34b091a39f22cbe60a02b79dcbdbea031&v=4 + url: https://github.com/KdHyeon0661 +LorhanSohaky: + login: LorhanSohaky + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 + url: https://github.com/LorhanSohaky +cfraboulet: + login: cfraboulet + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/62244267?u=ed0e286ba48fa1dafd64a08e50f3364b8e12df34&v=4 + url: https://github.com/cfraboulet +dedkot01: + login: dedkot01 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/26196675?u=e2966887124e67932853df4f10f86cb526edc7b0&v=4 + url: https://github.com/dedkot01 +AGolicyn: + login: AGolicyn + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/86262613?u=3c21606ab8d210a061a1673decff1e7d5592b380&v=4 + url: https://github.com/AGolicyn +fhabers21: + login: fhabers21 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/58401847?v=4 + url: https://github.com/fhabers21 +TabarakoAkula: + login: TabarakoAkula + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/113298631?u=add801e370dbc502cd94ce6d3484760d7fef5406&v=4 + url: https://github.com/TabarakoAkula +AhsanSheraz: + login: AhsanSheraz + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/51913596?u=08e31cacb3048be30722c94010ddd028f3fdbec4&v=4 + url: https://github.com/AhsanSheraz +ArtemKhymenko: + login: ArtemKhymenko + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/14346625?u=f2fa553d9e5ec5e0f05d66bd649f7be347169631&v=4 + url: https://github.com/ArtemKhymenko +hasnatsajid: + login: hasnatsajid + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/86589885?u=49958789e6385be624f2c6a55a860c599eb05e2c&v=4 + url: https://github.com/hasnatsajid +alperiox: + login: alperiox + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/34214152?u=2c5acad3461d4dbc2d48371ba86cac56ae9b25cc&v=4 + url: https://github.com/alperiox +emrhnsyts: + login: emrhnsyts + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/42899027?u=ad26798e3f8feed2041c5dd5f87e58933d6c3283&v=4 + url: https://github.com/emrhnsyts +vusallyv: + login: vusallyv + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/85983771?u=53a7b755cb338d9313966dbf2e4e68b512565186&v=4 + url: https://github.com/vusallyv +jackleeio: + login: jackleeio + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/20477587?u=c5184dab6d021733d10c8f975b20e391856303d6&v=4 + url: https://github.com/jackleeio +choi-haram: + login: choi-haram + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/62204475?v=4 + url: https://github.com/choi-haram +imtiaz101325: + login: imtiaz101325 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/54007087?u=7a210ee38a0a30b7536226419b3b799620ad57d9&v=4 + url: https://github.com/imtiaz101325 +waketzheng: + login: waketzheng + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/35413830?u=df19e4fd5bb928e7d086e053ef26a46aad23bf84&v=4 + url: https://github.com/waketzheng +billzhong: + login: billzhong + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1644011?v=4 + url: https://github.com/billzhong +chaoless: + login: chaoless + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/64477804?v=4 + url: https://github.com/chaoless +logan2d5: + login: logan2d5 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/146642263?u=dbd6621f8b0330d6919f6a7131277b92e26fbe87&v=4 + url: https://github.com/logan2d5 +andersonrocha0: + login: andersonrocha0 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/22346169?u=93a1359c8c5461d894802c0cc65bcd09217e7a02&v=4 + url: https://github.com/andersonrocha0 +saeye: + login: saeye + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/62229734?v=4 + url: https://github.com/saeye +timothy-jeong: + login: timothy-jeong + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/53824764?u=659311b6f6aeb0fbb8b527723fd4c83642f04327&v=4 + url: https://github.com/timothy-jeong +gerry-sabar: + login: gerry-sabar + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1120123?v=4 + url: https://github.com/gerry-sabar From 548dd233c39e7722a04d3eb52567cffd1611aba7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 2 Jan 2025 17:22:51 +0000 Subject: [PATCH 619/932] =?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 [skip ci] --- 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 2efe67ff8..3bb7ca9d5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -63,6 +63,7 @@ hide: ### Internal +* 👥 Update FastAPI People - Contributors and Translators. PR [#13145](https://github.com/fastapi/fastapi/pull/13145) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump markdown-include-variants from 0.0.3 to 0.0.4. PR [#13129](https://github.com/fastapi/fastapi/pull/13129) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump inline-snapshot from 0.14.0 to 0.18.1. PR [#13132](https://github.com/fastapi/fastapi/pull/13132) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump mkdocs-macros-plugin from 1.0.5 to 1.3.7. PR [#13133](https://github.com/fastapi/fastapi/pull/13133) by [@dependabot[bot]](https://github.com/apps/dependabot). From 1b8f823a0559ff36d49e6c724f7c9289f8c10a1f Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Thu, 2 Jan 2025 20:44:50 +0000 Subject: [PATCH 620/932] =?UTF-8?q?=F0=9F=91=B7=E2=80=8D=E2=99=80=EF=B8=8F?= =?UTF-8?q?=20Add=20script=20for=20GitHub=20Topic=20Repositories=20and=20u?= =?UTF-8?q?pdate=20External=20Links=20(#13135)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- .github/workflows/topic-repos.yml | 40 ++++++++++++++++ docs/en/data/topic_repos.yml | 0 docs/en/docs/external-links.md | 11 +++-- docs/en/docs/js/custom.js | 36 -------------- docs/en/mkdocs.yml | 1 + scripts/topic_repos.py | 80 +++++++++++++++++++++++++++++++ 6 files changed, 128 insertions(+), 40 deletions(-) create mode 100644 .github/workflows/topic-repos.yml create mode 100644 docs/en/data/topic_repos.yml create mode 100644 scripts/topic_repos.py diff --git a/.github/workflows/topic-repos.yml b/.github/workflows/topic-repos.yml new file mode 100644 index 000000000..3c5c881f1 --- /dev/null +++ b/.github/workflows/topic-repos.yml @@ -0,0 +1,40 @@ +name: Update Topic Repos + +on: + schedule: + - cron: "0 12 1 * *" + workflow_dispatch: + +env: + UV_SYSTEM_PYTHON: 1 + +jobs: + topic-repos: + if: github.repository_owner == 'fastapi' + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Setup uv + uses: astral-sh/setup-uv@v5 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - name: Install GitHub Actions dependencies + run: uv pip install -r requirements-github-actions.txt + - name: Update Topic Repos + run: python ./scripts/topic_repos.py + env: + GITHUB_TOKEN: ${{ secrets.FASTAPI_PR_TOKEN }} diff --git a/docs/en/data/topic_repos.yml b/docs/en/data/topic_repos.yml new file mode 100644 index 000000000..e69de29bb diff --git a/docs/en/docs/external-links.md b/docs/en/docs/external-links.md index 5a3b8ee33..3ed04e5c5 100644 --- a/docs/en/docs/external-links.md +++ b/docs/en/docs/external-links.md @@ -28,9 +28,12 @@ If you have an article, project, tool, or anything related to **FastAPI** that i {% endfor %} {% endfor %} -## Projects +## GitHub Repositories -Latest GitHub projects with the topic `fastapi`: +Most starred GitHub repositories with the topic `fastapi`: -
-
+{% for repo in topic_repos %} + +★ {{repo.stars}} - {{repo.name}} by @{{repo.owner_login}}. + +{% endfor %} diff --git a/docs/en/docs/js/custom.js b/docs/en/docs/js/custom.js index ff17710e2..4c0ada312 100644 --- a/docs/en/docs/js/custom.js +++ b/docs/en/docs/js/custom.js @@ -1,25 +1,3 @@ -const div = document.querySelector('.github-topic-projects') - -async function getDataBatch(page) { - const response = await fetch(`https://api.github.com/search/repositories?q=topic:fastapi&per_page=100&page=${page}`, { headers: { Accept: 'application/vnd.github.mercy-preview+json' } }) - const data = await response.json() - return data -} - -async function getData() { - let page = 1 - let data = [] - let dataBatch = await getDataBatch(page) - data = data.concat(dataBatch.items) - const totalCount = dataBatch.total_count - while (data.length < totalCount) { - page += 1 - dataBatch = await getDataBatch(page) - data = data.concat(dataBatch.items) - } - return data -} - function setupTermynal() { document.querySelectorAll(".use-termynal").forEach(node => { node.style.display = "block"; @@ -158,20 +136,6 @@ async function showRandomAnnouncement(groupId, timeInterval) { } async function main() { - if (div) { - data = await getData() - div.innerHTML = '
    ' - const ul = document.querySelector('.github-topic-projects ul') - data.forEach(v => { - if (v.full_name === 'fastapi/fastapi') { - return - } - const li = document.createElement('li') - li.innerHTML = `★ ${v.stargazers_count} - ${v.full_name} by @${v.owner.login}` - ul.append(li) - }) - } - setupTermynal(); showRandomAnnouncement('announce-left', 5000) showRandomAnnouncement('announce-right', 10000) diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index f2abf7f6b..e9a639d0b 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -72,6 +72,7 @@ plugins: - members: ../en/data/members.yml - sponsors_badge: ../en/data/sponsors_badge.yml - sponsors: ../en/data/sponsors.yml + - topic_repos: ../en/data/topic_repos.yml redirects: redirect_maps: deployment/deta.md: deployment/cloud.md diff --git a/scripts/topic_repos.py b/scripts/topic_repos.py new file mode 100644 index 000000000..bc1497751 --- /dev/null +++ b/scripts/topic_repos.py @@ -0,0 +1,80 @@ +import logging +import secrets +import subprocess +from pathlib import Path + +import yaml +from github import Github +from pydantic import BaseModel, SecretStr +from pydantic_settings import BaseSettings + + +class Settings(BaseSettings): + github_repository: str + github_token: SecretStr + + +class Repo(BaseModel): + name: str + html_url: str + stars: int + owner_login: str + owner_html_url: str + + +def main() -> None: + logging.basicConfig(level=logging.INFO) + settings = Settings() + + logging.info(f"Using config: {settings.model_dump_json()}") + g = Github(settings.github_token.get_secret_value(), per_page=100) + r = g.get_repo(settings.github_repository) + repos = g.search_repositories(query="topic:fastapi") + repos_list = list(repos) + final_repos: list[Repo] = [] + for repo in repos_list[:100]: + if repo.full_name == settings.github_repository: + continue + final_repos.append( + Repo( + name=repo.name, + html_url=repo.html_url, + stars=repo.stargazers_count, + owner_login=repo.owner.login, + owner_html_url=repo.owner.html_url, + ) + ) + data = [repo.model_dump() for repo in final_repos] + + # Local development + # repos_path = Path("../docs/en/data/topic_repos.yml") + repos_path = Path("./docs/en/data/topic_repos.yml") + repos_old_content = repos_path.read_text(encoding="utf-8") + new_repos_content = yaml.dump(data, sort_keys=False, width=200, allow_unicode=True) + if repos_old_content == new_repos_content: + logging.info("The data hasn't changed. Finishing.") + return + repos_path.write_text(new_repos_content, encoding="utf-8") + logging.info("Setting up GitHub Actions git user") + subprocess.run(["git", "config", "user.name", "github-actions"], check=True) + subprocess.run( + ["git", "config", "user.email", "github-actions@github.com"], check=True + ) + branch_name = f"fastapi-topic-repos-{secrets.token_hex(4)}" + logging.info(f"Creating a new branch {branch_name}") + subprocess.run(["git", "checkout", "-b", branch_name], check=True) + logging.info("Adding updated file") + subprocess.run(["git", "add", str(repos_path)], check=True) + logging.info("Committing updated file") + message = "👥 Update FastAPI GitHub topic repositories" + subprocess.run(["git", "commit", "-m", message], check=True) + logging.info("Pushing branch") + subprocess.run(["git", "push", "origin", branch_name], check=True) + logging.info("Creating PR") + pr = r.create_pull(title=message, body=message, base="master", head=branch_name) + logging.info(f"Created PR: {pr.number}") + logging.info("Finished") + + +if __name__ == "__main__": + main() From aa27afdb24cccadc5602a4185b4ca3a52c8a7536 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 2 Jan 2025 20:45:12 +0000 Subject: [PATCH 621/932] =?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 [skip ci] --- 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 3bb7ca9d5..c2050a165 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -63,6 +63,7 @@ hide: ### Internal +* 👷‍♀️ Add script for GitHub Topic Repositories and update External Links. PR [#13135](https://github.com/fastapi/fastapi/pull/13135) by [@alejsdev](https://github.com/alejsdev). * 👥 Update FastAPI People - Contributors and Translators. PR [#13145](https://github.com/fastapi/fastapi/pull/13145) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump markdown-include-variants from 0.0.3 to 0.0.4. PR [#13129](https://github.com/fastapi/fastapi/pull/13129) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump inline-snapshot from 0.14.0 to 0.18.1. PR [#13132](https://github.com/fastapi/fastapi/pull/13132) by [@dependabot[bot]](https://github.com/apps/dependabot). From ccae0c0cb9eb037ce200c90d8c179c618cd984dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 2 Jan 2025 21:00:17 +0000 Subject: [PATCH 622/932] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20GitHu?= =?UTF-8?q?b=20topic=20repositories=20(#13146)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions --- docs/en/data/topic_repos.yml | 495 +++++++++++++++++++++++++++++++++++ 1 file changed, 495 insertions(+) diff --git a/docs/en/data/topic_repos.yml b/docs/en/data/topic_repos.yml index e69de29bb..c1176e55c 100644 --- a/docs/en/data/topic_repos.yml +++ b/docs/en/data/topic_repos.yml @@ -0,0 +1,495 @@ +- name: full-stack-fastapi-template + html_url: https://github.com/fastapi/full-stack-fastapi-template + stars: 28796 + owner_login: fastapi + owner_html_url: https://github.com/fastapi +- name: Hello-Python + html_url: https://github.com/mouredev/Hello-Python + stars: 27554 + owner_login: mouredev + owner_html_url: https://github.com/mouredev +- name: serve + html_url: https://github.com/jina-ai/serve + stars: 21225 + owner_login: jina-ai + owner_html_url: https://github.com/jina-ai +- name: sqlmodel + html_url: https://github.com/fastapi/sqlmodel + stars: 14921 + owner_login: fastapi + owner_html_url: https://github.com/fastapi +- name: HivisionIDPhotos + html_url: https://github.com/Zeyi-Lin/HivisionIDPhotos + stars: 14025 + owner_login: Zeyi-Lin + owner_html_url: https://github.com/Zeyi-Lin +- name: Douyin_TikTok_Download_API + html_url: https://github.com/Evil0ctal/Douyin_TikTok_Download_API + stars: 10001 + owner_login: Evil0ctal + owner_html_url: https://github.com/Evil0ctal +- name: fastapi-best-practices + html_url: https://github.com/zhanymkanov/fastapi-best-practices + stars: 9820 + owner_login: zhanymkanov + owner_html_url: https://github.com/zhanymkanov +- name: awesome-fastapi + html_url: https://github.com/mjhea0/awesome-fastapi + stars: 8899 + owner_login: mjhea0 + owner_html_url: https://github.com/mjhea0 +- name: FastUI + html_url: https://github.com/pydantic/FastUI + stars: 8400 + owner_login: pydantic + owner_html_url: https://github.com/pydantic +- name: nonebot2 + html_url: https://github.com/nonebot/nonebot2 + stars: 6235 + owner_login: nonebot + owner_html_url: https://github.com/nonebot +- name: serge + html_url: https://github.com/serge-chat/serge + stars: 5685 + owner_login: serge-chat + owner_html_url: https://github.com/serge-chat +- name: fastapi-users + html_url: https://github.com/fastapi-users/fastapi-users + stars: 4787 + owner_login: fastapi-users + owner_html_url: https://github.com/fastapi-users +- name: FileCodeBox + html_url: https://github.com/vastsa/FileCodeBox + stars: 4479 + owner_login: vastsa + owner_html_url: https://github.com/vastsa +- name: hatchet + html_url: https://github.com/hatchet-dev/hatchet + stars: 4413 + owner_login: hatchet-dev + owner_html_url: https://github.com/hatchet-dev +- name: chatgpt-web-share + html_url: https://github.com/chatpire/chatgpt-web-share + stars: 4322 + owner_login: chatpire + owner_html_url: https://github.com/chatpire +- name: atrilabs-engine + html_url: https://github.com/Atri-Labs/atrilabs-engine + stars: 4115 + owner_login: Atri-Labs + owner_html_url: https://github.com/Atri-Labs +- name: strawberry + html_url: https://github.com/strawberry-graphql/strawberry + stars: 4084 + owner_login: strawberry-graphql + owner_html_url: https://github.com/strawberry-graphql +- name: dynaconf + html_url: https://github.com/dynaconf/dynaconf + stars: 3844 + owner_login: dynaconf + owner_html_url: https://github.com/dynaconf +- name: poem + html_url: https://github.com/poem-web/poem + stars: 3698 + owner_login: poem-web + owner_html_url: https://github.com/poem-web +- name: polar + html_url: https://github.com/polarsource/polar + stars: 3355 + owner_login: polarsource + owner_html_url: https://github.com/polarsource +- name: opyrator + html_url: https://github.com/ml-tooling/opyrator + stars: 3114 + owner_login: ml-tooling + owner_html_url: https://github.com/ml-tooling +- name: farfalle + html_url: https://github.com/rashadphz/farfalle + stars: 3022 + owner_login: rashadphz + owner_html_url: https://github.com/rashadphz +- name: fastapi-admin + html_url: https://github.com/fastapi-admin/fastapi-admin + stars: 3002 + owner_login: fastapi-admin + owner_html_url: https://github.com/fastapi-admin +- name: docarray + html_url: https://github.com/docarray/docarray + stars: 2998 + owner_login: docarray + owner_html_url: https://github.com/docarray +- name: datamodel-code-generator + html_url: https://github.com/koxudaxi/datamodel-code-generator + stars: 2845 + owner_login: koxudaxi + owner_html_url: https://github.com/koxudaxi +- name: fastapi-realworld-example-app + html_url: https://github.com/nsidnev/fastapi-realworld-example-app + stars: 2832 + owner_login: nsidnev + owner_html_url: https://github.com/nsidnev +- name: uvicorn-gunicorn-fastapi-docker + html_url: https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker + stars: 2727 + owner_login: tiangolo + owner_html_url: https://github.com/tiangolo +- name: WrenAI + html_url: https://github.com/Canner/WrenAI + stars: 2699 + owner_login: Canner + owner_html_url: https://github.com/Canner +- name: LitServe + html_url: https://github.com/Lightning-AI/LitServe + stars: 2664 + owner_login: Lightning-AI + owner_html_url: https://github.com/Lightning-AI +- name: logfire + html_url: https://github.com/pydantic/logfire + stars: 2495 + owner_login: pydantic + owner_html_url: https://github.com/pydantic +- name: huma + html_url: https://github.com/danielgtaylor/huma + stars: 2479 + owner_login: danielgtaylor + owner_html_url: https://github.com/danielgtaylor +- name: tracecat + html_url: https://github.com/TracecatHQ/tracecat + stars: 2446 + owner_login: TracecatHQ + owner_html_url: https://github.com/TracecatHQ +- name: RasaGPT + html_url: https://github.com/paulpierre/RasaGPT + stars: 2378 + owner_login: paulpierre + owner_html_url: https://github.com/paulpierre +- name: best-of-web-python + html_url: https://github.com/ml-tooling/best-of-web-python + stars: 2374 + owner_login: ml-tooling + owner_html_url: https://github.com/ml-tooling +- name: fastapi-react + html_url: https://github.com/Buuntu/fastapi-react + stars: 2274 + owner_login: Buuntu + owner_html_url: https://github.com/Buuntu +- name: nextpy + html_url: https://github.com/dot-agent/nextpy + stars: 2244 + owner_login: dot-agent + owner_html_url: https://github.com/dot-agent +- name: 30-Days-of-Python + html_url: https://github.com/codingforentrepreneurs/30-Days-of-Python + stars: 2154 + owner_login: codingforentrepreneurs + owner_html_url: https://github.com/codingforentrepreneurs +- name: FastAPI-template + html_url: https://github.com/s3rius/FastAPI-template + stars: 2067 + owner_login: s3rius + owner_html_url: https://github.com/s3rius +- name: langserve + html_url: https://github.com/langchain-ai/langserve + stars: 1980 + owner_login: langchain-ai + owner_html_url: https://github.com/langchain-ai +- name: sqladmin + html_url: https://github.com/aminalaee/sqladmin + stars: 1980 + owner_login: aminalaee + owner_html_url: https://github.com/aminalaee +- name: fastapi-utils + html_url: https://github.com/fastapiutils/fastapi-utils + stars: 1970 + owner_login: fastapiutils + owner_html_url: https://github.com/fastapiutils +- name: solara + html_url: https://github.com/widgetti/solara + stars: 1950 + owner_login: widgetti + owner_html_url: https://github.com/widgetti +- name: python-week-2022 + html_url: https://github.com/rochacbruno/python-week-2022 + stars: 1836 + owner_login: rochacbruno + owner_html_url: https://github.com/rochacbruno +- name: supabase-py + html_url: https://github.com/supabase/supabase-py + stars: 1803 + owner_login: supabase + owner_html_url: https://github.com/supabase +- name: mangum + html_url: https://github.com/Kludex/mangum + stars: 1760 + owner_login: Kludex + owner_html_url: https://github.com/Kludex +- name: manage-fastapi + html_url: https://github.com/ycd/manage-fastapi + stars: 1704 + owner_login: ycd + owner_html_url: https://github.com/ycd +- name: ormar + html_url: https://github.com/collerek/ormar + stars: 1688 + owner_login: collerek + owner_html_url: https://github.com/collerek +- name: agentkit + html_url: https://github.com/BCG-X-Official/agentkit + stars: 1615 + owner_login: BCG-X-Official + owner_html_url: https://github.com/BCG-X-Official +- name: langchain-serve + html_url: https://github.com/jina-ai/langchain-serve + stars: 1615 + owner_login: jina-ai + owner_html_url: https://github.com/jina-ai +- name: termpair + html_url: https://github.com/cs01/termpair + stars: 1613 + owner_login: cs01 + owner_html_url: https://github.com/cs01 +- name: coronavirus-tracker-api + html_url: https://github.com/ExpDev07/coronavirus-tracker-api + stars: 1591 + owner_login: ExpDev07 + owner_html_url: https://github.com/ExpDev07 +- name: piccolo + html_url: https://github.com/piccolo-orm/piccolo + stars: 1477 + owner_login: piccolo-orm + owner_html_url: https://github.com/piccolo-orm +- name: fastapi-crudrouter + html_url: https://github.com/awtkns/fastapi-crudrouter + stars: 1435 + owner_login: awtkns + owner_html_url: https://github.com/awtkns +- name: fastapi-cache + html_url: https://github.com/long2ice/fastapi-cache + stars: 1412 + owner_login: long2ice + owner_html_url: https://github.com/long2ice +- name: openapi-python-client + html_url: https://github.com/openapi-generators/openapi-python-client + stars: 1398 + owner_login: openapi-generators + owner_html_url: https://github.com/openapi-generators +- name: awesome-fastapi-projects + html_url: https://github.com/Kludex/awesome-fastapi-projects + stars: 1386 + owner_login: Kludex + owner_html_url: https://github.com/Kludex +- name: awesome-python-resources + html_url: https://github.com/DjangoEx/awesome-python-resources + stars: 1371 + owner_login: DjangoEx + owner_html_url: https://github.com/DjangoEx +- name: budgetml + html_url: https://github.com/ebhy/budgetml + stars: 1342 + owner_login: ebhy + owner_html_url: https://github.com/ebhy +- name: slowapi + html_url: https://github.com/laurentS/slowapi + stars: 1289 + owner_login: laurentS + owner_html_url: https://github.com/laurentS +- name: fastapi-pagination + html_url: https://github.com/uriyyo/fastapi-pagination + stars: 1240 + owner_login: uriyyo + owner_html_url: https://github.com/uriyyo +- name: fastapi-boilerplate + html_url: https://github.com/teamhide/fastapi-boilerplate + stars: 1173 + owner_login: teamhide + owner_html_url: https://github.com/teamhide +- name: fastapi-tutorial + html_url: https://github.com/liaogx/fastapi-tutorial + stars: 1162 + owner_login: liaogx + owner_html_url: https://github.com/liaogx +- name: fastapi-amis-admin + html_url: https://github.com/amisadmin/fastapi-amis-admin + stars: 1118 + owner_login: amisadmin + owner_html_url: https://github.com/amisadmin +- name: fastapi-code-generator + html_url: https://github.com/koxudaxi/fastapi-code-generator + stars: 1095 + owner_login: koxudaxi + owner_html_url: https://github.com/koxudaxi +- name: bolt-python + html_url: https://github.com/slackapi/bolt-python + stars: 1086 + owner_login: slackapi + owner_html_url: https://github.com/slackapi +- name: odmantic + html_url: https://github.com/art049/odmantic + stars: 1085 + owner_login: art049 + owner_html_url: https://github.com/art049 +- name: langchain-extract + html_url: https://github.com/langchain-ai/langchain-extract + stars: 1068 + owner_login: langchain-ai + owner_html_url: https://github.com/langchain-ai +- name: fastapi_production_template + html_url: https://github.com/zhanymkanov/fastapi_production_template + stars: 1059 + owner_login: zhanymkanov + owner_html_url: https://github.com/zhanymkanov +- name: fastapi-alembic-sqlmodel-async + html_url: https://github.com/jonra1993/fastapi-alembic-sqlmodel-async + stars: 1031 + owner_login: jonra1993 + owner_html_url: https://github.com/jonra1993 +- name: prometheus-fastapi-instrumentator + html_url: https://github.com/trallnag/prometheus-fastapi-instrumentator + stars: 1013 + owner_login: trallnag + owner_html_url: https://github.com/trallnag +- name: runhouse + html_url: https://github.com/run-house/runhouse + stars: 988 + owner_login: run-house + owner_html_url: https://github.com/run-house +- name: lanarky + html_url: https://github.com/ajndkr/lanarky + stars: 982 + owner_login: ajndkr + owner_html_url: https://github.com/ajndkr +- name: autollm + html_url: https://github.com/viddexa/autollm + stars: 981 + owner_login: viddexa + owner_html_url: https://github.com/viddexa +- name: bedrock-claude-chat + html_url: https://github.com/aws-samples/bedrock-claude-chat + stars: 977 + owner_login: aws-samples + owner_html_url: https://github.com/aws-samples +- name: SurfSense + html_url: https://github.com/MODSetter/SurfSense + stars: 971 + owner_login: MODSetter + owner_html_url: https://github.com/MODSetter +- name: restish + html_url: https://github.com/danielgtaylor/restish + stars: 954 + owner_login: danielgtaylor + owner_html_url: https://github.com/danielgtaylor +- name: secure + html_url: https://github.com/TypeError/secure + stars: 911 + owner_login: TypeError + owner_html_url: https://github.com/TypeError +- name: langcorn + html_url: https://github.com/msoedov/langcorn + stars: 909 + owner_login: msoedov + owner_html_url: https://github.com/msoedov +- name: energy-forecasting + html_url: https://github.com/iusztinpaul/energy-forecasting + stars: 884 + owner_login: iusztinpaul + owner_html_url: https://github.com/iusztinpaul +- name: vue-fastapi-admin + html_url: https://github.com/mizhexiaoxiao/vue-fastapi-admin + stars: 863 + owner_login: mizhexiaoxiao + owner_html_url: https://github.com/mizhexiaoxiao +- name: authx + html_url: https://github.com/yezz123/authx + stars: 850 + owner_login: yezz123 + owner_html_url: https://github.com/yezz123 +- name: titiler + html_url: https://github.com/developmentseed/titiler + stars: 809 + owner_login: developmentseed + owner_html_url: https://github.com/developmentseed +- name: marker-api + html_url: https://github.com/adithya-s-k/marker-api + stars: 792 + owner_login: adithya-s-k + owner_html_url: https://github.com/adithya-s-k +- name: fastapi_best_architecture + html_url: https://github.com/fastapi-practices/fastapi_best_architecture + stars: 742 + owner_login: fastapi-practices + owner_html_url: https://github.com/fastapi-practices +- name: fastapi-mail + html_url: https://github.com/sabuhish/fastapi-mail + stars: 728 + owner_login: sabuhish + owner_html_url: https://github.com/sabuhish +- name: fastcrud + html_url: https://github.com/igorbenav/fastcrud + stars: 727 + owner_login: igorbenav + owner_html_url: https://github.com/igorbenav +- name: annotated-py-projects + html_url: https://github.com/hhstore/annotated-py-projects + stars: 722 + owner_login: hhstore + owner_html_url: https://github.com/hhstore +- name: FastAPI-boilerplate + html_url: https://github.com/igorbenav/FastAPI-boilerplate + stars: 716 + owner_login: igorbenav + owner_html_url: https://github.com/igorbenav +- name: lccn_predictor + html_url: https://github.com/baoliay2008/lccn_predictor + stars: 707 + owner_login: baoliay2008 + owner_html_url: https://github.com/baoliay2008 +- name: chatGPT-web + html_url: https://github.com/mic1on/chatGPT-web + stars: 706 + owner_login: mic1on + owner_html_url: https://github.com/mic1on +- name: fastapi-do-zero + html_url: https://github.com/dunossauro/fastapi-do-zero + stars: 702 + owner_login: dunossauro + owner_html_url: https://github.com/dunossauro +- name: linbing + html_url: https://github.com/taomujian/linbing + stars: 699 + owner_login: taomujian + owner_html_url: https://github.com/taomujian +- name: fastapi-observability + html_url: https://github.com/blueswen/fastapi-observability + stars: 698 + owner_login: blueswen + owner_html_url: https://github.com/blueswen +- name: FastAPI-Backend-Template + html_url: https://github.com/Aeternalis-Ingenium/FastAPI-Backend-Template + stars: 682 + owner_login: Aeternalis-Ingenium + owner_html_url: https://github.com/Aeternalis-Ingenium +- name: learn-generative-ai + html_url: https://github.com/panaverse/learn-generative-ai + stars: 673 + owner_login: panaverse + owner_html_url: https://github.com/panaverse +- name: fastapi-jwt-auth + html_url: https://github.com/IndominusByte/fastapi-jwt-auth + stars: 668 + owner_login: IndominusByte + owner_html_url: https://github.com/IndominusByte +- name: pity + html_url: https://github.com/wuranxu/pity + stars: 660 + owner_login: wuranxu + owner_html_url: https://github.com/wuranxu +- name: starlette-admin + html_url: https://github.com/jowilf/starlette-admin + stars: 653 + owner_login: jowilf + owner_html_url: https://github.com/jowilf +- name: fastapi_login + html_url: https://github.com/MushroomMaula/fastapi_login + stars: 650 + owner_login: MushroomMaula + owner_html_url: https://github.com/MushroomMaula From 4f04377270af398a96a226ef0bc8ee853a008bdf Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 2 Jan 2025 21:01:23 +0000 Subject: [PATCH 623/932] =?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 [skip ci] --- 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 c2050a165..e37540862 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -63,6 +63,7 @@ hide: ### Internal +* 👥 Update FastAPI GitHub topic repositories. PR [#13146](https://github.com/fastapi/fastapi/pull/13146) by [@tiangolo](https://github.com/tiangolo). * 👷‍♀️ Add script for GitHub Topic Repositories and update External Links. PR [#13135](https://github.com/fastapi/fastapi/pull/13135) by [@alejsdev](https://github.com/alejsdev). * 👥 Update FastAPI People - Contributors and Translators. PR [#13145](https://github.com/fastapi/fastapi/pull/13145) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump markdown-include-variants from 0.0.3 to 0.0.4. PR [#13129](https://github.com/fastapi/fastapi/pull/13129) by [@dependabot[bot]](https://github.com/apps/dependabot). From 994340f839f8a833e400e554d5d659dad461d012 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 3 Jan 2025 09:47:55 +0000 Subject: [PATCH 624/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20ad?= =?UTF-8?q?ditional=5Fstatus=5Fcodes=20(#13149)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_tutorial001.py | 26 ++++++++++++++++--- .../test_tutorial001_an.py | 17 ------------ .../test_tutorial001_an_py310.py | 26 ------------------- .../test_tutorial001_an_py39.py | 26 ------------------- .../test_tutorial001_py310.py | 26 ------------------- 5 files changed, 22 insertions(+), 99 deletions(-) delete mode 100644 tests/test_tutorial/test_additional_status_codes/test_tutorial001_an.py delete mode 100644 tests/test_tutorial/test_additional_status_codes/test_tutorial001_an_py310.py delete mode 100644 tests/test_tutorial/test_additional_status_codes/test_tutorial001_an_py39.py delete mode 100644 tests/test_tutorial/test_additional_status_codes/test_tutorial001_py310.py diff --git a/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py b/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py index c382cb5fe..b304f7015 100644 --- a/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py +++ b/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py @@ -1,17 +1,35 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.additional_status_codes.tutorial001 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.additional_status_codes.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_update(): +def test_update(client: TestClient): response = client.put("/items/foo", json={"name": "Wrestlers"}) assert response.status_code == 200, response.text assert response.json() == {"name": "Wrestlers", "size": None} -def test_create(): +def test_create(client: TestClient): response = client.put("/items/red", json={"name": "Chillies"}) assert response.status_code == 201, response.text assert response.json() == {"name": "Chillies", "size": None} diff --git a/tests/test_tutorial/test_additional_status_codes/test_tutorial001_an.py b/tests/test_tutorial/test_additional_status_codes/test_tutorial001_an.py deleted file mode 100644 index 2cb2bb993..000000000 --- a/tests/test_tutorial/test_additional_status_codes/test_tutorial001_an.py +++ /dev/null @@ -1,17 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.additional_status_codes.tutorial001_an import app - -client = TestClient(app) - - -def test_update(): - response = client.put("/items/foo", json={"name": "Wrestlers"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Wrestlers", "size": None} - - -def test_create(): - response = client.put("/items/red", json={"name": "Chillies"}) - assert response.status_code == 201, response.text - assert response.json() == {"name": "Chillies", "size": None} diff --git a/tests/test_tutorial/test_additional_status_codes/test_tutorial001_an_py310.py b/tests/test_tutorial/test_additional_status_codes/test_tutorial001_an_py310.py deleted file mode 100644 index c7660a392..000000000 --- a/tests/test_tutorial/test_additional_status_codes/test_tutorial001_an_py310.py +++ /dev/null @@ -1,26 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.additional_status_codes.tutorial001_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_update(client: TestClient): - response = client.put("/items/foo", json={"name": "Wrestlers"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Wrestlers", "size": None} - - -@needs_py310 -def test_create(client: TestClient): - response = client.put("/items/red", json={"name": "Chillies"}) - assert response.status_code == 201, response.text - assert response.json() == {"name": "Chillies", "size": None} diff --git a/tests/test_tutorial/test_additional_status_codes/test_tutorial001_an_py39.py b/tests/test_tutorial/test_additional_status_codes/test_tutorial001_an_py39.py deleted file mode 100644 index 303c5dbae..000000000 --- a/tests/test_tutorial/test_additional_status_codes/test_tutorial001_an_py39.py +++ /dev/null @@ -1,26 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.additional_status_codes.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_update(client: TestClient): - response = client.put("/items/foo", json={"name": "Wrestlers"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Wrestlers", "size": None} - - -@needs_py39 -def test_create(client: TestClient): - response = client.put("/items/red", json={"name": "Chillies"}) - assert response.status_code == 201, response.text - assert response.json() == {"name": "Chillies", "size": None} diff --git a/tests/test_tutorial/test_additional_status_codes/test_tutorial001_py310.py b/tests/test_tutorial/test_additional_status_codes/test_tutorial001_py310.py deleted file mode 100644 index 02f2e188c..000000000 --- a/tests/test_tutorial/test_additional_status_codes/test_tutorial001_py310.py +++ /dev/null @@ -1,26 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.additional_status_codes.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_update(client: TestClient): - response = client.put("/items/foo", json={"name": "Wrestlers"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Wrestlers", "size": None} - - -@needs_py310 -def test_create(client: TestClient): - response = client.put("/items/red", json={"name": "Chillies"}) - assert response.status_code == 201, response.text - assert response.json() == {"name": "Chillies", "size": None} From 9eb712802e5e1c2eda0d29771ebfd097ded9ea46 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 3 Jan 2025 09:48:22 +0000 Subject: [PATCH 625/932] =?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 [skip ci] --- 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 e37540862..20dfa25d1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Refactors + +* ✅ Simplify tests for additional_status_codes. PR [#13149](https://github.com/fastapi/fastapi/pull/13149) by [@tiangolo](https://github.com/tiangolo). + ### Docs * 👷 Add new GitHub Action to update contributors, translators, and translation reviewers. PR [#13136](https://github.com/fastapi/fastapi/pull/13136) by [@tiangolo](https://github.com/tiangolo). From 27c700a6d347814e1bbfd1cb8969225097e01819 Mon Sep 17 00:00:00 2001 From: Zhongheng Cheng Date: Fri, 3 Jan 2025 08:16:52 -0800 Subject: [PATCH 626/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/fastapi-cli.md`=20(#13102)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/fastapi-cli.md | 74 +++++++++++++++++-------------------- 1 file changed, 33 insertions(+), 41 deletions(-) diff --git a/docs/zh/docs/fastapi-cli.md b/docs/zh/docs/fastapi-cli.md index f532c7fb7..8a70e1d80 100644 --- a/docs/zh/docs/fastapi-cli.md +++ b/docs/zh/docs/fastapi-cli.md @@ -9,47 +9,39 @@
    ```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 dev main.py + + FastAPI Starting development server 🚀 + + Searching for package file structure from directories with + __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with the + following code: + + from main import app + + app Using import string: main:app + + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: + + 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 [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. ```
    From 91738b5ae72a96a5d0255ca7c0ba224f63a6ff04 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 3 Jan 2025 16:17:14 +0000 Subject: [PATCH 627/932] =?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 [skip ci] --- 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 20dfa25d1..4690d83e4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Translations +* 🌐 Update Chinese translation for `docs/zh/docs/fastapi-cli.md`. PR [#13102](https://github.com/fastapi/fastapi/pull/13102) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Add new Spanish translations for all docs with new LLM-assisted system using PydanticAI. PR [#13122](https://github.com/fastapi/fastapi/pull/13122) by [@tiangolo](https://github.com/tiangolo). * 🌐 Update existing Spanish translations using the new LLM-assisted system using PydanticAI. PR [#13118](https://github.com/fastapi/fastapi/pull/13118) by [@tiangolo](https://github.com/tiangolo). * 🌐 Update Chinese translation for `docs/zh/docs/advanced/security/oauth2-scopes.md`. PR [#13110](https://github.com/fastapi/fastapi/pull/13110) by [@ChenPu2002](https://github.com/ChenPu2002). From 87fb46bcacbb5d4abc9f7ff93f588673ecf6510d Mon Sep 17 00:00:00 2001 From: Zhongheng Cheng Date: Fri, 3 Jan 2025 08:26:01 -0800 Subject: [PATCH 628/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20`fastapi-cli`?= =?UTF-8?q?=20UI=20examples=20in=20docs=20(#13107)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/deployment/manually.md | 66 +++++++---------- docs/en/docs/deployment/server-workers.md | 87 ++++++++++------------- docs/en/docs/tutorial/first-steps.md | 74 +++++++++---------- docs/en/docs/tutorial/index.md | 75 +++++++++---------- 4 files changed, 130 insertions(+), 172 deletions(-) diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index 3f7c7a008..19ba98075 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -7,45 +7,33 @@ In short, use `fastapi run` to serve your FastAPI application:
    ```console -$ fastapi run main.py -INFO Using path main.py -INFO Resolved absolute path /home/user/code/awesomeapp/main.py -INFO Searching for package file structure from directories with __init__.py files -INFO Importing from /home/user/code/awesomeapp - - ╭─ Python module file ─╮ - │ │ - │ 🐍 main.py │ - │ │ - ╰──────────────────────╯ - -INFO Importing module main -INFO Found importable FastAPI app - - ╭─ Importable FastAPI app ─╮ - │ │ - │ from main import app │ - │ │ - ╰──────────────────────────╯ - -INFO Using import string main:app - - ╭─────────── FastAPI CLI - Production mode ───────────╮ - │ │ - │ Serving at: http://0.0.0.0:8000 │ - │ │ - │ API docs: http://0.0.0.0:8000/docs │ - │ │ - │ Running in production mode, for development use: │ - │ │ - fastapi dev - │ │ - ╰─────────────────────────────────────────────────────╯ - -INFO: Started server process [2306215] -INFO: Waiting for application startup. -INFO: Application startup complete. -INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) +$ fastapi run main.py + + FastAPI Starting production server 🚀 + + Searching for package file structure from directories + with __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with + the following code: + + from main import app + + app Using import string: main:app + + server Server started at http://0.0.0.0:8000 + server Documentation at http://0.0.0.0:8000/docs + + Logs: + + INFO Started server process [2306215] + INFO Waiting for application startup. + INFO Application startup complete. + INFO Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C + to quit) ```
    diff --git a/docs/en/docs/deployment/server-workers.md b/docs/en/docs/deployment/server-workers.md index 622c10a30..5d6b0d00a 100644 --- a/docs/en/docs/deployment/server-workers.md +++ b/docs/en/docs/deployment/server-workers.md @@ -36,56 +36,43 @@ If you use the `fastapi` command:
    ```console -$
     fastapi run --workers 4 main.py
    -INFO     Using path main.py
    -INFO     Resolved absolute path /home/user/code/awesomeapp/main.py
    -INFO     Searching for package file structure from directories with __init__.py files
    -INFO     Importing from /home/user/code/awesomeapp
    -
    - ╭─ Python module file ─╮
    - │                      │
    - │  🐍 main.py          │
    - │                      │
    - ╰──────────────────────╯
    -
    -INFO     Importing module main
    -INFO     Found importable FastAPI app
    -
    - ╭─ Importable FastAPI app ─╮
    - │                          │
    - │  from main import app    │
    - │                          │
    - ╰──────────────────────────╯
    -
    -INFO     Using import string main:app
    -
    - ╭─────────── FastAPI CLI - Production mode ───────────╮
    - │                                                     │
    - │  Serving at: http://0.0.0.0:8000                    │
    - │                                                     │
    - │  API docs: http://0.0.0.0:8000/docs                 │
    - │                                                     │
    - │  Running in production mode, for development use:   │
    - │                                                     │
    - fastapi dev
    - │                                                     │
    - ╰─────────────────────────────────────────────────────╯
    -
    -INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
    -INFO:     Started parent process [27365]
    -INFO:     Started server process [27368]
    -INFO:     Waiting for application startup.
    -INFO:     Application startup complete.
    -INFO:     Started server process [27369]
    -INFO:     Waiting for application startup.
    -INFO:     Application startup complete.
    -INFO:     Started server process [27370]
    -INFO:     Waiting for application startup.
    -INFO:     Application startup complete.
    -INFO:     Started server process [27367]
    -INFO:     Waiting for application startup.
    -INFO:     Application startup complete.
    -
    +$ fastapi run --workers 4 main.py + + FastAPI Starting production server 🚀 + + Searching for package file structure from directories with + __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with the + following code: + + from main import app + + app Using import string: main:app + + server Server started at http://0.0.0.0:8000 + server Documentation at http://0.0.0.0:8000/docs + + Logs: + + INFO Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to + quit) + INFO Started parent process [27365] + INFO Started server process [27368] + INFO Started server process [27369] + INFO Started server process [27370] + INFO Started server process [27367] + INFO Waiting for application startup. + INFO Waiting for application startup. + INFO Waiting for application startup. + INFO Waiting for application startup. + INFO Application startup complete. + INFO Application startup complete. + INFO Application startup complete. + INFO Application startup complete. ```
    diff --git a/docs/en/docs/tutorial/first-steps.md b/docs/en/docs/tutorial/first-steps.md index 783295933..4f1b1f116 100644 --- a/docs/en/docs/tutorial/first-steps.md +++ b/docs/en/docs/tutorial/first-steps.md @@ -11,47 +11,39 @@ Run the live server:
    ```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 dev main.py + + FastAPI Starting development server 🚀 + + Searching for package file structure from directories + with __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with + the following code: + + from main import app + + app Using import string: main:app + + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: + + 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 [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. ```
    diff --git a/docs/en/docs/tutorial/index.md b/docs/en/docs/tutorial/index.md index bf613aace..4fe38256c 100644 --- a/docs/en/docs/tutorial/index.md +++ b/docs/en/docs/tutorial/index.md @@ -15,48 +15,39 @@ To run any of the examples, copy the code to a file `main.py`, and start `fastap
    ```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 dev main.py + + FastAPI Starting development server 🚀 + + Searching for package file structure from directories + with __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with + the following code: + + from main import app + + app Using import string: main:app + + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: + + 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 [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. ```
    From 01a1fc8d156fa5296b1bd460f9dc7216062d07f2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 3 Jan 2025 16:26:28 +0000 Subject: [PATCH 629/932] =?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 [skip ci] --- 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 4690d83e4..1b5fb25c7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Docs +* 📝 Update `fastapi-cli` UI examples in docs. PR [#13107](https://github.com/fastapi/fastapi/pull/13107) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 👷 Add new GitHub Action to update contributors, translators, and translation reviewers. PR [#13136](https://github.com/fastapi/fastapi/pull/13136) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix typo in `docs/en/docs/virtual-environments.md`. PR [#13124](https://github.com/fastapi/fastapi/pull/13124) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix error in `docs/en/docs/contributing.md`. PR [#12899](https://github.com/fastapi/fastapi/pull/12899) by [@kingsubin](https://github.com/kingsubin). From 8416e3ee235f7600bd562b207b14b882b46711b2 Mon Sep 17 00:00:00 2001 From: Hamza Kyamanywa Date: Sat, 4 Jan 2025 01:28:35 +0700 Subject: [PATCH 630/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20image=20in=20bo?= =?UTF-8?q?dy-nested-model=20docs=20(#11063)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tutorial/body-nested-models/image01.png | Bin 40992 -> 44866 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/docs/en/docs/img/tutorial/body-nested-models/image01.png b/docs/en/docs/img/tutorial/body-nested-models/image01.png index f3644ce792ea70e1e1f701c99291aaef7e83172a..1f7e07cfef9b0d94c66668ff0fa7396bd1c4cd5e 100644 GIT binary patch literal 44866 zcmeFYV|ZTQ_AVSWX=7WB+1PH_*tTukW@EdtZKJW#IC)~*I7$24IRCxRxz7IZet55I zKVP1?)*NfhHOJH#_dQmKw4^W$Bqk&f5D<*WHvw57Adn*k zmF;D9oIYFIS{a&{8+^8Ru{QW@;A~$PZ{;)+Lu(j@Ky^ z(8N>@c9MMk7Al4KnY6Dh@wefu#Add$dtR{jFoh_1GJ8}3Q5U~aK<#W{{r0v%K%6|z);fA-2KJwI4U9}Ixd={MItV_S=yMS$F-g!$So0eg zn|yP%HIQ?al-F}L(__;o;NgbkbY_23U}0dd^V!+L+|rKSnTz1JUiP>0`)wM6&%Z_N z&A14ZC8R&|TiF_XW~64Mru`!5Y~n~yzzzAC(^lV*T~?I^z>ieB)-_WSla72f3dV9d{^;Dhk${do~?gSMTm%Gf^`HMz{yqSI*KTR|ml58~LGxZiLq|3F7qQSWGEg$nw>SRBWB;fSH?TB% zule5|k+L;0c(cKKZ@CEQ2x#6dN%NN}-$sV!??dx$pa1WF|83+yvhjb-^x zg#SCc{%fxP$O8Y7@PB95|G&%y`48vL!1B$bb9!^#G=4!dyt#cJ?D$0FKfV3jKj{Yp z0euD%5%?uP3Y@$jvNk))|#F|{mYl|-VhETjvoCP}&Md$aCJmG2P2C+KA0Km+e&oiXUA7oZR7 z1n4;=_ndfecyLBL)?>GiT)WVxm)i_RoVt2?OYnT3@crTWmZLchKE3_FT|{?M|Bu24 z$9IuW_`OV<*Ja1aR^UAC7Sv7x{y8_bRj1R$t(xV_&d2f?pHyq33#%rb@4fYgO(iQR zpM_wX9J?5Z`cJmDYTT@~W-$qpul=^e$vr}~aEjt;0{L zKa%^MC+yDL;e1u&4BPTX>hOURi_8Q_s8|!-ZRc5$K!lUb<#I()xx8`R(&Ou*!Q>^8 zzs1JZ1*j56p4)(iy)S!7a>?59sC*nwe?|U%Ah*ekAKvb92xP_cy#(xaQ;jKzSCj7@ z^tE7x^88C$4adVd>#UUaPpsG~o?EQ&f{rbMLs*;}2^!hT!Kq_D`tN&8Q3yGw%T18f zdiYGKHMGYTT9QoHbe67U=e|r7Gi9E>c5IOEhHK0QX+fi?KsAMovZXdB(u0}jl10GG z`Y49)62WY_wU-46C1mhrK-IYK_{9)Ud~79^{87}*czq(9h3!g%^-{Ek{9%osi#lt0 z$ILyiI0pi|Jm1p^zxjL5r1?<4OBX>Tj+I>V?1y&nr_(W_gQ`AlPhdIxM!VJR5tT2{ z$wTY+lgew#!gZ4Yx-pgSW4P??vm!Lu)fNYYuQ#>c4CctRmU_b+2JXo1nRM-k2Tn~E zGAX__f4M8&W&}FQze8)nOJ?fC^jMv#YY_tDKHccFsZJs&lvCg{RgLrHFfY8t20W|m z*`y8YiNefB$X~>Bi7)_isw+f}-Ue|DTvS6Ogd=gb z>Gnw?q)WIWpdYfdr9rwKA5Y0>NDkwZyEQdve?I{5@kEtD!fTCpZ~z5p&+`G%uiuOV zHDf?R)afr7k{CT zf3s}52R@Pb_E|hv+F)>dTEnVpWeSCM78K8L)S}(JGB&p7W4bysgDeaF`<&$N(=(4{xs=!>hP?<;|wZfY+Z*BhW20dO|B>tIs9M)peK=+z}t7 zz=HK3j-wcQ%+Snu)CG$ul2u~ywD;p&J=-17j#Y%=c351B%t@qH=wt6ZUVAPsnmBEy zSrISBWfsEdA?624*j{YhRK6ZiF$6>z>Kta+DzGz-@fFWmcD)D^3K+pR8RPq>v6P3HWr=I(TEBIedf zMMje|qavV?iU($}OE#01YiUoWgDbs&cWk$%r<%HUy-*7?T?j!$M7&=0iw`S{89j?G zGZ4v8-O^e?ZBGrXH9oLI-@(ni>q!NC0}i%N$^*#EDA;0b;7LaCG2C^-afFl)Bw`jiFWEB5hg;-GB?cB4*}%FvU25I}rY z5WpP_mkQ21*eYq&T5TWaS-C_Y^khsNv@wlDqu`=`io|mc^Ku+%#TvGwy>apiG>A!w z|7D?son?Fuo`P&`z7$@x#9g%1h}Cm9c-QY;2Y<$xHR*RL&+Qo7=E0K?e^Uhv4kF~Q zx26@mWRXo*k?=EIUtW#olI>$1@GIV`NLFTiAZJah9pu|WL0qWtVaEEAA9gB`0}D-9 zI{M8~LdjdsbWCRZJFoI*X|P&fIpAf=aNpFvV)TqNn~Cd%85nplh7pyO-~KIRYeKG28hj_KvQH3GMUxr-AJM# zrR?f@wb7tl#9Rr99BSk}N2=O*+x!Q!@}Bm}K#eNE-a?-6@~FV`F7lOM&-ulEbEB=j zA`AJwvZG3f))^810NRwgx)9(6lo9!M!}g0V>({C}<@wszy8iEK-nPQ*>?^M}<#4Iu%GeEKP zHrwbM`ZuK{>e2kYbELaSQK7^*U(XXFz5#t3!~2XdZcb+r8MzQOTZS^cw$WrGC~Ia= zJv7_t7$~gVruFmd_JxNSDEKI-n*iZ)k5$St$f0?Upxoiv%973CCl`|DYB;u*E1-H) zFnc8QYD3e8fTOn~Kd=>N@B=hnsO1&%X8xM!Xc&zy=VS}Ft3fz#3G9GVUx`54TD>o~ zhS>x%j|v^kNXOvRa=1M@RPTDvG~`L z^YLP~M0kIVHdH>go$$;21_SRrgBJ*+TIKPopT#Zihzpd62N4)g2iNgNORQS9*+XmU zopJ4$yC^pqE014!2vb(~lpY-%KP$Iqtyd>J&LSC3nF3SovawU$c`y-$GEBsAIs}8j zrWs}50*G|T&puK+gh;D{Ph)n|_H22}|$;Q{EjUjPv^Y2*rm zLBxb@WX#SZm07WLR=x)d`yct)H6OLlpsfIMorI)eu}rv`KrJ(MMnvN;{-Rq*C9U?h-3^G zlD##1qMgPS?@WnT18C@;P0J(`nWVW_@?lwN)Hkn$$>fVzAAE zbSRwmU==*ZT%CBy3e;gLa2@t45|(S6Yh5OlV@Tf>TSG-uW8a zttM@iSjIMqIoa%wnWLY5UWVhDR+JokZF<;#UL0`oE8$FsU&3*mg1b%)!P~gtR_=L| z2PIUJy#rE=y!ZuI;~$H0?`X~PBl;RHLncsKIWVPRYaYfcY+D=r<`e}SL-1-0OFs_{ z3z?j|dcIcVMDn2rbo*6QD_#TLuC}MCXi96@C3RS84B#8#IYn+WFlUIb4-yEy2 zSm4mOF-1q6N2EimSNhLzATLLdlrF(eFgnZ6(_3Pp%c7rY#h$}X@a1A0-Z;daR%+H# zPX`kAt~3PCm>gU-IGCe{k#NOzog#*@jmsJ zdgKCm-$R!79pK&Hhvy3}`Akgrr?}jyAE@!a*Zy7Xn>N}XA$3a4wZ)8k!!y9rj;*i& znW+@kBezEP;r7}Eja^9k*aQms%!@AZY`JwqWNN$66+b zV=gW80IIhxw7@T1pNHe7_h$uv262~f#2QU|c7k=gG;P%EPy@*BS_fHCm#nP_e1#&T zzTfF9$%iD>-KGbz)7%;%88$$(Lrc#ZGtIv?GY_4T|Jg;rbj@ubWA6E`jWy-?}={`1*Yq6&%~5qiPk|mpzF0iABS`J?6Tgn=YrT> zZ*6<;!`*Rfa_SY6-GD58W;`z#GVU>q?kEf<7{)ST-`7AJ5SZvWc0LA0=(3CWK42>* z-QWnbrdwMbk+Mb(8(1u%5P*|@wO>DPd=Jm-Vomu#ue8aDDkcL3uFZOy+!zeBZiT2g zlv@s4XcG=uA7#J_LCxrxnlN!o&&zhK-1go zIFEon8uJ~$uYB}R9Tbut@yLUL7FLk9g)#ay>u$BUM1{F-GUW%g*;GqjGF`Ah<^8e*4>j1iInE;{UZHm`yAefNXB-u<>O+nvI~ zrwHgDFC)U(P_1DY-=(83IWl-$%AL^I-e>Y8pTu{c&JA$+GR4x&r-vXLaO*oB0v!Q%d>yh_{l4!;Fp2Xymw$fmdhR@* z9@yN98rfQO)G$n8Y=}k;e1(@~SG+Byj|_X^(7@fItEpIgn30=aCjK)wP(YwkMwY(S zqqFJz;H<$}X_3%`d1)0B_0y!R-`~PBQ{Y;aK{ZtQr@$Q2;?&$)jtkLj&0-);f|3QP ztmG1r#O*UE(GI4=1?oQ?I9C2(_xV)>YQo-ay!kXk77=j7)tb?Ps_59V7p6Z4mtZHht!6&IJa*Lu3UMh- zyVEh`^*TK0cgr=3WS(!Gl`U+<2Q9S*8f}J7CgT7M!lVHxAlcue~06 zMBz2~eAd+jjgA!+h1X~{%J}R7N{pvupZ=tmk7T!|Y%jxZ%&52WUGP`G@8x58-RH#q zJ7^G?kA*NlKTj}Zx&jJsJSONgx#bu_(vt(37sBQa5KU`V`x;x!Zho1$lh|C+pH1_N zok$)iOkA!{Y;qiG<`j_R&Nfu!y7sgr*;28Lwdm7~fv!kt=}tIX41ioVlAGZImE%;{ z*;)W+5#JT<&SnkeG4{TKf^l9jKm!#|#V?JTMpz9B)pv z`eMpvjjv3IoGEyTrmeivFf?0~A2%pO6$VFAo`A#(W-c$wT8uNbXZ-FZG$~RCc;1g=6sUL(#|@LXd2Q{OBFQ66^{4Xx$=4N9}?QKoJE#@^bM3cns4=J4}6wIGy8g?o?!Jww`&B? zI_O#=V-;~gkHJ#!sY}D$(p*ajFE;$LX4ko~TS)$3+{JQ;U*4c>Gm}|bn5UD5G*7Pi zRl(DtJY%Bwqw+=DfXqSWX2q;%ltlpXn9j)HHRo%hdrI3!dV-(eW$~?-C!npD3ZlBy zkYT3oB>8|{lkD=Ji-*s}&0k_0tF%2mh?!8RXC@&&1UjUj;F2dptHgwJnSmO?ri@n* zt~STyl+BG%+8judATiH*Yb3%B)KvC4fH_8mi-U6|c|TWJ$vHLxSA-<@e$fnn3`1L_ zA=4|M-}?@|&>YF|TA7vnL=&6KDluH6QM9zFz5y72J$y!8CQAyQP*Aatc=_EQMV z0t(LJMqou9vcwyZczs>BOiZG^_bt$ba&VMot&!_iT284l(n*w}stM)bOAwoUnfISq zb+>hxTa2l{Sfi9H4r&sq>CNj1Dj|Q1RBLmBi|a)phsI=#Ifc`$-Xc{GV}3jCohS-p z&_&1wJ?|Kn#N5`UM^VH{BIv{K^Q10$aEm`VXBy5tWgsjgexQSP~ zIo#N1&?DbJZ4-TPD?w-G$=K;=m)PE4Jyojf0*VmAluWWwP^-k_@HSC187NV`VzBC` zBn_*Mx*V^_rC$nN^WRu0-$cQ@Ma{ur@vEeRgmD{k^OssFGbxlh&2tw6hK)_mmr$8O z?}128bAADlQ}ap+g}G-HH!Q{C$*OODq=su#2`D}e(++jC~$ImQV{8?vLJO31qrNbE>V^P&aZQ;R6$-WMKyPWvK~5m ziw@n*t{F=uNYs*VCZtfrCLAveqT|Dh zG65+GX3Zg^YVs<$?+9W#<6*+rR^-8jv+>iUdNUc*w*eCS1oFUc#6N1Z)9A8*6|o=D zoL083M2~`+3M67tR8D0+b9!ZWq_)=ab-SX+OOoV!EYc*n+4&yyXBSh>{ZeshX{wbu z9Veefw2E@Dc30F;IN@WmALnKnbPmnw6UAALUu~SOMqy0jAD+)~7pfDsTV3mqMFsDEjS#|OJ3;sj+R(8 zVB1$BzepsZiORSr4JIswA472z18)?PeMLfm){2{+a=~tjSZJ62bfV5p1)li^nMSn= zJP>lFZj?`HEZu@Sf#t7RWMyA+Q9dbxb0;j1W64-6sWeMc_VI;**&}rEt_|rfiW^m_ zA^Z;BDY{*^j88HUr2y?x3ks$!T`lEVjgJ68;aCPSiw8tA#VA;m8@K%tyT8W{>y=-< zUV2ja!3^_3b3w0S=db6gn%x7-RN*IaoI0!0{JTnw29S0*F8*#_*OAHwj}o}^j6`Y7 zs2iiWv3brJ$Vv>_znv!hYZFaI7Lh~yXQs?T;aksqhy z;2{wOR`43@-uc``Y?%x;6CsB@JK`wNWLxJ!2P z)A_HR_K~IqNVM4&GHP-k1is+YXiv(JNrCX4@};0j=QE^wG)7Ooj{+uzIb(#OWc>3q zvVQ{oqJv#a7xeD)^F#MMeykt4b;WNpb;{m9#aG+cs>3fDS}VnI+ff5bKG~Yp!5G}W zZkmwlgF^#X@o#K^B|q&(`XjqL_}*D#N`E~_aY;+NU1E}qd(L@8%ge^fJpBB1wul0e z%nRh~wNO?HMG0RtclA;b1%C+K&5!n~rBZhq8gLWPI$^K6CBYIb&L_nS91ExI-GtP=GiLW-~vhd zJK6yC8*RutapPD~R5k4+Wx^@bj0kFuI%I8&EuLoY#!Hv_8EoCk2V*=SNvtb-SGU#? zxTH+WnOx}YvrKOZt0#Yd#I>Y3?RjKRJ^GzNB|1f1o|kAp7gyUbbsg zlhdVK?>t8IQS?O+aSzYq>^0O(Ik zE`>*ir7BiBoC}xbt+2_XGkzE=!@ndCP zx$f)kx{7TA;XQ$}?m%LZ0Y59->t`gN^Wi4B=>2+mBnNUIEpVPK4JVc^C(_|al9%J+ zA(RVUZdl~ECSP9H+Jz3E+&;OPV@#@Ad&qnn)pEMEef&Q1&;@w{bL?ukFEs}$?Yaly z>5$j3O%8cY{Mw7&68+l5hWvvr^UKnjuG;{xDWz9f;tf}?@72Kl3M*56za93|F2#%L z?ED29)+4N??p9nfr^73pwA;;dePoK-F2m8>4RcG$D5Hgn)IEt^#jV-D0dGz}d0LQG zlezv965pW;6rbMMubqILO<$sy(eBo;4> zqOj&Q>hq`Ijon;eqc3$1TJvr_iD@5k)c*-S(pr!NoBxh&PPiMxIL>S4z`ZliBE6&% zDEB~4TwxO2eyWLhGU409XEz2uR!+HR=Mrgl_=p}fX4F|T4qw*XnErOCw5$9ko%PYn zx!y5=h*7{uwN!`u4V66zzh-i%UY}JVD}IM{N4J5&qsKy7iLm*jWyMbYn88VlJ44vC1zU z+b9qM+gzffAb=DM>Bqez&~I-is>Kh}66&2K4-VE;R8$^|fckzLev|U-phICFgYA)9 zCI|Du{qA{`|O5aYF{(3|q3JzgFux4Wp4`y*7Y z*pbl7igoa&Hg9WT_lSIs)?A(fn7;pa3w+DyKFRYI2;5+aKzlNjv+}_`be3HSH@onCO`+kX>kSnO{5jJC0}RYU0L zEh7UFhc^Km=kK}c(`I#LvPL-T=E;j>e@g5S zCG&3auI{UlQ(LQwX=DTe6{Yo%_BQP^w$J`GBY$fyrj`pKoQy#WAY0+<#M?z;Wyh4$ z0aO06Q06@c`-a?$RiSAuwx0LDjO~3}E~H)6V$Xn?rOSJH&@g;$4t@17M`1dltmEyu&2Y^$ z&|^w;ud{q)c-q_Mf3CUo{ZHuNL9qWD9o(@+(G$4@gL}|^O?pH^ssn>5nL^VcE>@Jn z**8>}x|lV^Kc@Y@^1f-GYN)~)jr4xNg!B6L9p-Ajik}IOYxL$aDzxzRQb--oP4UDEtG zml05|nNwcwG)~r-Ycdp6pRdEEYj{vR_w}sWG~K>W7J&U zWvaj{9|B907cKBP=IT1|t%T`;dxCPXxB?pY8)Ppx!_cL!sKwp>AJ|gSH7Bk3*;v#L zX8U5AmP!-B-H)>{8HjVg_jR8(rvtVo3qqq7Fjb8q`Fxlnz4-*}p@Rw?D_^ko-d@kdDeH7t@^jkJjFN5%a;aXKtf=$x;F8E z>>(q9C?KN_k1qVxnfbJcYc8uxBd4!sP;<>f=JOZaM=;wnOaTb#-+kvhqBbG12mC)4 zWGiXF*DA0Fj(WxD%zEXKXk$8!h-VwlL&-O?@x+#QJa;79Z<0r1=%JslbKRkp0oH!B znF-k$(DiBE;)s``rj4>cP34@kYJ5%o!%@mOq%Piwk=R>8kEH<^Q;(csaD&FyyG=@u zo2XmBjA~Fj!Ub9(MXg&<7Lj=~!#!ykU(Y{9R+nElN5;c5QKkcBs+YDUi_Bw81e)QC zLOExLgz|?$^~w8`G^r&j0u16pEhYXaYmlPZq1=&B4*d=E?zU9R;)xFK7o8ee%8aw4qM&+ z{>dukf@jNbSL?J7N4FfG7!QEOfzhZ9QRGC{h$W%ifRkl%R##Y-g;fyh@o_EO=Vx61nf~WEo5cK|Evay^ zSMmX}#7Eo0&-dxj(eIXRH{0LiP(md9<214a$MwEze5?3>a6&zs%W}OSZ%1&XoNw>e zObt(4@M7kP{Qh!4uVIdWEF#jzRwXqxjI^z~Ok;unavJ+T9W_>|m=;$3%zC#2-zOWu z8)6J3YsC32MO9EN_j?W@8#Yz(z!$y0`LeJ_W9*P{r#~jugUV(Tf9BDJC)=}N8W6UO zu^If$MQ!(Ki)q!1-^H6tGChM#8Tgr}Y&(X6|NW0M9b9tBv@%!q9Wx9mz5>$~RWcVhujJb9~$eE%;r{=T7_=)%)jiIqCl)-SzKo<=+ecje*o!1iE1nPw2@x*-11~y)fNE*jAIDMI(A^W?o+rQ-=?|Iq6q5XNae=+*Mu7tne z`CD8TT(Wtsaaid(a*E+#B>U+1AjNwBfM*i6->8gdSi0a&hcAu+{gm*nRvT)QteSuovO#jhq=;LiM{ zu~e+Flo_uqf7};?#;o9aUC^+~cR59+cu5Jn#0;1m%Q{+Y32armFabqR5V^R3Fb-d0 zeZG{kQTMBFtS{ZUOBl=Yy5An+nXkHD#l-EHjS~EI5k&iLDUe4c`PfH{SEUIL1y|X8 zar^`I4H%TU4w+(GG8cNdc=mw8f`Z(|`oQXE#YNLm7GuAq#>)(nZd<>*$_GT6L<702 zMNjp@b4>b#!h1OQ`PLX;iTQFKi&4dIm=fMn+=?IXBBlCkRz3A#3*>s-S`^IN3zG4F z0V5A$yf^<%`;}r@;(CVB!Hs~?=hG{uWM+92b@~OPIDz2-C!emKw2ZLWFU=vIN6@3y)TwEF?CR0WDT^1@sfZ!Y z8=l@A1q-0NhrMbS8Y$80i7W7CPg(D~g-=2Bi_(OOKv8zG%68}HE+6})pJ~j8n=BpHy)XPgGO1z?1)YDFZ?cutN1rF)kZUMO5xS>e%Ha582}j*0EBEM#NgsX z&SoyK-RWWxJ^bCeI(T@*zyREGongvLyH89M<(O4Bp(*lrs1qVGa_sn}(C4$=xQ_UU zHoKn|0W(Uy2yxl{4;9Y7)0jm(h6B+HP2f!b$`>z9)kQR>hNy7*WwCxaxj;&iGNI-! za%IqLldhE#n>FW{CIEFVyFi30eEI}=9+c01kdl63N%DJ;PQRd34f1~~E(2wSwu=@dlbN@J~j5mOB+}htV>f(U$QYU>2t00 z-K*-6VS*D>@(QOPHil0382za~;Rmts`oL@ugmspZB(l8O*Vy6wmU^ERNqDh)IiX;Y z@B9m5x#}%9f)O&R|AIS8$*MN4cu=l1ytxSGEjLwDdjd|m>LKXv6`=IAH>>W#g7mhJ z5LMpBkYwoiwbJb%PdVeTZ>4hweXb_ITh};92O=@O%{b`6JSbeb53-DsK(`}dSTDB+ z;cSpugZv<{er(b$8z&ZqQkhbCLI-*f)F2tra={&QbR-l8@6U?>0E2l3h!kMVLUr zc4M)2v>WJFG9~>VnZcSPImz?^p9d@<=Wsh$Uq~UuPk+E)gjMZ5*^c9d4Rrw+$8jZQ zEH+qQ>tG7T_ac>M_ADj%JzSx{)F2lh>&U}W!b#tV$>5?&pqPFHWYw>uRy8IRphMhS zVF(z|qB*C4Su9Hw1sIF)Fl%5_mxi~5pLgrRt@RS=s)^mT-nl-7X!>ahKqqncKcFz5 zavhOEr?DpU^1~O8A=sYuOd}bCQ8>yPs7j9Tdl3~fX7&%cn@XAIHWjJu@puOBVMx&t zP$fQu5|j#ZR3XPtR}ep22FxiM+kr@uTJWZBeuzLjzN}(@+SNy7V?(g0M2#AQtK2C% z|FEosaA#b~7;leK)j0f4JbrLgU~Qi?Z55&-v6uo|V&0c2*`rW7HwWc3Zc_i)GG94R zfIxSuxw(@>zMyQg?FbV2{AiLvABJDiH*H`1!R;$969<$v`El4oZy*2xWnkhqUz1ko zhqJ>gr~M_wLD&f~cWzoWkIK4xhrMxkt90m43t!zoctUUBu0m`>b1i%7ENu>>{4$2h zTZ2~DK0j1a=aMcg>h?p)4Oi5aHqF((cP9|y$Rpcmq0(Aalsi}aJ}~mznL483n#kb^ zN*b$kFe)kS5xLOXv;~F|^|n`vn8dQPz0E$l5Vz>es2-VeP1<54yVG{BZDc%2HeQTm zXV!V|%h^YPqX&%FRk^3@+w5ElL5C&IO{0TC4?U*7pwUK@GmkwCL~vi>3Z;DQr3r-; zTNOnq)n)4LCm%77$Qof7H!y>TY@#>8S2$+v%!M$=1Vg#2I|z4S;#@J&uRKnO*?QHi zHSTcf^M)3r%+|X1J~zq7!?=5pb8yVkHl;q`P=)OW$_<*^&eyiv>^y~*XHSyL1ivvj zEzIKw5oN?4UvuR2;;n~e_C=AJB5Z=GNt5!*La4JTbxt6J!MkQyS(hxrQqWa=ghFcd z$~uh4UlvJD?E){EFTt~<=~+KBuq^5_a&Goo(w43m#<0r;Q(3`J%~&xPdyP4v9QB4w z;JUJUjJ(S!KPbI(gU)a>>8}_H=B%sf9uBEh3f@k#-6(z*Zx9UuvaYTxhTzJ2_H539 z1P2Gx|77>-I=09d_>ZJP+{;^!>!;LBtHo$oh00h<)C+Ux8L zPY!oq{QJQG<|pr^g|;*$drrQX5+3`5WwL`LFd#zsVL1`GZp3t!u>`w(lKFJ_`_BNv--&({I!2-;;D6-{pedQck*Q8LGIVg;&Jy zywJ-{TbBiiYd;WaCm}~9ehnHrMReh63&0;$b<{i|MECRT46Qq@boGpBjeXBGUDJJ5 zLIlL}ing-s_yx>pjpH&I$hE@i=8x%}`CTqq9V%BPUid;KFj!?d&%-00Jb>mhW?{b& z3v&;HU4n-?3eg(hxC%8eZ<=!k?El0EvD(i#PIHFI=$WXB%9-<)bqY;^Q#unoz8?lx z<g||#%a%2yGTaMq_pphvJ6t2fW6exbpg{ms zW+UTu#^~YGmr~|2m$^X!2zdxD_Kkw85@c%tpCW%v?#@p-5`^U>TJ-9V>HcJV`(TUm z%XYwwm#o`lcCAed+@;YXMw8~~B-Cp!B1Z^*hXu`%WsPcO=3QL3gWIB*e))o=ah=-+ z4@2z4J-GaW4eGA!%SA#YToTB2Q{0y|-mR!pqMKj)&P7M89b^S2^N!0WtMNc}IAb~b zE1bH9)I|FOnzeHY(hZI<@h&)M_@d-Hvns~8F5X)WT^d?ndqP6XF>l(#mHvtU>Z}7e zNR}UaM%U9HyTM}K1V&pVvQWH@#b(RMd+Z_+_%)5i9k-}sLPxzduz833r8GYv-puU$ zUhhNH>1}k?6NN73y}1HZYNG#{a1C_O+Xi~BL9*uZqJfqu^z)9D(Ul1|kd@CUf5YYi zer~5kIdM95tsR>;dCoz??7Ab~g=@wy-ReMv<~LP!Hx`R=bK2}*1np`M;;GYoWA%}% zD(IqasZzzj_BxsukG$v-u!tvrnyoE@%8WttuEZVcY6;q{GplOZW6h8ADprv5 zYMt{WIf*Y=75vVW$s%RcE*7ACzc_hg1^UdsM@qZZrqH{#XdzsL7@~Pe(Q^`Ya-+_Q zP@+g@AGvXHh}jWc%QG(Qgz~8F_8Oa4G1#j#d!6={y8F$`4fmx@J=1L1G}4HBtm9SQ zd->+udt|>x^32eK%NfH#Qn1e5lrBMPW_=h)>pA3{UpHH&<3vn9`TnufJHG~fRJ?BO z%Q_aLvIJDZ7K84 z^1TUImI(^s?|-J>+d6`%x4H#HlHZKYY>4PI~?e}9& zj%l$Tzb6{vg4g$ajFlV*Yh8vCDO7Dch-^E18r{(!rK@V6Jr=BbZ9_-&FDq1lc-q<1 z@VxpEhc?k->>79G6a^XF^Lcz9P|+^=z5@^cNVpZH3Pe0wblu1@UblrVN)pv?c+aTn zeFh|iBLYxR17Nv05U;l|!^nQJc1Gp~IM-POb!>8%{c_d%kyN!hOPL~S?!uNNX)ymZ z+~>$KC!Ae;*{t}f!REOANP+3KTv?;U{w-hW_fZ`v%T`=2sg4E|05a==F*mwErG2_* zy)T7nm6`g;mRk%WAIaigG1P;$MuOYWP+kHQ@Ek!SjeL`6$z4|Ry?`ci3{9&k=f>#= zMFmg|OerymG`o(LnU(og;ZC=UT#r|J5lEb<3qjJKF`rkA_6W3{mu_}24@^vjIsrzo zH#-d57AG+}8F-tbzlutju zCRCaaii0~ZmtVwbQ@;^F$1*LHCV8#>>w7NXBSS#T&CZHa6&zvJVC_M1?H~IICeB#|mVnKallLHXk$P$U10Bm@;$4R&%x~<(w_IKZI60 z#x$Do%=xfX6(ZqPISOKJW~lYON(5CqNL8O5mpL_Zl7uRj_g^;!8Q-6FF%~nG0*DJ5 z>y{ zPvt0io{mUxU)kFNMyyg1o_fU>B^N&-sr)S$;KO15Eo<{up8NDW$#9-JOGZYv=X9z4 zGddbxR!+{KWK~a|&~U0*jh@sL%=!10FT*o6tMtBW{?j)qsrVXyOKAuafogdl$oDT8 ze-jt~DEuqU-pC}y4hE)a;f8>N;9pS#Ief29A9b`okPG(H&h`XpQfm4HgVMz7DLh8B z2==|nV72Xp+Dgh4A*7`;h;89^(w7nx_l63f+d^emu#&vMKP}#&SiZf5l{UO&z#tJW z7e4~;KK0E*gEp`7r{XJQs#~?PVsLsQPXt`7)!fSGZ>k^fy>%#go;)Z%N~M7H1TJH6IU zbQ6`!`Z8rp0krJSi#Ps2b0eqy;kJ+*I{gKI?#R=eQ}fv~!h~|z=-6l?RW6vm_2)&R zeQz6Gr1Yz^<1Xtu(~X=EkNimaZ6=Y3R=8Wk+k^M`Bt6>onY3D(@zFeI{oTToPiORc zt6a;Kx*x9b_d;kXcwW7)dSxdba!d-^uck)=B=BsVk**IB_2v;fHb`t&Go@T5iD50& zbV*l?ejl)wdkOX-0;k>P+u9%U@%qYGZ z<~wpz5|S^5&r{obu`%RBA|xKi!bID5@bDPQ41USJglcryOM;H=$-ev$$kcZZG_~KzKlQZ);lvg(iNQM^ z-}hkFp)?=cK7SHgH4Mkv)S4XzU9zJRA!0@QJnd&vBTL28)~A561Ru`2^bq01HEkx@ zlf2JXpJY~(1GOA+O&-wDUu%h`8q?HOP1twkB;)?FVtWXXj^rg5BVS|dr2^w{hfOfG zxubFdihUi6!B+Mnx68!PwTpv`Nd>Wv#BilK2uws3#Q4Dv41I~cCl=51$;NG7rJ6C3 z8~F?9BHyzumOkCSE;Ho9s_#}<01-A*}`HYKY z{7{0nFC#)vL-ig%x%nBU}qH2=ejm< zck*u`wfr>3fdiSZoVnOcrTHr8IDES4S)Ia?X$Nq|hEWxcdj7{nOo|tO$hS8A$MST( zB+?D!LS-z8Z5W&7UTKqu95y)hP-1x6+~a%sAPTaWu^4QlmzlU>1IjkWEeJZVb%Sua ztIugU#*8|WMWlh97@;+c>GP6?qjX2aPOG6gHhMyaM4hWBWkIZ;)?UM(n*5%x0HfB{ zA{{K1%Q{7)Hi1s&AW$^B{pavJuH6BXb-AM(lsm%OO0HVzK&^ zrq+A8lC9|3+&f95PR90cWzPobC{Y^msWuF9&;nhvB4!S95%oY*;35*z7&mM{<|PJ_ z3y~ELPLTNDH)!CgdWFCuVo=_0#Fk_r^Mnr)LeFdiN-((n`7j^9oY?BSDwcK_7A$kc zzc&II19@C&P2o5>*Qdp){{_0GnfUxpbnb*^XW8DBs!FlRiXQrB2sbl79&MAqUA&>} z;7d?C`Of|{3&II@`vU)uTE*L++b+`WqbjAU`SuQC@h64(C~WNR`Wkc ztWDuUK|wt`7GgA$U*WTSmoMb@;jal8YnLj(m;V)vx>5s4=c%2Q<69eWu}=E$yGsA( zLoZ`6Oa5K#|J%X-*X90CPy63r{s*AV+wSO)Eon08#~xzs*>!ifOyIFG#P533*;GLh z`C#nDz`M=u4gZp>kEQLaBDM+2RsVSRcF||ec|0zCI~rm-su-m{t6lHF))apwn0b&c zb=|+yjZU#06Cgzn<302t{l~b7o>7qFB&usPG*F}tQm$D2-w}q|@BUW~=znzXzdO+X zHV(KX;XkF<5^_?d+pGF_brR^EI$9^9ehQ^~SESuy@AAR54gy^k2y{0nWma;mKo6U) z`KQAi`3my#0j#BkYOiTn6%Q(5O6;edSW52WGi`o$SCQ+j{4-_!AVasFXZqQYp{|yEGq;9j zUgkdw`dMOQXXj>4kMHmib>i}UPIKRQt{B#0zjPbt*LY5zKC>`t@Ghz2!QU{ zp;@1lr#+p=C$z4gp$Uma*E8N?3~47sEO&1)FFf}V0e!7dPCFv~XY@S(Jm zp3IIt_R?8x{r#iPX|r@C!h8EV7OR^F7~{UqDKX1ERR-mG`TU+8<5`yaSk$CdZ40#1 z8d1op;DS^ZR!`O)Kr>&<5q62-X*G*!25?VgYOBd}d7J*XpoeF9+rh04xfEYCl%~B> z3efWKL0sL7K4m|NJ^FF#Lk?$3AA!~U&Ee=YlcnmI`moO=Jv8Q5(9@+^6aA6U7L5DN zxS#Bl8QP3)aPuri=yl%f8KzZ|ZPqY!Q4mUlc}cE28D6_SGkH~( zr~)rJQ{J^O`c8WJ^!`o+D>o;NPkmt+CF7H>7vh;G7~vr3p$jJo-Agux{@r)TELMb- zH!5?(ys>p!q7eGpw_iwBXXiB2s11#z?R&y967?Ejm$mA5-kY$8#SK{=o5-ZF~J^C&Iofb)wQI6di8 z2!V<0i10P-cfQpYSTA35xK7?B!mr+~n*rt)xgeW*E@ahV)8I#)%@0C@E=iA9MmC=V z5k5_|jl6A%b4j|UP^1I#xtx7_o1GdTQl$m^W$DgGxQ4BQ(&m4T@>FjFF=~hy--0ld z8vN$B>HbzEPdLJ_QWJ2~;Bu|Tl9ac`NbMdKrzIGsprH>^hwSjSKWe{1l%O`jEsVF2kn&Pl|FmC zu70p~i@haUg)KK@Iw=?F*}2+oCLp`k)l2ZP(zMnX{vPafsi!yaAWf6{nE;8ktwo~Yjjs;6 zpV2YYy_M1L8U8j@(MXKRy-%O@s_1h3S=oU2wgrlXJv@K+yh_)uw2Aqb656LY_UdN9 zS%WF#X-4<~-_cloW8Wh>P`xJk(&jyym?&crkcXk-N`LW(D(`w~CkI)ULp8uGT5hQxjX1Z1 z+I6O?3MiLpryfqq;Frr@fL6i$BsE0Yyi@r;f-|+G=S!auULXmKwd2{FmveaiMaPlR zRC^#$^Z*|mwY@sgRcn#IJ^ke?W*~o5JE~Y(?FU`=eYjb0l&lh(u?*h)%gqwL%(8@F zWTwB)=}#v$SZ|b-%3tnGPgTk20XWv~k=}KwIi^3q!_3LzXf52UxP&!b-x;DJHKOu; zt~XEo`yqtF|{X!p*Q-V5M_CN#|rN=|Z z#bGDoGpDUeL~XtPX?|dI=nET1@H8{tf`-`uUz$|?0*YS40atY#V%5<&PVB|+0Xk~^ zsWA$1mosu9t*>7{*W#2@GppB=giYt5-cS(gYaJV#zcE~6D)Nrz2eBT6s-+~wxqpGK z8!McxwiT4#v1v9l%NAlr>u3trZ@|NPRIW66KUZf`kmdSLUwJx~N{UO+ZG1E33zQwb zTeWHcrqyV;W;KaCw`_2hvK;SW&VDd?rsvpS;QBBU(%RDc3STT@l2<@rqM-jf5iN8Np#S$0 z#$y=8t1u#`kPKXHO3sm{jwo{tB{6c;I~Y!#6=)kaQw8T@lNo72S;BA7>lN#YG*1ja zv7H8g)xy)5IZ1w=MB|4thp3HC8z|N+Zz!CMVC+aL_%yyG(C&gX7!X`_cBzj@p6_%p z?=VZT$E0p+%fR?r;ysG{;DXraY0a`U%JH;osJ_=&cm}?Plyii+$UTI! zB9YhbP>5W53&=>TUPG%^^H_u**mJLTPv;YLy_3RJB+6+O3DVz81C#yDsfH2Rv{dBA(MUAT^s73Y#GyTQ+=LbH_&MQZ#<&_6HN&kc0; zRqcHn_+`k7r=bsahSSC?41O1v?DPBFa8H#((LOrT@qb`1Fv=pzAZ}tVGkOQd|Cj=j z=1`lZsmM6#6jV+C2+V9>E3un5&x=1>5KP@9uGrW6{$S)zy&9fc|W&HR)7 z`|D~l!Lu_O<8{t~FzZk~!}RI4b{*^An7=q&cipml zZXQ%rq87M>%U%@%h(cQdjtoXaAxXJd z3*y%3XiLjK!F^)ANlMz?$ZIi`uc-AKdV$uPfK#n%uu>nWAed#-gdm`=6#J2sI<#q6 zu{WS<((4bQvVv4hz2VGv_u#SV4K4+W);p1#tPSdYRg_sWO^D7VT_A?BeG3`igy97J z;%4C(>=@D$vh3~q=a%3Y8V)`dot<=K%>yW9PdDxTAaz$~E_Ktr3-NiA#lnj0S?l5X zGLr-}+RfBa_~TM+q|=!-f9e-dvcRPRDCU>m+jq3SS{oAMS7;`Byz)=+G$EXfKu5 z)n__`?jUCBuAZ9+D)o2ZNJ#uVHY2^F%!)&uo29JPM| zSgSk1YM8Q>r@AW#E5R`IU43lKkpluGaVhYHfh`_r5ZbKYU2VnW<`%K&%+$S#zIV_w zN!uQZ_?8AmcL)SshinX*vR$&;cJ@@rz}`CctY`@L*S~z17gF7zqqPc&v96&Z&{9q6 zZFHavsFEx~a1<~@fSD=zztESwL$nm|EA?nIfmc|vK zyo-lrxjj}#%&GEeCaWx3xrSw>D-C&l^GEZ;W|QW8J%2)VL53R_ceLsWF2s|kTb7eq zfy>RWE5KUStaEd8=Ul(f_UDsON%z_cq4u>HS}xnSjKQz5=}N5N42BFCq%T*SRR@_X z*sJKAfAa;RDC6*Y2@s1{CctAs0n385;!&m`1Rl;iaoV_?IG~dl@g+#E#l668HyXLx zSCHt`B)T}c8m&}fIZ*^eqp2{m=W~a18lrcR4uUl4SFJg)JJp%sSV^t-%L`Qqf7)Zi zmvO)PU0Cfc)}5+NX8|*>JP|m@ha1ut-=Db+sx}vsSsax!e$iGlxE&mV;GB=Nm~5#Q?~wrZugnd4H^#EkHC zHq7;*v_n~RcEMUz4}L2_g%c*2rBz97Il;b-G6{qVsBS8HF?rsuPTvTl+i#gSdq=aF zHZUY%;^Pjbh9qjVQE20_&st031hNgQrcNRwvLVl&RS`OwfGo3JOz7{A)X(ucHXvZ* zWj3WWvOJz*kg?I!f#H9RvS=>7osu--=GREQyqKrwT#}q`zobY^uh-VO24KI~S$2w*1Y` zPOR;rQ#W$)%>$kAMELvrd#lM2PXNM*p1 zKIqxC-I$M^7|oq)S7vy!8hE$bF_zQ(*#H*JIgrcE+ZXpfos<~POF^5WyHB`=l)Qko zo9ow!Nmv}y)C>dO$Y#>o<0g=&C5$vxK)N6U@w zip(&i5}$|V+AY_w;Na6O^Z|{DZKqrV*nc$6PI%gzcc{S?Z!QgG5Da!_dJKrUvxrxR z4{70Y!&v%l9H0jxu;QCVot_ibAE9Ku{$w($g1^uh<>LCagBx{qmMGy%aC{CmuTa`^;jVr_uu#epDS%<&TA zeI)HmiGdxL&kd_ydMk(OTCRjtAMZG<9t@|RVn@XY{{>NZxzOF0f}hKAWFqeo{OHPI$Co@_xtjmX zaXR@@ngV=W(|^+n{`mT2v1|)|Pf^mHWF5NHQShtoX-4lFuUr|!i@UO%s^8~6?38UN zyPDB%Ut{%{9{lYst|SkCkbgi$S@FYc^9KGZuF8KJ+&gdk24kdnE@;PsME2{ zcX&(3nm;{EDY) zt|80KmDjPIbZcjN%#_}S%i0IgVd<6=$X42W3+q>uQ8s6zg{u~>&9Ro^aVDc)mb;Y` zL#=T9<-{&7@acLps^U<1g(P1ZFe5lvqgs5WK9Cvg#Y_CO?~=#cgy;`Fbr8YMk$J04 z9oXEV=n@CoCJZ=v=1bP~NJx*zJMuSMHMl!Dt>j&!^gq|*MX)>NW+|*B+0H*L{#A(R zk6C|2Fq8<{djBXKSIH6<8Z}F)!CxPb=%LN^IV#`}EM5io-%Mznf0en=fowyKVy08P zPVgrxwtzSvttJtKoJz9H@8E64->zwWNC_D+T~|}es^TtBrs?y8X?8Ervr{>{{FR43 zFc{u`e%-&%xQ;pxo(>aSXqxrbs2@#RyPpBoYwc1Xo8MntJ0Zd))t1S5!%pvA(jSOZ z;C5m?Xv^mG{^XV->5M(iun>=INgtEmVui!ZJZ7#lCGz!e-{~I?_C>#XST$5^Cv2kf zrbc?}+VfsUVu~+ZM6rhL`-L@N=IfB{u<#7X-u-x5zD(Lt`0!P9z&9Is=jNM_Tw?%( zQ~DyJfI~^VGhyKShQ1i>2L5d9t00h}80$7!`w)4;nsxMm7?S~SOfa=M)y9Tcav6WD zH4q}>QEA?&TJPy^iUi*?(jOp-328#nPHJ;}n|z>^ShZ_0QHg|$kbF(UvO+FNXB>8m zkGV}S;KGWYQ&5G<*j?QHOkv129)lRtIU zVRP6THux}ziV9p*BPA1pU`pgod!xiIC#-d4t5n;|Us=k$MthzV^r~73`6+sbQ~OK3 z7yt@5gNt+|rR_q8e8xRXGcNg|xPze_IpYw?vB2$(u?lSf5T9n%TJl1ZgwFk7yrdi( zKvuPW{OtAU;vLKBm-!aHmYmg7@eZfA!axTq&9%zzR1@%{0H%y5@- zEsXzQ0SFG{7Ak-Rt?tN>SrLQ-;Y`-N3zZ0<)I zXQ+O8ihqxflQvt*Xh90CrwhUi+onv%o*O*wEFJ@$I>IAYtusAdgHDUSW3SyjFLcB~ z1gHTre%nC&iK7&gws0>rx}2)r%^HB1uX~eHGvYL96TTP{R!0~7#X6^RFk&b5 zMrif500wd!@hUoXz#Rn4?z5Uj>UvujWO$$xCNALX0P%$~3y*Wh(Cn>wam*|Wf}cX_ zNphG@y`zjuBaKwp`&(-e^9hmHGbt#r2A(;BUvKQj`9$w(ycp^4Nw{`#HFGry-HtUfZ)7*X zP+<$18WP|ih`i(TP!+$fs`@K^d6D@MD<1L={b4oKSEQ$K@7=mMe@@5Y5TzoEq zj4R;pEX#3Cekn&mrw3|Y^|WUQILcC$WFbnY@?|dM!zH(LedJ0@9`~7wXzuwH$O0bW zOg(vwR3qQ#+T9ylA0%*W#EQGGR%5^AY)62Q-Lr2i=_%z|l;Po?Xp5gK z>s&du@t&tmc4(t)FmOO2H<_Csv3tI9!3e_No!P?_y~IV2(Ljbi6LK?|X^{}1{er$S zZ{~KLt*F}m`o(8TZF7Mx5r+lTVGRtHlYKYh&g7(MHA=5BlzAbEASo(O)^FeEG zz0A0~*lKyvD8x+U_3kbGN>ix)IG;PZ+mW7v{~v7 zDLmy%D3wy8(}QXQCy{pNgqW)GtpUg}!b=?`eC-k`o3G73&JL8LnBUvzRrA|b1*dIy zD|c$EU#gU84Vz-J5I?KzQ zb%X-L>4>QLXZE+t>6*L4$$^yicvLBtr%ay@bvm}?QRZUn=`lr7o>B)=g;m@ivb-GM zZo%bhJF|yureNPRFF_5)hO=*0O4o`{)U){xLi_O+)^?Nub! zfb+VZ@r=9INk77!D12uxTLNf&dX2M?=JZRxa#*bBnU|#1A)GeX2t@2|Rui0x-};6Kw49(0e~M2QH06u7BfY$1Q=MB2jS>}`0DL>RQ3TXCm3_)72}1c&=|0N$0QAnCNJb*`k$4Ct)Eu2E=hlr77I5W|mAvgMzz$wzBLY{k|Td?iHFVbH_BJq{D=l}p#I#)~U= z#|f%jTxZM0s~8QoFc${?o1qrx2fQUo*TRV-Z6hg^w!cdWXyq*SkJFuM)tf9YEXf{w z66WpuqL@QMDCjm#v>{LRzBZ7@y7q|w4o*ZRbO^6z>8F%k^*vWi!hs_T2FP=9<1);h z4wUbO+eu;c;sLZ5P#ssrO=j}1WD_usl-Wqc=Ap9BA*R~8IozBIKfxgBF`DYyMpSak zX!vbA>buTl0~|$Jp4y!WbSZvgSomq7&DU`g)fT`&GaEfM>^Q3XcHqs}l&WS}L>g2RIE7B21TtiH4c-75S%LOdz>vy4&CYn*_h6 z%`>UJOO&KlHe`QaA}LQ zYX}(zRi*OUUSc|pta3?7{&g)ZS(VS6fz3TBc0=0>XoU@5q&6)QUg< z3}JpyAj)AxsAZ~szhDB5rR+=QhLko%aXt;hvhPlru@$dm{kZYD|KLWcq4^zamuDP@ zxF#J2+bf$ z2tJQG{L#0D(c3#=ON})3v7;YJOa<1&B1y~1I;AnWlpY4q|5*?B9%kyG6z0%6!1+kW z7aAH+Q-?xHzYZJ$cj>HF2>nRKjGLcU+7%BsDY?1BcTUs{Q z8%cr*M3gdLtnisEtWsW`iD3{_?GHzn&Y$r-&#O%r5kwK0P0l)NDyu7uD0PUn#;>y# zcu}$Xo?!K=8Ug20M~q8lZ^eAA3_OgL{mVIxy~)+h!$R;Nd%W)w5e^oAwx7v};cczA zwRF=cC0jv;wHJG8UZmH!2%vCVxN?H6fBP2iB5z@CZ$W}ri4w8Qf_~|oV4DF zB!70>9_N&IfmqR>0CJhBOMMOaAh$0$lN!Z!J{PC{CL*0l?kU;Lx7`(kfuGWlrp5F* z_f777bV(^3dDGj`qu)S{+WuD@Nh?p_#*t;u-K9@yH@C0aINNNekjcqd`qI6ftQT)w zx+mR9(@tIFVj&f0Y@pH-|2ozL;o%@%JnL4le~I+aCjo-#3Im*y*@u)%r_PzmS@rR@ zqOX<_BU(9yEka>ZQ%gMNAO%pc!m-@a4oBlVEkX*GP6i=0FSKp8+K-oF2~R9UcBP1i z>q61(hciaWOYh=~Dwsap6xZ^8v=H1n#&=vc%^8NE?*APiY1KM2hi$bI+N&KR=@M{g zU_~~+wD!b#{D~;_fSzHkG6gBskR-)KEeItH0YCl*VU^tV`z(lkmCX9p)aw|G7p%`udeT0YM&kb55!VWT~Lb; zD&+h~mpNfOZjD%HDx<2ZNe>rew5{#Vo$EF9G#~+vQh{^ziMXsVO5yIf!FX6h+BTAg zKE?&wrLyE@l%q+jyOaY?z=lh7wIsC)vB;m7foSd$URhn+!Q8!3Lp9{yNjLvz?K$eJt>;~L{a%7IBcsG$KEJ-{`d$7&d4Mqymq{RG zfw>n}DTn49}Imc5Z%%CR<-O4n)ys2$EYShzUSh`$|;lf zp$52Mi!Q$Twm_mt?7B{F&)m~8io$y3cS@@Ur^r~g#v`C;1yTX#w$F7PAHt>K>?rYy zWR1L$@u-)H7j-)T1WK&Rd7MTN9*cjwve5!bY9& zylpFRjd)~fn29a9rmE@BeQi9+=mWoW6K&n>=oM9<*~$j%NVzEjxNzL^m0#S|(RcVb&zr2-vQPvr>N-ULN5le$=R zJEl&dJz>hjhq$Jh;i)zXB~UnVbt7hZ1CkE3*tkD0^8uoM!s)=+zKXN8E1o7WtcH^I z@=KOd+QAyuaueF6v2}R|B2?O3^fBgdUo+^Hg7l-Z( z_Y*fl?$or&)rl(Fz>=K7cpUhnZG|v+C20K(yh|L$lH#Jdg>ifb?lPhEI7VV^UpN)h z#oXSl`*mv@oZCQiQ-J{Fj&;Ib9pn9>g{OD)Rmb6IoUT-AGj#7G{Ef~|vE&caox+_$ z$hCvM`m;}?J?;=#JjsXAr0Lb$7X0`KQSkMLm6M#ZV5j*50{LEJa@yUh+GMT^#=~=@ z+H$FjR6{B9W~OpGJrkhKnUMDl*_k@`f0S$bv`ssUydcsBChNx6OD5@WBn(mTnZ zi*RAsFMX8?6NKBFU+|x?&N3f^mV|hiw*2|i*NW9IS9E=S3w~Pz{n#s@R@gbzyLqLu+ zoNnEi$_*tlXAIJc>I-~6?3LDSyvo@IIuLqdedkv&m&qk1 zU(0e6`}yzS9< zoHNk+4?#D=Dy41S7HQLB^YL#HSa*_EJqgw?Q zSU2L3yD*(zNt%h;)84XR@OVi!Ek(wNop|&UWWJD zzC7_bkYewHy*VFT0bQk-2FF>q|8|eeeY}P6h%&lawjP?Cd#NTzmNC8Q41`?}U&D`G z!naPGuV+U(*DJE*<^Df$=bOE4C;1qh^+aOJ-8JJy*~Di2!K>**CreCCw%bhbud9M* zO5l%P^05E%PuS&J)__p2n(aeuTIaUcgpH1T6q`<+s)(63=1)RI_}bI*sZxV|V*`uI zj@M>o^KxfJA+-@I?AGdHf&6VOR{We6jC8MjcNYP12TFZYcmsEmQseRMsIpuM_xtG9 z+~KD4`51XeHThe-96{txdS9ykq_ZB2f0SYzguQJF?Vw}`iNweCV2mmm4Y<-o7V0DB zaow#gZF3qLNc5idqmVaWCf^84;+amK$0Q^#V{HL9Js|N#cg+&vWu7ju`gsA;c`ieg zpwFxQMvO=e@UF*DwA}~Kc2zz_qpIfzxc&LAJ;U{}lhw~zvo@p%E$aN`5yrT^J+cT< z??P>+P>p~8$~FXBW(lWai}%qWK+IQA;W=-rdL`=ocDX6Pv7;je+BC^(|1lHNbm2;9 zS?wtAQw6t?(e75T(=_mDSuW01{;lNX%91697?~sGgvDyfCg^2^Q^r#5b!gKxwYb@l z_Uima$)?(f(m=`wxPyR}@4%OVYO zu^AmOPb`ZDsGh>K}u@O z|2##yT5`?Ri0`SCAA-i(^TK>fehk2#xI(Z3RNc?$j(Oi;-)bK$OHb8=fjiLJoP5$3f+J75oCU2@M5+ik2f5Z7jvDWmed?PVWTUKyJ?lsPTR{;J72P#gfZNuH5D739Tq!=UW_Ar{*DDQpctM*{-uMHt&OSYG0 z>h;x+*X7l(e;7xb9O(0ODfo9(X!gWHSY9g&%S+ceHuv7%wATI6?6(f(i*-g9;Hmu$ z5_b#7zO?rwW@DqK{mKlcs3sl1|H>x84$$32LqW3zV0Hm z|NgBvYH%*`zkreI#BkbLVx|bI`B)fqa}6z)v)6<@NCMy2qu- z)f}Jl&XBkiz=g_H0b}<1f(3O=k{A?;5!75Fsd z@Gw;l=LGK4s7hlGU%aBD&9--AsQKR71)vFULQ}A>Oz8V4r^*Xb`g`Y37axNa3`%>6YQ%AQC zl7#}C@PG*lkJ@-HR$8d0AUafeeo%4tF~IqqIBM)0jDPeOS;kXE;~8?W;6LfbGoB=s z|H4dmtmV>oKa87*|5a3W9|!SRZ}e8=b#2uvSj3?m3IDaLOYxg}e1W)2Yu1lYD5>dr z5?nUR9MN0}#>AeApS_MwGQ%p*aPdqJEx6qeh%&9@zQ^bE^kA!`%M5@vZ1UmL;`k7UP9$-#5qJbITOfy%9mx*Ul@AiEgi%gJFLh=3;}=T6>JuPQQ8Q(jj9=O2k5^2zp;rF3*g zkLS2qXUdu9p{){x+G$ax%g?+US!gBg?avNDB(v^DC63z~{$qkOMMR_c;Gk~W2;|qe zhcE|cX$BLy-&DLSD6$&q7Q)+7Wb{fGi+-uIw=kw9=Y8*QpnlN4xb|g7s&(6fyw~jL zsr?nyiZHU~0b*~{Eh-ywmyuv&cvyNnQD`b%92G3pw-tkqA=c(PxS_~uM^SKhFT0lDrKtE=nO94R32`PD7(*|F=7 z^vRe$eJFF%sm z_kHN<0uQJGCv5jsTil}QkuJqG7vi=LiC&E=-_8L7pDK!+Pxd<)J7NJco7EWDsJ_u3 zb#1QkC{}9VE$d>7wyVL|yPL|@6OBbH{Q-*r`;-N_b2pwM5v=ExZy5G+pdE8z7j9_! zQAr0d$g~G>xXV=P!U%IdbYM2%?wH%=FRLEDASo3&C~CzvnZfRMgF^{Zl}mosF-Y+_ zfx!c8PC1E2gUD#s=@~;6AFfeId;Cij(sIbz$Er(ys7*qlIvo{(kFS!j1XDIT(>3{% z-c(;V^~(q>*MeLV6g8KO^pv?9vlWqs*#VN0HyO zgKBQcT1-#?f9~2k``D~)c_`50)`6B0HCRw@BG*jJ8h?h9^;Gy0wse2KiSxW+PqrCW z>CAdFFt8kry&Ohy3{$aEbUCGB%Jhj@l_Bo0-usV2jqTJP?8T`ZGX`F%CaSW9R5fki z@BA9KOHlh5J70|Z%eQKTPuJIsdEpkZ3#cmn4`nRa9UnT)mQ#&pUr3*KA0gb|b z>H6$91Tyn_qn`sW*G4ai`9#=n8qmkWmK6G~*(UO>$2^(}ylA9e3~@Y6bn z(NrAp`oD970pPXU`qX2Q4OSS=ub?rC%JLrG5@KC9(sJ*xIya&Tn*p`(baU8!2hzY( zu(_uLju$j{v#fLK*Xp7SPj^x#KeUfeBqFl3e}V@b?YlDT@aAS71qFp_wO0f7 z(<9S7xp!-k8VLsD75~8kTx_wP#sL4GNl9fw`2{&jat81LA)ecBG(l`Y9O419Egj@AttF$s{1yrz867ElKu;mqDW>9 z`Kv5}ya{_V%of7L!SUKZm+f(T@&N|s_r&%0yRG)i_jmd`w6JdnzrI-`ZpDB3fjwwP zDV}?*JUm*nf&+Yi^)6ThE$2aSmWy6kqXP}Cr09R1g)EmcG*gx4KH>C@e{sg8d!iG6 zC0it1(=mS1)p7P{P%JE1QO;qB_2J`e1gM*cgLL4v#TixZgAsbdm+Ze}K_EFAK-j2c zf0GOM$!8vLQ)nV$@+p?9))2OHPLj_Ijls^}O(+k!(Gg;Ds^QNaJvFISW*}4WklZC2oGpIA*yTmd0NjoauSE`)t=XZn-1ih;SZ2LYsQAdxSK<;h%cGa z&w`a%lJ^PaafN6ph@41y{T|)&9z_Zo0;W%}UEZl8 zzaD-ooJA=k;Lfmm$T88V^#T#vwfiqFU`~>RJQ?vVshyJ4C@vWYb>Exq$8h*i(SGhjirh0CRJfJq!p%NoIl7|^Wkd^cb^HZWSyoey zYW|`!rcBnRuJc^MDt0ag_g$aE-MvNH+Yb7xMiQrqn2{kwYks+sV9M!y4)*&yH7r%8 zq{8VlNwj8TP;q25+t^k!U?yF!@JqI3O$V9wQ@|35M0k>030_-bCgXXZ-FN5F*uKPBu764M!adE8b9W8vMtjDbRVg5r)UBzKzx5_*3hx1^6&;CLO|~-c6jN+ zW=Tb`m5tLo{N^abXONRpVn}#<1tkGho^#`2 zRGgR2md1(NSLxhRvxNsr&5VuR#%!WE;@AdC@#Fu`t86FjzKKsHm77kaU7xDQ@Wv7o zGg+<&FV^qnWN*CVwI|1f6R9B*;ilr&@Q@zlATEg;K?_b9tw**qw>@zmgCpUIvU zlhz*tN|Bxfy-#n;>8oQcM%rHY*)d|W!4GIB(wHs>uf}oK(jO*}zusx9dZi0Sajcoy z>uH78Qkmz-+1n~<=W~eE*zkGad5NB~y)A5133YkoIZfAiuRrYiA7+_;H8oBfHPuWf zCnuz2WHA}fW4e@AhjUToS`B;+FbN|(%{cpL9Suf_XQVAWhrcUdU^;qW;8zOhoj zywGRDgp%Wrxa_xGU0tY3Q3lQj2j3?BK5vOM{ILqiQKRB-m)w7@wh>Je1n=o|qcVek zz-IRKjl}#tzgy^|#5|3utu6iG8OPB7YV0e6;%v5ckp!0nhu|6!+G=Vz0bY3>Yl3e{+X(tS}m))*Xq^sJnQT!WG<`hlYPVv zeE)jmO`7t5TYo`EB3xV=4>i@Hi3yAZ=>T6}-&dl+gZb6fZz9C~8yXs3i6T)jP<;IO z$T}+d&KbH&eN+_j?sHH1^xO8QqZvIN(cxh zj%fb<71riKi0Oi^cO2WtbkwfRwNw1_V^B*$1P$q5eY^HvzlBL6kOnuyq5 zUO~>|i;C}Ux)j1;&Q>T^L?ipGA=S0jd+U8wotuB#Q`GKpPWe?9v8w=WTx$&cWHt$_ zdCPuw&7%A4gz~8nN1@a+X34fwdgS-@w-SQ_V`iQ3YkJ~ko*)yABlbTL(BdBMypoyM zWR|$A{Jnu|8#R}Om9Z<|{d$W(5%4MMT|uurg|gcHR%53|e9cpT{FS9dY{mv1Tf#eUECEh%#6ku1i})xiB64j{@hh|8!-ST1U0e z!k%S}QW4xVXFd!WgHa8zmG5(`;DQN2Tc_c^D% zqYbljr$%PMHqc%~qV+Au`~29^QL67+`1{NpITOumXbxq?;WWC*-S;o=eplO3{m{O^ zE0YJAE{?+6Eq+X*4j?gI7A4kf{+WOK?Z>HT6TJcZrn-W9Mbs-MrKqP+QqqGZA!E20 zw{deGFFfwhmGwf4xuA7}v7Y@~IPT7Op#!t18#QF?uF^~!&ve<3koWJZZx0UJbx z48Jvrl~1$`?x%D}Zp!;S;(Xq=Y3=BY^ja1eA>bZ3%@{5otBh@TXGulVQH96*dXOBk zzW}9{ID#>jU4Ft(+HW*xwW8>47i2Kg2}hY8UgY!7A6>ezrv7VuP}GJ+i}v^T->YVF zHgrsEZCXD%v!Oto3nj{y-)G(+6`lMYfB9g?Z)W25?^$5k4gzRdm6`3CWhOEyXaxh3 zn_;}$^S2Bj`-|$=`~(DX&Uc9F5_HiO3pp)z>BjUXTwwMsSmM?KcrUnz%D&HXTsCU= zy!Ica1{I zm0g8*476jtuesNHxOF--@(JPX?T*p5H^Dfy0pk#Ij!O^^`)OmmwP|Cs`fu2Z@(nV} zGMrjg5?U$>)bNPCG|6B@B^NfCMk|w*#tN&I+MgOEG}OTQIn!Eg2D6PKTXJX2H?GeV zj((8W{Al7c$bFGao;+vM4ZSL|J|0Q=G*rWSRdt|Px3IeLnPg{Ltr(4>fWcTjSx#2D zM{q$YPOCAHzXJnDdaR5S!)^Cq-&b8m2>6AO9@0qunh*1%#|g~Tde`uKV7}Is;K%YS z74jM32CoT#146sQ{a=(Pbpt__J74(B8i_8DS1!bqiSjjYm1c?us#>rZ(T1u zx>lJP6Jvp@AwdP@m2;VHWZt1KISuW94h?%sFXX2p$hYTT{2H?vSknSrBXzYv&Cf@_ zP1t0FZ0}tY4Z#!9VyIwZKC+i8g?L??8SepY+7fTm*>D)?&Y1QMoqnq}IRM906HQkGUX3JbodA>FT@Th$ds^R&93S>dkOCzwYs>Oz3LAyB=EJa`CHA1_`=Lcf732 zY;J3J)Yx|4WMlF(1bH9iX6xSi=u!WgXZEdwD*^{7|6|YI=RFz7RVy9Shk}aL8t@$< zJc5?pJ#a6=;})((8yg~f8)tZm$vybE<8bG>yo};e0zGeDs4_H8tV$VM83}v5=_MQ! zOpUNS!cSRUe2s{0EZf#tc%9q(OKmIhz(7DJu^b*}2>&m5Ayl<=DYMDF_YWCHwCBTF zOAg7&#+83J8L#4NL0WaGp3KD5!1={=NTK5Nc}r^x-)=#y-us6Ome52JlN84rwXV{Cl<;sN zf-C1!+{yxfc}Cv;Q(M#$NfZ}NY_w>~o7+80S+CTF z9=v^Qt^i{gELZyMyqxeAUo)U~k%oIf^*GNI8n+P@e?;z`J*H)IWtDCgki}K9@EQ^%lq;FPhYYEX>+BRQF#wWrwvodyS zi5(`S|GGwCkia*9VjM1WlN^~GUq-NC;a|n~)m$b>+`8HWViXfZ%Z;JCylG(xmz)jZ zPjilt9SPk%-r4<)20?p7BD3XUi1KyxYLIIwlao8Q?*Yr7`6vjVUSPZ7J+@XL z>|y%a_Uc4pqw^^=*6C;8IKY(<)%ncGTO>yd_RocSJ>b(F6)ZIhj6>3Q>uv%s2AXY= zs%~g!f?UtLEvP@4c-&+hZ@@&UD`@<~{5F zlQn*kk%DV02T%N$g`^8{b+jT@QmURO+tc0^Ana`#7u8F}0U0f?Ykfu;q-!#H=p#_k_5iD>>kmecdMJc@;mGaGWSV%p~D%A>*Jf} zuVEi%?Y0kWm%Iv!EuNQa;C18jB!jzXzJEI38)UQLCSz90?P%^SZ|o@T#9(ZqME+H- zBR=F63by_A7VC}k#s^T+t43?WiN=R`$&i(v+-7DUr4Wah2p?HP;{Yum>J`7jc!Pl@ zfg;SU9o(Bm#@A-I?kDFLb>W&r)rfArru*9SE_xnWaPKrXyhNcJGMaNjHQ`~UF7jpI}9K=3k}&!7oA@|rW{+Y zrS%&>vQ?CbU{^=tses<792RmNuJYqZa+R&Cx|qv0fE8`@sv<_7DKOH~cgFOHds?Br zeDf;=xqjx*eb)3uMg!=_5fCNA_LTBOeRs+gy65d-U1Y^(9=vp`*J{ z4CbXWwHFF|6H&G6111y8VbIeLa(E1l^D=LVPsbZ;RCX-wq>|f^&sZ`+<$0cUN+fQG z8wVG^yYxGf^^VM&EHjQBpku9!1?^^aTzX1H2rs*>rqtM^`mx-MH6R31(Ks$+vHq@! z?K6#O(~R*kLj1skMSl^3kzYKQ^1r=Z;;rd^umw{U@G6kPNEUgF33v;ps?wCbOoH z3kCb3+BsEORnOn5QwLrJHbSvjHRO3xTt6O;xv4* zb;U8!t1UT(nRFv=b)m`tF{!ZLz9dk&H9|fR$!6b9Fw@kUkI?rir5#;-a>>pg1c+}_13rjA!|X%wo}Ix_Al7w28}_7 zRJ67EZCI5yrX#!8U!KOtMPgkl=q5eTM1>3nCHJh?_}3dVVLy@dJzbZSLrR!7DyV*P zrwdAyLYG(jXW7ST8600{RiLw4@aGE-rYdy(zCBqW5I9pSjp=WYX}jAm8^`R-P>^i@ z<=WUeiBWB8^12r_maqCEh(RYDi2m!Y;#o4?NJ&YLN6Tq^-)!4XPf^AsCzoLbcPab4 z8Wk$JYZ@e>CKPmLT zP<&8@mU=%Wcp5a3;8Mv&^s!>CQ9Kz3j`)GVXi^zh5iK8O(?1qK;Itu_@dsf_X?Rzf z(G7}oUVI|TO6H@w&&6kNLe~berq;Ltb(qx4B(b#rS+)!(;(~;PCk2Rc(aNR%N=m|~ zrKR<}-SXje*dJ5zLX%DBjq!sM48v!=lSn)}J5v~pB&n{h{(8AT{&+Rx&c_b)hbp%r zPhU1$k`9lJq18!uhOHi`jZnfd@VB+7Y_)T_T*DZe)O>(2X?3~DIMO3a=?HsL#JSD;1ZfzFr9))4-%Dvp6H&m>F*Bp5(j;_f!Z>4ip zSfnRyb~b@`Cyt!M!}M6;3?W5=L=k~QLy~_t#e;(+7s-Mt=E^JBCS+*z7-8`gSY9yd zN(##-dQPwOlIUCz4O^n~_T*2vz(VW~qyI4|EI;BoKz+`|PlDYLtq zks#P~g1gA1g=du@^A)3huMMi*uZi5R-3c8W956`u`!4nvhd?02?y0Gm8skCbrb+>J zcJ_1um*>h?cNIl_kMZ8Y_#3bKWvsu<4%~b&`I*P+2|Df+(OHK4Vl}?a0%Sm z-xoJEr4?{K{<rq;m+0JaZ~7UAiub>k~ee6>;1^P;nM|R*^NzK$fez%|3)NZ^Y}w79!cyQ z7l+MbyZ&u|471tolD4yx+4bS1sYEFcK_ZH@cSsW2?Sg`%M`yISrH2yv80?z>j{s>@ z1gzQ&CkpEcLbgU#lH1*0l2VCkU%%c?5ZQeE=?1BwJDX9TfXhkKN?M<4m3~GHmBe(j z9aX$E%|c~=oy8mji++5VBtRMZ>nZ2r8ltJeLrq6d(vriN`OT^PD0l9Fz53eKTc9QN zHce>{n_ZMjd*MjltZHFs%4ExE#|`wWqn3!rW-OWAn4N=TCr)91rbvOT(P{~nW&F$jb_BJgxKE8zH5Uhv@ z#%hyPcvu(*huOr}xzf3GAul2c2?<(R0tI(>{vZsJ(phfL=R15DfLaYhRP?oh_nk=# z6qu`Hsn@WBQDkP&ZJOrRRyLbeUS$>AYBNx#y-AykPe^t)`9L_Ke@x8V%1Rb<&hL(g z(*->yWphr*=*-$6i@DMo?i}aE|^j zW);o-)nTv82J_x>gC(amq_eQ_1hB0|UnQUX!y;gBnK z{GF(po#QC;THDF73PDybqMqw3OV2JJQn@vL_2CaqHfy2kWnyJ>wO$@?fI(?Gn#f!{ zXR*4vs#*ON4H-EEX#RA438ub2x=c|-a4Z>avER|SQ zttT@&TJhe+$cVDBk(+>!P^nCv*^!?F&||@lu~B8B%%YsEECD~TxbyNV(W;{j3>2$U zV&mefxVq5O)%{^_pKG~Ld81n;vA3xhmY+`z=uA3DOkz+q8O@;6^RChmFmGT-eqB91 zVE*Kah2gn+kbNndvAf)tvsrD1#aXK$;4~+nn3zaTOM}l|IAYW-3SFnvC`*K|si`R# zcSJ!&ZE?Te+8ERNarafL79)GX@cZ|WhKA6;Ugi6ApZ#8yUYq)%+u3qM*l--(76dX< zAd|%Fc7X#-ngncskCNKZ2gy{uSoSKP&V=InX#0C?Mv~ZMN>;Eua-K{ttY@9We%| zX%>=6>uY@~(gxY02GK8@*cM?}AdxtTSe9BOE}nxOy@y^~T^(vkNy+ZPL0ocja7YNU zy1IJ7j^!M~231^95#7Vh865)yN{4=wa!KF%`txbKQc;^3mceXb+i&9tLuF;k28+3# zzP@}%p!XQ1q!t(jqt4ISAag1^r>7H*)?Lb7-d>P-HHSNUSLov^%pwpfABq;r%gbZd zXNH7Gx%5}5S7@sdg@uQsaT3WT^nGMzjsWI#?T;-=KYxGd^>qTa`aef-5x#_t6E@8) z{3p7(D2~n!R{LkWx;&GvgJPY*YPlatYaS(~cVYqOuxZ^Kh~ zy1!O>k3&F2bg`e-tH_XmOFK3&Fi>x$HJi9PRD3MHTqu_Yg+l31X$Fvacz6KQD4HeY zRmxNtgh?h`HunK=SG@fE7d@!f;Mo$+EZ#mCm{)jGUxZavzPH_tAfcibnT#fWkr<4Q zixUN0!umQoGG>=_)r(6@Q>AK**~KsSE3Cz(Bfy{{ zWZUFwbvz9B_lM8S%tRv-N(T}(fSY#+=($>TrhtTUlZ_q`_Z2NazxZF{;3}_LDJ5%& z7xFeqvfY5NBXE%|;*07>u1K*HL+L11JFT~%z?@NgGzgkKgTBXKDE|5S~KxtVb6ojb~~CK?zmD? zQU!vY@tSSU%*F%lgQ2*LlZW-k8)Q9z!cVouMMNmO9xqVy#3MusYPTVCWd&>e`W@~G zQ9}30!u|-;WecO`4ce8uEj_>xQrFVGytugCjeGgv+58D`l%GBTBvNQ-?MJ>d56GC9 zgR`^ofVYMf!whwIb9;-6tJWTY%%s;E4j70WMS|GaSdq`4$wh-Yl@3kJIf*)NjR11& z2M(ZrbUQs$b_Sy~?(FbzaKdwP{5riJ*xj$pr)Oqb91pR8ILPN`3(of03pen6Gc$9z z0xNkxLM8Y@0^V%%83LC-n4*G0%`$_65ZT#XJ}EAC*SzjXyNipB>9#GJ|7v0?mlO!E z)p@hgeqNR7cmV;0fW40Sn|yWk{)n=6<&*v4StpQIS5G{C108d4aw<7b2S^5$p4)13 zBj28Wqt3ws)rCO^kz_tf=|p9QAKoKNrD|GeE^=J&RY?s89~@{}o%B46VVJqQHcCPM-WJUl$G9*>eTG^8Mk5RU~QeWQQ< zn|t`cKj+tHAU~i$ssAux#Qq0-9jF0N58ywnf5S`vt?WMuK%4)H{GW{eKhpm?p8nrS x|849)IsbRr|FiUe7xkY;{G+P>SNd7}1v9Hz!eyQK$OQ)Yq{QUEREm7{`!BZLXJh~X literal 40992 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 From cf4dfcbd59fd50187afd3c3e1e941df6267d5121 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 3 Jan 2025 18:29:01 +0000 Subject: [PATCH 631/932] =?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 [skip ci] --- 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 1b5fb25c7..2c88669d2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Docs +* 📝 Update image in body-nested-model docs. PR [#11063](https://github.com/fastapi/fastapi/pull/11063) by [@untilhamza](https://github.com/untilhamza). * 📝 Update `fastapi-cli` UI examples in docs. PR [#13107](https://github.com/fastapi/fastapi/pull/13107) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 👷 Add new GitHub Action to update contributors, translators, and translation reviewers. PR [#13136](https://github.com/fastapi/fastapi/pull/13136) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix typo in `docs/en/docs/virtual-environments.md`. PR [#13124](https://github.com/fastapi/fastapi/pull/13124) by [@tiangolo](https://github.com/tiangolo). From 083c6dd481cb1c4bafdafb08deea9b83b1cfbdd1 Mon Sep 17 00:00:00 2001 From: Chai Landau <112015853+chailandau@users.noreply.github.com> Date: Fri, 3 Jan 2025 16:29:07 -0500 Subject: [PATCH 632/932] =?UTF-8?q?=F0=9F=94=A7=20Update=20Speakeasy=20spo?= =?UTF-8?q?nsor=20graphic=20(#13147)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/img/sponsors/speakeasy.png | Bin 4790 -> 11887 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/docs/en/docs/img/sponsors/speakeasy.png b/docs/en/docs/img/sponsors/speakeasy.png index 001b4b4caffe26d75892dd040064c5d5f4c1ff22..5ddc25487b6b52ea5da49effe465605de207ee3d 100644 GIT binary patch literal 11887 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 literal 4790 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 JRI6we`aev(U(5gi From 023bc0196771058dd167dbe7abe00d11c9e2d0cd Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 3 Jan 2025 21:29:28 +0000 Subject: [PATCH 633/932] =?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 [skip ci] --- 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 2c88669d2..846904a09 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -70,6 +70,7 @@ hide: ### Internal +* 🔧 Update Speakeasy sponsor graphic. PR [#13147](https://github.com/fastapi/fastapi/pull/13147) by [@chailandau](https://github.com/chailandau). * 👥 Update FastAPI GitHub topic repositories. PR [#13146](https://github.com/fastapi/fastapi/pull/13146) by [@tiangolo](https://github.com/tiangolo). * 👷‍♀️ Add script for GitHub Topic Repositories and update External Links. PR [#13135](https://github.com/fastapi/fastapi/pull/13135) by [@alejsdev](https://github.com/alejsdev). * 👥 Update FastAPI People - Contributors and Translators. PR [#13145](https://github.com/fastapi/fastapi/pull/13145) by [@tiangolo](https://github.com/tiangolo). From f229dd97c05aefcf6d28112c4126fb85d1619fde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 4 Jan 2025 00:26:30 +0000 Subject: [PATCH 634/932] =?UTF-8?q?=F0=9F=91=B7=20Add=20retries=20to=20Smo?= =?UTF-8?q?keshow=20(#13151)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/smokeshow.yml | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index ba505985d..a0ffd55e6 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -40,7 +40,17 @@ jobs: path: htmlcov github-token: ${{ secrets.GITHUB_TOKEN }} run-id: ${{ github.event.workflow_run.id }} - - run: smokeshow upload htmlcov + # Try 5 times to upload coverage to smokeshow + - name: Upload coverage to Smokeshow + run: | + for i in 1 2 3 4 5; do + if smokeshow upload htmlcov; then + echo "Smokeshow upload success!" + break + fi + echo "Smokeshow upload error, sleep 1 sec and try again." + sleep 1 + done env: SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage} SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 100 From c99b945d879c4e2c7a8414045476c58a2fd2b788 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 4 Jan 2025 00:26:56 +0000 Subject: [PATCH 635/932] =?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 [skip ci] --- 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 846904a09..714d217c4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -70,6 +70,7 @@ hide: ### Internal +* 👷 Add retries to Smokeshow. PR [#13151](https://github.com/fastapi/fastapi/pull/13151) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update Speakeasy sponsor graphic. PR [#13147](https://github.com/fastapi/fastapi/pull/13147) by [@chailandau](https://github.com/chailandau). * 👥 Update FastAPI GitHub topic repositories. PR [#13146](https://github.com/fastapi/fastapi/pull/13146) by [@tiangolo](https://github.com/tiangolo). * 👷‍♀️ Add script for GitHub Topic Repositories and update External Links. PR [#13135](https://github.com/fastapi/fastapi/pull/13135) by [@alejsdev](https://github.com/alejsdev). From dace29835c8374743cb346e8e932245bb73197e5 Mon Sep 17 00:00:00 2001 From: FakeDocument <127398201+FakeDocument@users.noreply.github.com> Date: Sat, 4 Jan 2025 19:53:58 +0900 Subject: [PATCH 636/932] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Delete=20unnecessa?= =?UTF-8?q?ry=20backspace=20in=20`docs/ja/docs/tutorial/path-params-numeri?= =?UTF-8?q?c-validations.md`=20(#12238)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ja/docs/tutorial/path-params-numeric-validations.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/ja/docs/tutorial/path-params-numeric-validations.md b/docs/ja/docs/tutorial/path-params-numeric-validations.md index 13a71f72f..a1810ae37 100644 --- a/docs/ja/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ja/docs/tutorial/path-params-numeric-validations.md @@ -58,7 +58,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 `Query`と`Path`(、そして後述する他のもの)を用いて、文字列の制約を宣言することができますが、数値の制約も同様に宣言できます。 -ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなれけばなりません。 +ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなれけばなりません。 {* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *} @@ -104,7 +104,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 /// note | 技術詳細 -`fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。 +`fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。 呼び出されると、同じ名前のクラスのインスタンスを返します。 From 924c96bf9098a3de933536d383f33fe6b555ac7c Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 4 Jan 2025 10:54:27 +0000 Subject: [PATCH 637/932] =?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 [skip ci] --- 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 714d217c4..9b6cae978 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -25,6 +25,7 @@ hide: ### Translations +* ✏️ Delete unnecessary backspace in `docs/ja/docs/tutorial/path-params-numeric-validations.md`. PR [#12238](https://github.com/fastapi/fastapi/pull/12238) by [@FakeDocument](https://github.com/FakeDocument). * 🌐 Update Chinese translation for `docs/zh/docs/fastapi-cli.md`. PR [#13102](https://github.com/fastapi/fastapi/pull/13102) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Add new Spanish translations for all docs with new LLM-assisted system using PydanticAI. PR [#13122](https://github.com/fastapi/fastapi/pull/13122) by [@tiangolo](https://github.com/tiangolo). * 🌐 Update existing Spanish translations using the new LLM-assisted system using PydanticAI. PR [#13118](https://github.com/fastapi/fastapi/pull/13118) by [@tiangolo](https://github.com/tiangolo). From d784a90207e6545a62d86b57c7a09a0c90e29bce Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 5 Jan 2025 14:44:44 +0000 Subject: [PATCH 638/932] =?UTF-8?q?=F0=9F=94=A5=20Remove=20unused=20Peewee?= =?UTF-8?q?=20tutorial=20files=20(#13158)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../sql_databases_peewee/sql_app/__init__.py | 0 docs_src/sql_databases_peewee/sql_app/crud.py | 30 ------- .../sql_databases_peewee/sql_app/database.py | 24 ------ docs_src/sql_databases_peewee/sql_app/main.py | 79 ------------------- .../sql_databases_peewee/sql_app/models.py | 21 ----- .../sql_databases_peewee/sql_app/schemas.py | 49 ------------ 6 files changed, 203 deletions(-) delete mode 100644 docs_src/sql_databases_peewee/sql_app/__init__.py delete mode 100644 docs_src/sql_databases_peewee/sql_app/crud.py delete mode 100644 docs_src/sql_databases_peewee/sql_app/database.py delete mode 100644 docs_src/sql_databases_peewee/sql_app/main.py delete mode 100644 docs_src/sql_databases_peewee/sql_app/models.py delete mode 100644 docs_src/sql_databases_peewee/sql_app/schemas.py diff --git a/docs_src/sql_databases_peewee/sql_app/__init__.py b/docs_src/sql_databases_peewee/sql_app/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs_src/sql_databases_peewee/sql_app/crud.py b/docs_src/sql_databases_peewee/sql_app/crud.py deleted file mode 100644 index 56c587559..000000000 --- a/docs_src/sql_databases_peewee/sql_app/crud.py +++ /dev/null @@ -1,30 +0,0 @@ -from . import models, schemas - - -def get_user(user_id: int): - return models.User.filter(models.User.id == user_id).first() - - -def get_user_by_email(email: str): - return models.User.filter(models.User.email == email).first() - - -def get_users(skip: int = 0, limit: int = 100): - return list(models.User.select().offset(skip).limit(limit)) - - -def create_user(user: schemas.UserCreate): - fake_hashed_password = user.password + "notreallyhashed" - db_user = models.User(email=user.email, hashed_password=fake_hashed_password) - db_user.save() - return db_user - - -def get_items(skip: int = 0, limit: int = 100): - return list(models.Item.select().offset(skip).limit(limit)) - - -def create_user_item(item: schemas.ItemCreate, user_id: int): - db_item = models.Item(**item.dict(), owner_id=user_id) - db_item.save() - return db_item diff --git a/docs_src/sql_databases_peewee/sql_app/database.py b/docs_src/sql_databases_peewee/sql_app/database.py deleted file mode 100644 index 6938fe826..000000000 --- a/docs_src/sql_databases_peewee/sql_app/database.py +++ /dev/null @@ -1,24 +0,0 @@ -from contextvars import ContextVar - -import peewee - -DATABASE_NAME = "test.db" -db_state_default = {"closed": None, "conn": None, "ctx": None, "transactions": None} -db_state = ContextVar("db_state", default=db_state_default.copy()) - - -class PeeweeConnectionState(peewee._ConnectionState): - def __init__(self, **kwargs): - super().__setattr__("_state", db_state) - super().__init__(**kwargs) - - def __setattr__(self, name, value): - self._state.get()[name] = value - - def __getattr__(self, name): - return self._state.get()[name] - - -db = peewee.SqliteDatabase(DATABASE_NAME, check_same_thread=False) - -db._state = PeeweeConnectionState() diff --git a/docs_src/sql_databases_peewee/sql_app/main.py b/docs_src/sql_databases_peewee/sql_app/main.py deleted file mode 100644 index 8fbd2075d..000000000 --- a/docs_src/sql_databases_peewee/sql_app/main.py +++ /dev/null @@ -1,79 +0,0 @@ -import time -from typing import List - -from fastapi import Depends, FastAPI, HTTPException - -from . import crud, database, models, schemas -from .database import db_state_default - -database.db.connect() -database.db.create_tables([models.User, models.Item]) -database.db.close() - -app = FastAPI() - -sleep_time = 10 - - -async def reset_db_state(): - database.db._state._state.set(db_state_default.copy()) - database.db._state.reset() - - -def get_db(db_state=Depends(reset_db_state)): - try: - database.db.connect() - yield - finally: - if not database.db.is_closed(): - database.db.close() - - -@app.post("/users/", response_model=schemas.User, dependencies=[Depends(get_db)]) -def create_user(user: schemas.UserCreate): - db_user = crud.get_user_by_email(email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(user=user) - - -@app.get("/users/", response_model=List[schemas.User], dependencies=[Depends(get_db)]) -def read_users(skip: int = 0, limit: int = 100): - users = crud.get_users(skip=skip, limit=limit) - return users - - -@app.get( - "/users/{user_id}", response_model=schemas.User, dependencies=[Depends(get_db)] -) -def read_user(user_id: int): - db_user = crud.get_user(user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post( - "/users/{user_id}/items/", - response_model=schemas.Item, - dependencies=[Depends(get_db)], -) -def create_item_for_user(user_id: int, item: schemas.ItemCreate): - return crud.create_user_item(item=item, user_id=user_id) - - -@app.get("/items/", response_model=List[schemas.Item], dependencies=[Depends(get_db)]) -def read_items(skip: int = 0, limit: int = 100): - items = crud.get_items(skip=skip, limit=limit) - return items - - -@app.get( - "/slowusers/", response_model=List[schemas.User], dependencies=[Depends(get_db)] -) -def read_slow_users(skip: int = 0, limit: int = 100): - global sleep_time - sleep_time = max(0, sleep_time - 1) - time.sleep(sleep_time) # Fake long processing request - users = crud.get_users(skip=skip, limit=limit) - return users diff --git a/docs_src/sql_databases_peewee/sql_app/models.py b/docs_src/sql_databases_peewee/sql_app/models.py deleted file mode 100644 index 46bdcd009..000000000 --- a/docs_src/sql_databases_peewee/sql_app/models.py +++ /dev/null @@ -1,21 +0,0 @@ -import peewee - -from .database import db - - -class User(peewee.Model): - email = peewee.CharField(unique=True, index=True) - hashed_password = peewee.CharField() - is_active = peewee.BooleanField(default=True) - - class Meta: - database = db - - -class Item(peewee.Model): - title = peewee.CharField(index=True) - description = peewee.CharField(index=True) - owner = peewee.ForeignKeyField(User, backref="items") - - class Meta: - database = db diff --git a/docs_src/sql_databases_peewee/sql_app/schemas.py b/docs_src/sql_databases_peewee/sql_app/schemas.py deleted file mode 100644 index d8775cb30..000000000 --- a/docs_src/sql_databases_peewee/sql_app/schemas.py +++ /dev/null @@ -1,49 +0,0 @@ -from typing import Any, List, Union - -import peewee -from pydantic import BaseModel -from pydantic.utils import GetterDict - - -class PeeweeGetterDict(GetterDict): - def get(self, key: Any, default: Any = None): - res = getattr(self._obj, key, default) - if isinstance(res, peewee.ModelSelect): - return list(res) - return res - - -class ItemBase(BaseModel): - title: str - description: Union[str, None] = None - - -class ItemCreate(ItemBase): - pass - - -class Item(ItemBase): - id: int - owner_id: int - - class Config: - orm_mode = True - getter_dict = PeeweeGetterDict - - -class UserBase(BaseModel): - email: str - - -class UserCreate(UserBase): - password: str - - -class User(UserBase): - id: int - is_active: bool - items: List[Item] = [] - - class Config: - orm_mode = True - getter_dict = PeeweeGetterDict From 6e60d0a0563497f134088b9d161611367b95d21d Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 5 Jan 2025 14:45:08 +0000 Subject: [PATCH 639/932] =?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 [skip ci] --- 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 9b6cae978..cb0eda45d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Docs +* 🔥 Remove unused Peewee tutorial files. PR [#13158](https://github.com/fastapi/fastapi/pull/13158) by [@alejsdev](https://github.com/alejsdev). * 📝 Update image in body-nested-model docs. PR [#11063](https://github.com/fastapi/fastapi/pull/11063) by [@untilhamza](https://github.com/untilhamza). * 📝 Update `fastapi-cli` UI examples in docs. PR [#13107](https://github.com/fastapi/fastapi/pull/13107) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 👷 Add new GitHub Action to update contributors, translators, and translation reviewers. PR [#13136](https://github.com/fastapi/fastapi/pull/13136) by [@tiangolo](https://github.com/tiangolo). From b0e70cb37e2fe9446f51443d88cb053da91748ce Mon Sep 17 00:00:00 2001 From: Kinuax Date: Mon, 6 Jan 2025 12:24:17 +0100 Subject: [PATCH 640/932] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Update=20Strawberr?= =?UTF-8?q?y=20integration=20docs=20(#13155)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/how-to/graphql.md | 2 +- docs_src/graphql/tutorial001.py | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/docs/en/docs/how-to/graphql.md b/docs/en/docs/how-to/graphql.md index a6219e481..361010736 100644 --- a/docs/en/docs/how-to/graphql.md +++ b/docs/en/docs/how-to/graphql.md @@ -35,7 +35,7 @@ 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] *} +{* ../../docs_src/graphql/tutorial001.py hl[3,22,25] *} You can learn more about Strawberry in the Strawberry documentation. diff --git a/docs_src/graphql/tutorial001.py b/docs_src/graphql/tutorial001.py index 3b4ca99cf..e92b2d71c 100644 --- a/docs_src/graphql/tutorial001.py +++ b/docs_src/graphql/tutorial001.py @@ -1,6 +1,6 @@ import strawberry from fastapi import FastAPI -from strawberry.asgi import GraphQL +from strawberry.fastapi import GraphQLRouter @strawberry.type @@ -19,8 +19,7 @@ class Query: schema = strawberry.Schema(query=Query) -graphql_app = GraphQL(schema) +graphql_app = GraphQLRouter(schema) app = FastAPI() -app.add_route("/graphql", graphql_app) -app.add_websocket_route("/graphql", graphql_app) +app.include_router(graphql_app, prefix="/graphql") From d7bd68979f9db9dc3b6a59dc3b8ba46b47580dbc Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 6 Jan 2025 11:24:40 +0000 Subject: [PATCH 641/932] =?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 [skip ci] --- 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 cb0eda45d..520b0f9e6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Docs +* ✏️ Update Strawberry integration docs. PR [#13155](https://github.com/fastapi/fastapi/pull/13155) by [@kinuax](https://github.com/kinuax). * 🔥 Remove unused Peewee tutorial files. PR [#13158](https://github.com/fastapi/fastapi/pull/13158) by [@alejsdev](https://github.com/alejsdev). * 📝 Update image in body-nested-model docs. PR [#11063](https://github.com/fastapi/fastapi/pull/11063) by [@untilhamza](https://github.com/untilhamza). * 📝 Update `fastapi-cli` UI examples in docs. PR [#13107](https://github.com/fastapi/fastapi/pull/13107) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). From 4cd5a7ac1c8f37951cec2caf4ad150aa75c112d8 Mon Sep 17 00:00:00 2001 From: Yaroslav Luchinsky <61277193+Yarous@users.noreply.github.com> Date: Mon, 6 Jan 2025 21:26:39 +0300 Subject: [PATCH 642/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Russian=20trans?= =?UTF-8?q?lation=20for=20`docs/ru/docs/tutorial/security/first-steps.md`?= =?UTF-8?q?=20(#13159)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/tutorial/security/first-steps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ru/docs/tutorial/security/first-steps.md b/docs/ru/docs/tutorial/security/first-steps.md index e55f48b89..375c2d7f6 100644 --- a/docs/ru/docs/tutorial/security/first-steps.md +++ b/docs/ru/docs/tutorial/security/first-steps.md @@ -182,7 +182,7 @@ oauth2_scheme(some, parameters) Если он не видит заголовка `Authorization` или значение не имеет токена `Bearer`, то в ответ будет выдана ошибка с кодом состояния 401 (`UNAUTHORIZED`). -Для возврата ошибки даже не нужно проверять, существует ли токен. Вы можете быть уверены, что если ваша функция будет выполнилась, то в этом токене есть `строка`. +Для возврата ошибки даже не нужно проверять, существует ли токен. Вы можете быть уверены, что если ваша функция была выполнена, то в этом токене есть `строка`. Проверить это можно уже сейчас в интерактивной документации: From 144f09ea146b2cc026bf317f730aa0e0dbc3de24 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 6 Jan 2025 18:27:10 +0000 Subject: [PATCH 643/932] =?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 [skip ci] --- 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 520b0f9e6..e3e07afb7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Translations +* 🌐 Update Russian translation for `docs/ru/docs/tutorial/security/first-steps.md`. PR [#13159](https://github.com/fastapi/fastapi/pull/13159) by [@Yarous](https://github.com/Yarous). * ✏️ Delete unnecessary backspace in `docs/ja/docs/tutorial/path-params-numeric-validations.md`. PR [#12238](https://github.com/fastapi/fastapi/pull/12238) by [@FakeDocument](https://github.com/FakeDocument). * 🌐 Update Chinese translation for `docs/zh/docs/fastapi-cli.md`. PR [#13102](https://github.com/fastapi/fastapi/pull/13102) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). * 🌐 Add new Spanish translations for all docs with new LLM-assisted system using PydanticAI. PR [#13122](https://github.com/fastapi/fastapi/pull/13122) by [@tiangolo](https://github.com/tiangolo). From 44adb29ce18b5a720898ca69c2b0995170542da2 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Wed, 8 Jan 2025 19:23:42 +0000 Subject: [PATCH 644/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20ba?= =?UTF-8?q?ckground=5Ftasks=20(#13166)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_background_tasks/test_tutorial002.py | 23 ++++++++++++++++--- .../test_tutorial002_an.py | 19 --------------- .../test_tutorial002_an_py310.py | 21 ----------------- .../test_tutorial002_an_py39.py | 21 ----------------- .../test_tutorial002_py310.py | 21 ----------------- 5 files changed, 20 insertions(+), 85 deletions(-) delete mode 100644 tests/test_tutorial/test_background_tasks/test_tutorial002_an.py delete mode 100644 tests/test_tutorial/test_background_tasks/test_tutorial002_an_py310.py delete mode 100644 tests/test_tutorial/test_background_tasks/test_tutorial002_an_py39.py delete mode 100644 tests/test_tutorial/test_background_tasks/test_tutorial002_py310.py diff --git a/tests/test_tutorial/test_background_tasks/test_tutorial002.py b/tests/test_tutorial/test_background_tasks/test_tutorial002.py index 74de1314b..d5ef51ee2 100644 --- a/tests/test_tutorial/test_background_tasks/test_tutorial002.py +++ b/tests/test_tutorial/test_background_tasks/test_tutorial002.py @@ -1,14 +1,31 @@ +import importlib import os from pathlib import Path +import pytest from fastapi.testclient import TestClient -from docs_src.background_tasks.tutorial002 import app +from ...utils import needs_py39, needs_py310 -client = TestClient(app) +@pytest.fixture( + name="client", + params=[ + "tutorial002", + pytest.param("tutorial002_py310", marks=needs_py310), + "tutorial002_an", + pytest.param("tutorial002_an_py39", marks=needs_py39), + pytest.param("tutorial002_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.background_tasks.{request.param}") -def test(): + client = TestClient(mod.app) + return client + + +def test(client: TestClient): log = Path("log.txt") if log.is_file(): os.remove(log) # pragma: no cover diff --git a/tests/test_tutorial/test_background_tasks/test_tutorial002_an.py b/tests/test_tutorial/test_background_tasks/test_tutorial002_an.py deleted file mode 100644 index af682ecff..000000000 --- a/tests/test_tutorial/test_background_tasks/test_tutorial002_an.py +++ /dev/null @@ -1,19 +0,0 @@ -import os -from pathlib import Path - -from fastapi.testclient import TestClient - -from docs_src.background_tasks.tutorial002_an import app - -client = TestClient(app) - - -def test(): - log = Path("log.txt") - if log.is_file(): - os.remove(log) # pragma: no cover - response = client.post("/send-notification/foo@example.com?q=some-query") - assert response.status_code == 200, response.text - assert response.json() == {"message": "Message sent"} - with open("./log.txt") as f: - assert "found query: some-query\nmessage to foo@example.com" in f.read() diff --git a/tests/test_tutorial/test_background_tasks/test_tutorial002_an_py310.py b/tests/test_tutorial/test_background_tasks/test_tutorial002_an_py310.py deleted file mode 100644 index 067b2787e..000000000 --- a/tests/test_tutorial/test_background_tasks/test_tutorial002_an_py310.py +++ /dev/null @@ -1,21 +0,0 @@ -import os -from pathlib import Path - -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@needs_py310 -def test(): - from docs_src.background_tasks.tutorial002_an_py310 import app - - client = TestClient(app) - log = Path("log.txt") - if log.is_file(): - os.remove(log) # pragma: no cover - response = client.post("/send-notification/foo@example.com?q=some-query") - assert response.status_code == 200, response.text - assert response.json() == {"message": "Message sent"} - with open("./log.txt") as f: - assert "found query: some-query\nmessage to foo@example.com" in f.read() diff --git a/tests/test_tutorial/test_background_tasks/test_tutorial002_an_py39.py b/tests/test_tutorial/test_background_tasks/test_tutorial002_an_py39.py deleted file mode 100644 index 06b5a2f57..000000000 --- a/tests/test_tutorial/test_background_tasks/test_tutorial002_an_py39.py +++ /dev/null @@ -1,21 +0,0 @@ -import os -from pathlib import Path - -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@needs_py39 -def test(): - from docs_src.background_tasks.tutorial002_an_py39 import app - - client = TestClient(app) - log = Path("log.txt") - if log.is_file(): - os.remove(log) # pragma: no cover - response = client.post("/send-notification/foo@example.com?q=some-query") - assert response.status_code == 200, response.text - assert response.json() == {"message": "Message sent"} - with open("./log.txt") as f: - assert "found query: some-query\nmessage to foo@example.com" in f.read() diff --git a/tests/test_tutorial/test_background_tasks/test_tutorial002_py310.py b/tests/test_tutorial/test_background_tasks/test_tutorial002_py310.py deleted file mode 100644 index 6937c8fab..000000000 --- a/tests/test_tutorial/test_background_tasks/test_tutorial002_py310.py +++ /dev/null @@ -1,21 +0,0 @@ -import os -from pathlib import Path - -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@needs_py310 -def test(): - from docs_src.background_tasks.tutorial002_py310 import app - - client = TestClient(app) - log = Path("log.txt") - if log.is_file(): - os.remove(log) # pragma: no cover - response = client.post("/send-notification/foo@example.com?q=some-query") - assert response.status_code == 200, response.text - assert response.json() == {"message": "Message sent"} - with open("./log.txt") as f: - assert "found query: some-query\nmessage to foo@example.com" in f.read() From afd150228352ffc87d04ed841870dcab6936b4f1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 8 Jan 2025 19:24:05 +0000 Subject: [PATCH 645/932] =?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 [skip ci] --- 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 e3e07afb7..bf95dbea9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for background_tasks. PR [#13166](https://github.com/fastapi/fastapi/pull/13166) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for additional_status_codes. PR [#13149](https://github.com/fastapi/fastapi/pull/13149) by [@tiangolo](https://github.com/tiangolo). ### Docs From 5d3f45c2d47f04a7a8c793c13e0349803394e86b Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Wed, 8 Jan 2025 19:25:01 +0000 Subject: [PATCH 646/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20bi?= =?UTF-8?q?gger=5Fapplications=20(#13167)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_bigger_applications/test_main.py | 19 +- .../test_bigger_applications/test_main_an.py | 715 ----------------- .../test_main_an_py39.py | 742 ------------------ 3 files changed, 15 insertions(+), 1461 deletions(-) delete mode 100644 tests/test_tutorial/test_bigger_applications/test_main_an.py delete mode 100644 tests/test_tutorial/test_bigger_applications/test_main_an_py39.py diff --git a/tests/test_tutorial/test_bigger_applications/test_main.py b/tests/test_tutorial/test_bigger_applications/test_main.py index 35fdfa4a6..fe40fad7d 100644 --- a/tests/test_tutorial/test_bigger_applications/test_main.py +++ b/tests/test_tutorial/test_bigger_applications/test_main.py @@ -1,13 +1,24 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient +from ...utils import needs_py39 + -@pytest.fixture(name="client") -def get_client(): - from docs_src.bigger_applications.app.main import app +@pytest.fixture( + name="client", + params=[ + "app_an.main", + pytest.param("app_an_py39.main", marks=needs_py39), + "app.main", + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.bigger_applications.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_bigger_applications/test_main_an.py b/tests/test_tutorial/test_bigger_applications/test_main_an.py deleted file mode 100644 index 4e2e3e74d..000000000 --- a/tests/test_tutorial/test_bigger_applications/test_main_an.py +++ /dev/null @@ -1,715 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.bigger_applications.app_an.main import app - - client = TestClient(app) - return client - - -def test_users_token_jessica(client: TestClient): - response = client.get("/users?token=jessica") - assert response.status_code == 200 - assert response.json() == [{"username": "Rick"}, {"username": "Morty"}] - - -def test_users_with_no_token(client: TestClient): - response = client.get("/users") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_users_foo_token_jessica(client: TestClient): - response = client.get("/users/foo?token=jessica") - assert response.status_code == 200 - assert response.json() == {"username": "foo"} - - -def test_users_foo_with_no_token(client: TestClient): - response = client.get("/users/foo") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_users_me_token_jessica(client: TestClient): - response = client.get("/users/me?token=jessica") - assert response.status_code == 200 - assert response.json() == {"username": "fakecurrentuser"} - - -def test_users_me_with_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_users_token_monica_with_no_jessica(client: TestClient): - response = client.get("/users?token=monica") - assert response.status_code == 400 - assert response.json() == {"detail": "No Jessica token provided"} - - -def test_items_token_jessica(client: TestClient): - response = client.get( - "/items?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 200 - assert response.json() == { - "plumbus": {"name": "Plumbus"}, - "gun": {"name": "Portal Gun"}, - } - - -def test_items_with_no_token_jessica(client: TestClient): - response = client.get("/items", headers={"X-Token": "fake-super-secret-token"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_items_plumbus_token_jessica(client: TestClient): - response = client.get( - "/items/plumbus?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 200 - assert response.json() == {"name": "Plumbus", "item_id": "plumbus"} - - -def test_items_bar_token_jessica(client: TestClient): - response = client.get( - "/items/bar?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 404 - assert response.json() == {"detail": "Item not found"} - - -def test_items_plumbus_with_no_token(client: TestClient): - response = client.get( - "/items/plumbus", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_items_with_invalid_token(client: TestClient): - response = client.get("/items?token=jessica", headers={"X-Token": "invalid"}) - assert response.status_code == 400 - assert response.json() == {"detail": "X-Token header invalid"} - - -def test_items_bar_with_invalid_token(client: TestClient): - response = client.get("/items/bar?token=jessica", headers={"X-Token": "invalid"}) - assert response.status_code == 400 - assert response.json() == {"detail": "X-Token header invalid"} - - -def test_items_with_missing_x_token_header(client: TestClient): - response = client.get("/items?token=jessica") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -def test_items_plumbus_with_missing_x_token_header(client: TestClient): - response = client.get("/items/plumbus?token=jessica") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -def test_root_token_jessica(client: TestClient): - response = client.get("/?token=jessica") - assert response.status_code == 200 - assert response.json() == {"message": "Hello Bigger Applications!"} - - -def test_root_with_no_token(client: TestClient): - response = client.get("/") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_put_no_header(client: TestClient): - response = client.put("/items/foo") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_put_invalid_header(client: TestClient): - response = client.put("/items/foo", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -def test_put(client: TestClient): - response = client.put( - "/items/plumbus?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"item_id": "plumbus", "name": "The great Plumbus"} - - -def test_put_forbidden(client: TestClient): - response = client.put( - "/items/bar?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 403, response.text - assert response.json() == {"detail": "You can only update the item: plumbus"} - - -def test_admin(client: TestClient): - response = client.post( - "/admin/?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"message": "Admin getting schwifty"} - - -def test_admin_invalid_header(client: TestClient): - response = client.post("/admin/", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "tags": ["users"], - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/users/me": { - "get": { - "tags": ["users"], - "summary": "Read User Me", - "operationId": "read_user_me_users_me_get", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/users/{username}": { - "get": { - "tags": ["users"], - "summary": "Read User", - "operationId": "read_user_users__username__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Username", "type": "string"}, - "name": "username", - "in": "path", - }, - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/items/": { - "get": { - "tags": ["items"], - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "404": {"description": "Not found"}, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/items/{item_id}": { - "get": { - "tags": ["items"], - "summary": "Read Item", - "operationId": "read_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - }, - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "404": {"description": "Not found"}, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - "put": { - "tags": ["items", "custom"], - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - }, - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "404": {"description": "Not found"}, - "403": {"description": "Operation forbidden"}, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - }, - "/admin/": { - "post": { - "tags": ["admin"], - "summary": "Update Admin", - "operationId": "update_admin_admin__post", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "418": {"description": "I'm a teapot"}, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/": { - "get": { - "summary": "Root", - "operationId": "root__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py b/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py deleted file mode 100644 index 8c9e976df..000000000 --- a/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py +++ /dev/null @@ -1,742 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.bigger_applications.app_an_py39.main import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_users_token_jessica(client: TestClient): - response = client.get("/users?token=jessica") - assert response.status_code == 200 - assert response.json() == [{"username": "Rick"}, {"username": "Morty"}] - - -@needs_py39 -def test_users_with_no_token(client: TestClient): - response = client.get("/users") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_users_foo_token_jessica(client: TestClient): - response = client.get("/users/foo?token=jessica") - assert response.status_code == 200 - assert response.json() == {"username": "foo"} - - -@needs_py39 -def test_users_foo_with_no_token(client: TestClient): - response = client.get("/users/foo") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_users_me_token_jessica(client: TestClient): - response = client.get("/users/me?token=jessica") - assert response.status_code == 200 - assert response.json() == {"username": "fakecurrentuser"} - - -@needs_py39 -def test_users_me_with_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_users_token_monica_with_no_jessica(client: TestClient): - response = client.get("/users?token=monica") - assert response.status_code == 400 - assert response.json() == {"detail": "No Jessica token provided"} - - -@needs_py39 -def test_items_token_jessica(client: TestClient): - response = client.get( - "/items?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 200 - assert response.json() == { - "plumbus": {"name": "Plumbus"}, - "gun": {"name": "Portal Gun"}, - } - - -@needs_py39 -def test_items_with_no_token_jessica(client: TestClient): - response = client.get("/items", headers={"X-Token": "fake-super-secret-token"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_items_plumbus_token_jessica(client: TestClient): - response = client.get( - "/items/plumbus?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 200 - assert response.json() == {"name": "Plumbus", "item_id": "plumbus"} - - -@needs_py39 -def test_items_bar_token_jessica(client: TestClient): - response = client.get( - "/items/bar?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 404 - assert response.json() == {"detail": "Item not found"} - - -@needs_py39 -def test_items_plumbus_with_no_token(client: TestClient): - response = client.get( - "/items/plumbus", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_items_with_invalid_token(client: TestClient): - response = client.get("/items?token=jessica", headers={"X-Token": "invalid"}) - assert response.status_code == 400 - assert response.json() == {"detail": "X-Token header invalid"} - - -@needs_py39 -def test_items_bar_with_invalid_token(client: TestClient): - response = client.get("/items/bar?token=jessica", headers={"X-Token": "invalid"}) - assert response.status_code == 400 - assert response.json() == {"detail": "X-Token header invalid"} - - -@needs_py39 -def test_items_with_missing_x_token_header(client: TestClient): - response = client.get("/items?token=jessica") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py39 -def test_items_plumbus_with_missing_x_token_header(client: TestClient): - response = client.get("/items/plumbus?token=jessica") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py39 -def test_root_token_jessica(client: TestClient): - response = client.get("/?token=jessica") - assert response.status_code == 200 - assert response.json() == {"message": "Hello Bigger Applications!"} - - -@needs_py39 -def test_root_with_no_token(client: TestClient): - response = client.get("/") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_put_no_header(client: TestClient): - response = client.put("/items/foo") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_put_invalid_header(client: TestClient): - response = client.put("/items/foo", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -@needs_py39 -def test_put(client: TestClient): - response = client.put( - "/items/plumbus?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"item_id": "plumbus", "name": "The great Plumbus"} - - -@needs_py39 -def test_put_forbidden(client: TestClient): - response = client.put( - "/items/bar?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 403, response.text - assert response.json() == {"detail": "You can only update the item: plumbus"} - - -@needs_py39 -def test_admin(client: TestClient): - response = client.post( - "/admin/?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"message": "Admin getting schwifty"} - - -@needs_py39 -def test_admin_invalid_header(client: TestClient): - response = client.post("/admin/", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "tags": ["users"], - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/users/me": { - "get": { - "tags": ["users"], - "summary": "Read User Me", - "operationId": "read_user_me_users_me_get", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/users/{username}": { - "get": { - "tags": ["users"], - "summary": "Read User", - "operationId": "read_user_users__username__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Username", "type": "string"}, - "name": "username", - "in": "path", - }, - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/items/": { - "get": { - "tags": ["items"], - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "404": {"description": "Not found"}, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/items/{item_id}": { - "get": { - "tags": ["items"], - "summary": "Read Item", - "operationId": "read_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - }, - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "404": {"description": "Not found"}, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - "put": { - "tags": ["items", "custom"], - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - }, - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "404": {"description": "Not found"}, - "403": {"description": "Operation forbidden"}, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - }, - "/admin/": { - "post": { - "tags": ["admin"], - "summary": "Update Admin", - "operationId": "update_admin_admin__post", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "418": {"description": "I'm a teapot"}, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/": { - "get": { - "summary": "Root", - "operationId": "root__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } From a8447c15e5193eb304cadaef114d2af3df25d2ce Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 8 Jan 2025 19:25:29 +0000 Subject: [PATCH 647/932] =?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 [skip ci] --- 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 bf95dbea9..559ddc5d7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for bigger_applications. PR [#13167](https://github.com/fastapi/fastapi/pull/13167) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for background_tasks. PR [#13166](https://github.com/fastapi/fastapi/pull/13166) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for additional_status_codes. PR [#13149](https://github.com/fastapi/fastapi/pull/13149) by [@tiangolo](https://github.com/tiangolo). From 0cc031f4779fbaf26e3bfa0394d95711f5675394 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Wed, 8 Jan 2025 19:26:16 +0000 Subject: [PATCH 648/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20bo?= =?UTF-8?q?dy=20(#13168)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_body/test_tutorial001.py | 17 +- .../test_body/test_tutorial001_py310.py | 498 ------------------ 2 files changed, 13 insertions(+), 502 deletions(-) delete mode 100644 tests/test_tutorial/test_body/test_tutorial001_py310.py diff --git a/tests/test_tutorial/test_body/test_tutorial001.py b/tests/test_tutorial/test_body/test_tutorial001.py index 0d55d73eb..f8b5aee8d 100644 --- a/tests/test_tutorial/test_body/test_tutorial001.py +++ b/tests/test_tutorial/test_body/test_tutorial001.py @@ -1,15 +1,24 @@ +import importlib from unittest.mock import patch import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient +from ...utils import needs_py310 -@pytest.fixture -def client(): - from docs_src.body.tutorial001 import app - client = TestClient(app) +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.body.{request.param}") + + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_body/test_tutorial001_py310.py b/tests/test_tutorial/test_body/test_tutorial001_py310.py deleted file mode 100644 index 4b9c12806..000000000 --- a/tests/test_tutorial/test_body/test_tutorial001_py310.py +++ /dev/null @@ -1,498 +0,0 @@ -from unittest.mock import patch - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture -def client(): - from docs_src.body.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_body_float(client: TestClient): - response = client.post("/items/", json={"name": "Foo", "price": 50.5}) - assert response.status_code == 200 - assert response.json() == { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - } - - -@needs_py310 -def test_post_with_str_float(client: TestClient): - response = client.post("/items/", json={"name": "Foo", "price": "50.5"}) - assert response.status_code == 200 - assert response.json() == { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - } - - -@needs_py310 -def test_post_with_str_float_description(client: TestClient): - response = client.post( - "/items/", json={"name": "Foo", "price": "50.5", "description": "Some Foo"} - ) - assert response.status_code == 200 - assert response.json() == { - "name": "Foo", - "price": 50.5, - "description": "Some Foo", - "tax": None, - } - - -@needs_py310 -def test_post_with_str_float_description_tax(client: TestClient): - response = client.post( - "/items/", - json={"name": "Foo", "price": "50.5", "description": "Some Foo", "tax": 0.3}, - ) - assert response.status_code == 200 - assert response.json() == { - "name": "Foo", - "price": 50.5, - "description": "Some Foo", - "tax": 0.3, - } - - -@needs_py310 -def test_post_with_only_name(client: TestClient): - response = client.post("/items/", json={"name": "Foo"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "price"], - "msg": "Field required", - "input": {"name": "Foo"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "price"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py310 -def test_post_with_only_name_price(client: TestClient): - response = client.post("/items/", json={"name": "Foo", "price": "twenty"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "float_parsing", - "loc": ["body", "price"], - "msg": "Input should be a valid number, unable to parse string as a number", - "input": "twenty", - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "price"], - "msg": "value is not a valid float", - "type": "type_error.float", - } - ] - } - ) - - -@needs_py310 -def test_post_with_no_data(client: TestClient): - response = client.post("/items/", json={}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "name"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "price"], - "msg": "Field required", - "input": {}, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "name"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "price"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py310 -def test_post_with_none(client: TestClient): - response = client.post("/items/", json=None) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py310 -def test_post_broken_body(client: TestClient): - response = client.post( - "/items/", - headers={"content-type": "application/json"}, - content="{some broken json}", - ) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "json_invalid", - "loc": ["body", 1], - "msg": "JSON decode error", - "input": {}, - "ctx": { - "error": "Expecting property name enclosed in double quotes" - }, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", 1], - "msg": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)", - "type": "value_error.jsondecode", - "ctx": { - "msg": "Expecting property name enclosed in double quotes", - "doc": "{some broken json}", - "pos": 1, - "lineno": 1, - "colno": 2, - }, - } - ] - } - ) - - -@needs_py310 -def test_post_form_for_json(client: TestClient): - response = client.post("/items/", data={"name": "Foo", "price": 50.5}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "model_attributes_type", - "loc": ["body"], - "msg": "Input should be a valid dictionary or object to extract fields from", - "input": "name=Foo&price=50.5", - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body"], - "msg": "value is not a valid dict", - "type": "type_error.dict", - } - ] - } - ) - - -@needs_py310 -def test_explicit_content_type(client: TestClient): - response = client.post( - "/items/", - content='{"name": "Foo", "price": 50.5}', - headers={"Content-Type": "application/json"}, - ) - assert response.status_code == 200, response.text - - -@needs_py310 -def test_geo_json(client: TestClient): - response = client.post( - "/items/", - content='{"name": "Foo", "price": 50.5}', - headers={"Content-Type": "application/geo+json"}, - ) - assert response.status_code == 200, response.text - - -@needs_py310 -def test_no_content_type_is_json(client: TestClient): - response = client.post( - "/items/", - content='{"name": "Foo", "price": 50.5}', - ) - assert response.status_code == 200, response.text - assert response.json() == { - "name": "Foo", - "description": None, - "price": 50.5, - "tax": None, - } - - -@needs_py310 -def test_wrong_headers(client: TestClient): - data = '{"name": "Foo", "price": 50.5}' - response = client.post( - "/items/", content=data, headers={"Content-Type": "text/plain"} - ) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "model_attributes_type", - "loc": ["body"], - "msg": "Input should be a valid dictionary or object to extract fields from", - "input": '{"name": "Foo", "price": 50.5}', - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body"], - "msg": "value is not a valid dict", - "type": "type_error.dict", - } - ] - } - ) - - response = client.post( - "/items/", content=data, headers={"Content-Type": "application/geo+json-seq"} - ) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "model_attributes_type", - "loc": ["body"], - "msg": "Input should be a valid dictionary or object to extract fields from", - "input": '{"name": "Foo", "price": 50.5}', - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body"], - "msg": "value is not a valid dict", - "type": "type_error.dict", - } - ] - } - ) - response = client.post( - "/items/", content=data, headers={"Content-Type": "application/not-really-json"} - ) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "model_attributes_type", - "loc": ["body"], - "msg": "Input should be a valid dictionary or object to extract fields from", - "input": '{"name": "Foo", "price": 50.5}', - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body"], - "msg": "value is not a valid dict", - "type": "type_error.dict", - } - ] - } - ) - - -@needs_py310 -def test_other_exceptions(client: TestClient): - with patch("json.loads", side_effect=Exception): - response = client.post("/items/", json={"test": "test2"}) - assert response.status_code == 400, response.text - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "price": {"title": "Price", "type": "number"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } From fe4b25e2d7c01925fc1b9bd4504b99452f436139 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 8 Jan 2025 19:26:39 +0000 Subject: [PATCH 649/932] =?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 [skip ci] --- 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 559ddc5d7..4897b4022 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for body. PR [#13168](https://github.com/fastapi/fastapi/pull/13168) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for bigger_applications. PR [#13167](https://github.com/fastapi/fastapi/pull/13167) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for background_tasks. PR [#13166](https://github.com/fastapi/fastapi/pull/13166) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for additional_status_codes. PR [#13149](https://github.com/fastapi/fastapi/pull/13149) by [@tiangolo](https://github.com/tiangolo). From 9b88c7c18a0019a729945b3d5c7e1bf6f0b1e139 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Wed, 8 Jan 2025 19:28:44 +0000 Subject: [PATCH 650/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20bo?= =?UTF-8?q?dy=5Ffields=20(#13169)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_body_fields/test_tutorial001.py | 21 +- .../test_body_fields/test_tutorial001_an.py | 203 ----------------- .../test_tutorial001_an_py310.py | 209 ------------------ .../test_tutorial001_an_py39.py | 209 ------------------ .../test_tutorial001_py310.py | 209 ------------------ 5 files changed, 17 insertions(+), 834 deletions(-) delete mode 100644 tests/test_tutorial/test_body_fields/test_tutorial001_an.py delete mode 100644 tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py delete mode 100644 tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py delete mode 100644 tests/test_tutorial/test_body_fields/test_tutorial001_py310.py diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001.py b/tests/test_tutorial/test_body_fields/test_tutorial001.py index fd6139eb9..fb68f2868 100644 --- a/tests/test_tutorial/test_body_fields/test_tutorial001.py +++ b/tests/test_tutorial/test_body_fields/test_tutorial001.py @@ -1,13 +1,26 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient +from ...utils import needs_py39, needs_py310 + -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_fields.tutorial001 import app +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.body_fields.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_an.py b/tests/test_tutorial/test_body_fields/test_tutorial001_an.py deleted file mode 100644 index 72c18c1f7..000000000 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_an.py +++ /dev/null @@ -1,203 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_fields.tutorial001_an import app - - client = TestClient(app) - return client - - -def test_items_5(client: TestClient): - response = client.put("/items/5", json={"item": {"name": "Foo", "price": 3.0}}) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "item": {"name": "Foo", "price": 3.0, "description": None, "tax": None}, - } - - -def test_items_6(client: TestClient): - response = client.put( - "/items/6", - json={ - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": "5.4", - } - }, - ) - assert response.status_code == 200 - assert response.json() == { - "item_id": 6, - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": 5.4, - }, - } - - -def test_invalid_price(client: TestClient): - response = client.put("/items/5", json={"item": {"name": "Foo", "price": -3.0}}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "greater_than", - "loc": ["body", "item", "price"], - "msg": "Input should be greater than 0", - "input": -3.0, - "ctx": {"gt": 0.0}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"limit_value": 0}, - "loc": ["body", "item", "price"], - "msg": "ensure this value is greater than 0", - "type": "value_error.number.not_gt", - } - ] - } - ) - - -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_update_item_items__item_id__put" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "The description of the item", - "anyOf": [ - {"maxLength": 300, "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "The description of the item", - "maxLength": 300, - "type": "string", - } - ), - "price": { - "title": "Price", - "exclusiveMinimum": 0.0, - "type": "number", - "description": "The price must be greater than zero", - }, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "Body_update_item_items__item_id__put": { - "title": "Body_update_item_items__item_id__put", - "required": ["item"], - "type": "object", - "properties": {"item": {"$ref": "#/components/schemas/Item"}}, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py deleted file mode 100644 index 1bc62868f..000000000 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py +++ /dev/null @@ -1,209 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_fields.tutorial001_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_items_5(client: TestClient): - response = client.put("/items/5", json={"item": {"name": "Foo", "price": 3.0}}) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "item": {"name": "Foo", "price": 3.0, "description": None, "tax": None}, - } - - -@needs_py310 -def test_items_6(client: TestClient): - response = client.put( - "/items/6", - json={ - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": "5.4", - } - }, - ) - assert response.status_code == 200 - assert response.json() == { - "item_id": 6, - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": 5.4, - }, - } - - -@needs_py310 -def test_invalid_price(client: TestClient): - response = client.put("/items/5", json={"item": {"name": "Foo", "price": -3.0}}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "greater_than", - "loc": ["body", "item", "price"], - "msg": "Input should be greater than 0", - "input": -3.0, - "ctx": {"gt": 0.0}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"limit_value": 0}, - "loc": ["body", "item", "price"], - "msg": "ensure this value is greater than 0", - "type": "value_error.number.not_gt", - } - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_update_item_items__item_id__put" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "The description of the item", - "anyOf": [ - {"maxLength": 300, "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "The description of the item", - "maxLength": 300, - "type": "string", - } - ), - "price": { - "title": "Price", - "exclusiveMinimum": 0.0, - "type": "number", - "description": "The price must be greater than zero", - }, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "Body_update_item_items__item_id__put": { - "title": "Body_update_item_items__item_id__put", - "required": ["item"], - "type": "object", - "properties": {"item": {"$ref": "#/components/schemas/Item"}}, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py deleted file mode 100644 index 3c5557a1b..000000000 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py +++ /dev/null @@ -1,209 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_fields.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_items_5(client: TestClient): - response = client.put("/items/5", json={"item": {"name": "Foo", "price": 3.0}}) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "item": {"name": "Foo", "price": 3.0, "description": None, "tax": None}, - } - - -@needs_py39 -def test_items_6(client: TestClient): - response = client.put( - "/items/6", - json={ - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": "5.4", - } - }, - ) - assert response.status_code == 200 - assert response.json() == { - "item_id": 6, - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": 5.4, - }, - } - - -@needs_py39 -def test_invalid_price(client: TestClient): - response = client.put("/items/5", json={"item": {"name": "Foo", "price": -3.0}}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "greater_than", - "loc": ["body", "item", "price"], - "msg": "Input should be greater than 0", - "input": -3.0, - "ctx": {"gt": 0.0}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"limit_value": 0}, - "loc": ["body", "item", "price"], - "msg": "ensure this value is greater than 0", - "type": "value_error.number.not_gt", - } - ] - } - ) - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_update_item_items__item_id__put" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "The description of the item", - "anyOf": [ - {"maxLength": 300, "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "The description of the item", - "maxLength": 300, - "type": "string", - } - ), - "price": { - "title": "Price", - "exclusiveMinimum": 0.0, - "type": "number", - "description": "The price must be greater than zero", - }, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "Body_update_item_items__item_id__put": { - "title": "Body_update_item_items__item_id__put", - "required": ["item"], - "type": "object", - "properties": {"item": {"$ref": "#/components/schemas/Item"}}, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py b/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py deleted file mode 100644 index 8c1386aa6..000000000 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py +++ /dev/null @@ -1,209 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_fields.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_items_5(client: TestClient): - response = client.put("/items/5", json={"item": {"name": "Foo", "price": 3.0}}) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "item": {"name": "Foo", "price": 3.0, "description": None, "tax": None}, - } - - -@needs_py310 -def test_items_6(client: TestClient): - response = client.put( - "/items/6", - json={ - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": "5.4", - } - }, - ) - assert response.status_code == 200 - assert response.json() == { - "item_id": 6, - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": 5.4, - }, - } - - -@needs_py310 -def test_invalid_price(client: TestClient): - response = client.put("/items/5", json={"item": {"name": "Foo", "price": -3.0}}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "greater_than", - "loc": ["body", "item", "price"], - "msg": "Input should be greater than 0", - "input": -3.0, - "ctx": {"gt": 0.0}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"limit_value": 0}, - "loc": ["body", "item", "price"], - "msg": "ensure this value is greater than 0", - "type": "value_error.number.not_gt", - } - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_update_item_items__item_id__put" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "The description of the item", - "anyOf": [ - {"maxLength": 300, "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "The description of the item", - "maxLength": 300, - "type": "string", - } - ), - "price": { - "title": "Price", - "exclusiveMinimum": 0.0, - "type": "number", - "description": "The price must be greater than zero", - }, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "Body_update_item_items__item_id__put": { - "title": "Body_update_item_items__item_id__put", - "required": ["item"], - "type": "object", - "properties": {"item": {"$ref": "#/components/schemas/Item"}}, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } From 3d2ef237edf99cff95e68ff9245f8b823d322a69 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 8 Jan 2025 19:29:11 +0000 Subject: [PATCH 651/932] =?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 [skip ci] --- 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 4897b4022..3245bd8c4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for body_fields. PR [#13169](https://github.com/fastapi/fastapi/pull/13169) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for body. PR [#13168](https://github.com/fastapi/fastapi/pull/13168) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for bigger_applications. PR [#13167](https://github.com/fastapi/fastapi/pull/13167) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for background_tasks. PR [#13166](https://github.com/fastapi/fastapi/pull/13166) by [@alejsdev](https://github.com/alejsdev). From 9d293b7086064e2e20b2fff0c3c472eba79137bd Mon Sep 17 00:00:00 2001 From: nillvitor <32855855+nillvitor@users.noreply.github.com> Date: Thu, 9 Jan 2025 17:41:07 -0300 Subject: [PATCH 652/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Portuguese=20tr?= =?UTF-8?q?anslations=20(#13156)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/deployment/manually.md | 66 +++++++---------- docs/pt/docs/deployment/server-workers.md | 87 ++++++++++------------- docs/pt/docs/tutorial/first-steps.md | 72 ++++++++----------- docs/pt/docs/tutorial/index.md | 62 +++++++++------- 4 files changed, 130 insertions(+), 157 deletions(-) diff --git a/docs/pt/docs/deployment/manually.md b/docs/pt/docs/deployment/manually.md index 237f4f8b9..46e580807 100644 --- a/docs/pt/docs/deployment/manually.md +++ b/docs/pt/docs/deployment/manually.md @@ -7,45 +7,33 @@ Em resumo, utilize o comando `fastapi run` para inicializar sua aplicação Fast
    ```console -$ fastapi run main.py -INFO Using path main.py -INFO Resolved absolute path /home/user/code/awesomeapp/main.py -INFO Searching for package file structure from directories with __init__.py files -INFO Importing from /home/user/code/awesomeapp - - ╭─ Python module file ─╮ - │ │ - │ 🐍 main.py │ - │ │ - ╰──────────────────────╯ - -INFO Importing module main -INFO Found importable FastAPI app - - ╭─ Importable FastAPI app ─╮ - │ │ - │ from main import app │ - │ │ - ╰──────────────────────────╯ - -INFO Using import string main:app - - ╭─────────── FastAPI CLI - Production mode ───────────╮ - │ │ - │ Serving at: http://0.0.0.0:8000 │ - │ │ - │ API docs: http://0.0.0.0:8000/docs │ - │ │ - │ Running in production mode, for development use: │ - │ │ - fastapi dev - │ │ - ╰─────────────────────────────────────────────────────╯ - -INFO: Started server process [2306215] -INFO: Waiting for application startup. -INFO: Application startup complete. -INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) +$ fastapi run main.py + + FastAPI Starting production server 🚀 + + Searching for package file structure from directories + with __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with + the following code: + + from main import app + + app Using import string: main:app + + server Server started at http://0.0.0.0:8000 + server Documentation at http://0.0.0.0:8000/docs + + Logs: + + INFO Started server process [2306215] + INFO Waiting for application startup. + INFO Application startup complete. + INFO Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C + to quit) ```
    diff --git a/docs/pt/docs/deployment/server-workers.md b/docs/pt/docs/deployment/server-workers.md index 63eda56b4..a0db1bea4 100644 --- a/docs/pt/docs/deployment/server-workers.md +++ b/docs/pt/docs/deployment/server-workers.md @@ -36,56 +36,43 @@ Se você usar o comando `fastapi`:
    ```console -$
     fastapi run --workers 4 main.py
    -INFO     Using path main.py
    -INFO     Resolved absolute path /home/user/code/awesomeapp/main.py
    -INFO     Searching for package file structure from directories with __init__.py files
    -INFO     Importing from /home/user/code/awesomeapp
    -
    - ╭─ Python module file ─╮
    - │                      │
    - │  🐍 main.py          │
    - │                      │
    - ╰──────────────────────╯
    -
    -INFO     Importing module main
    -INFO     Found importable FastAPI app
    -
    - ╭─ Importable FastAPI app ─╮
    - │                          │
    - │  from main import app    │
    - │                          │
    - ╰──────────────────────────╯
    -
    -INFO     Using import string main:app
    -
    - ╭─────────── FastAPI CLI - Production mode ───────────╮
    - │                                                     │
    - │  Serving at: http://0.0.0.0:8000                    │
    - │                                                     │
    - │  API docs: http://0.0.0.0:8000/docs                 │
    - │                                                     │
    - │  Running in production mode, for development use:   │
    - │                                                     │
    - fastapi dev
    - │                                                     │
    - ╰─────────────────────────────────────────────────────╯
    -
    -INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
    -INFO:     Started parent process [27365]
    -INFO:     Started server process [27368]
    -INFO:     Waiting for application startup.
    -INFO:     Application startup complete.
    -INFO:     Started server process [27369]
    -INFO:     Waiting for application startup.
    -INFO:     Application startup complete.
    -INFO:     Started server process [27370]
    -INFO:     Waiting for application startup.
    -INFO:     Application startup complete.
    -INFO:     Started server process [27367]
    -INFO:     Waiting for application startup.
    -INFO:     Application startup complete.
    -
    +$ fastapi run --workers 4 main.py + + FastAPI Starting production server 🚀 + + Searching for package file structure from directories with + __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with the + following code: + + from main import app + + app Using import string: main:app + + server Server started at http://0.0.0.0:8000 + server Documentation at http://0.0.0.0:8000/docs + + Logs: + + INFO Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to + quit) + INFO Started parent process [27365] + INFO Started server process [27368] + INFO Started server process [27369] + INFO Started server process [27370] + INFO Started server process [27367] + INFO Waiting for application startup. + INFO Waiting for application startup. + INFO Waiting for application startup. + INFO Waiting for application startup. + INFO Application startup complete. + INFO Application startup complete. + INFO Application startup complete. + INFO Application startup complete. ```
    diff --git a/docs/pt/docs/tutorial/first-steps.md b/docs/pt/docs/tutorial/first-steps.md index 523b8f05c..5184d2d5f 100644 --- a/docs/pt/docs/tutorial/first-steps.md +++ b/docs/pt/docs/tutorial/first-steps.md @@ -11,26 +11,42 @@ Execute o servidor:
    ```console -$ uvicorn main:app --reload +$ fastapi dev main.py -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] -INFO: Waiting for application startup. -INFO: Application startup complete. -``` + FastAPI Starting development server 🚀 -
    + Searching for package file structure from directories + with __init__.py files + Importing from /home/user/code/awesomeapp -/// note | Nota + module 🐍 main.py -O comando `uvicorn main:app` se refere a: + code Importing the FastAPI app object from the module with + the following code: -* `main`: o arquivo `main.py` (o "módulo" Python). -* `app`: o objeto criado no arquivo `main.py` com a linha `app = FastAPI()`. -* `--reload`: faz o servidor reiniciar após mudanças de código. Use apenas para desenvolvimento. + from main import app -/// + app Using import string: main:app + + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: + + 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 [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. +``` + +
    Na saída, temos: @@ -151,34 +167,6 @@ Aqui, a variável `app` será uma "instância" da classe `FastAPI`. Este será o principal ponto de interação para criar toda a sua API. -Este `app` é o mesmo referenciado por `uvicorn` no comando: - -
    - -```console -$ uvicorn main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
    - -Se você criar a sua aplicação como: - -{* ../../docs_src/first_steps/tutorial002.py hl[3] *} - -E colocar em um arquivo `main.py`, você iria chamar o `uvicorn` assim: - -
    - -```console -$ uvicorn main:my_awesome_api --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
    - ### Passo 3: crie uma *rota* #### Rota diff --git a/docs/pt/docs/tutorial/index.md b/docs/pt/docs/tutorial/index.md index 4e6293bb0..7c04b17f2 100644 --- a/docs/pt/docs/tutorial/index.md +++ b/docs/pt/docs/tutorial/index.md @@ -4,9 +4,7 @@ Esse tutorial mostra como usar o **FastAPI** com a maior parte de seus recursos, Cada seção constrói, gradualmente, sobre as anteriores, mas sua estrutura são tópicos separados, para que você possa ir a qualquer um específico e resolver suas necessidades específicas de API. -Ele também foi feito como referência futura. - -Então você poderá voltar e ver exatamente o que precisar. +Ele também foi construído para servir como uma referência futura, então você pode voltar e ver exatamente o que você precisa. ## Rode o código @@ -17,13 +15,39 @@ Para rodar qualquer um dos exemplos, copie o codigo para um arquivo `main.py`, e
    ```console -$ uvicorn main:app --reload +$ fastapi dev main.py + + FastAPI Starting development server 🚀 + + Searching for package file structure from directories + with __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with + the following code: + + from main import app + + app Using import string: main:app + + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] -INFO: Waiting for application startup. -INFO: Application startup complete. + 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 [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. ```
    @@ -43,32 +67,18 @@ Para o tutorial, você deve querer instalá-lo com todas as dependências e recu
    ```console -$ pip install "fastapi[all]" +$ pip install "fastapi[standard]" ---> 100% ```
    -...isso também inclui o `uvicorn`, que você pode usar como o servidor que rodará seu código. - /// note | Nota -Você também pode instalar parte por parte. - -Isso é provavelmente o que você faria quando você quisesse lançar sua aplicação em produção: - -``` -pip install fastapi -``` - -Também instale o `uvicorn` para funcionar como servidor: - -``` -pip install "uvicorn[standard]" -``` +Quando você instala com pip install "fastapi[standard]", ele vem com algumas dependências opcionais padrão. -E o mesmo para cada dependência opcional que você quiser usar. +Se você não quiser ter essas dependências opcionais, pode instalar pip install fastapi em vez disso. /// From 837e94573db9a56b9de4ef004fb96eedf031421e Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 9 Jan 2025 20:41:29 +0000 Subject: [PATCH 653/932] =?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 [skip ci] --- 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 3245bd8c4..f1e033da3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 🌐 Update Portuguese translations. PR [#13156](https://github.com/fastapi/fastapi/pull/13156) by [@nillvitor](https://github.com/nillvitor). * 🌐 Update Russian translation for `docs/ru/docs/tutorial/security/first-steps.md`. PR [#13159](https://github.com/fastapi/fastapi/pull/13159) by [@Yarous](https://github.com/Yarous). * ✏️ Delete unnecessary backspace in `docs/ja/docs/tutorial/path-params-numeric-validations.md`. PR [#12238](https://github.com/fastapi/fastapi/pull/12238) by [@FakeDocument](https://github.com/FakeDocument). * 🌐 Update Chinese translation for `docs/zh/docs/fastapi-cli.md`. PR [#13102](https://github.com/fastapi/fastapi/pull/13102) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). From e54cc8ffa3e0d1d3f55515887f89b45df7d60258 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Fri, 10 Jan 2025 10:32:37 -0300 Subject: [PATCH 654/932] =?UTF-8?q?=F0=9F=8C=90=20Remove=20Wrong=20Portugu?= =?UTF-8?q?ese=20translations=20location=20for=20`docs/pt/docs/advanced/be?= =?UTF-8?q?nchmarks.md`=20(#13187)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/benchmarks.md | 34 ----------------------------- 1 file changed, 34 deletions(-) delete mode 100644 docs/pt/docs/advanced/benchmarks.md diff --git a/docs/pt/docs/advanced/benchmarks.md b/docs/pt/docs/advanced/benchmarks.md deleted file mode 100644 index 72ef1e444..000000000 --- a/docs/pt/docs/advanced/benchmarks.md +++ /dev/null @@ -1,34 +0,0 @@ -# Benchmarks - -Benchmarks independentes da TechEmpower mostram que aplicações **FastAPI** rodando com o Uvicorn como um dos frameworks Python mais rápidos disponíveis, ficando atrás apenas do Starlette e Uvicorn (utilizado internamente pelo FastAPI). - -Porém, ao verificar benchmarks e comparações você deve prestar atenção ao seguinte: - -## Benchmarks e velocidade - -Quando você verifica os benchmarks, é comum ver diversas ferramentas de diferentes tipos comparados como se fossem equivalentes. - -Especificamente, para ver o Uvicorn, Starlette e FastAPI comparados entre si (entre diversas outras ferramentas). - -Quanto mais simples o problema resolvido pela ferramenta, melhor será a performance. E a maioria das análises não testa funcionalidades adicionais que são oferecidas pela ferramenta. - -A hierarquia é: - -* **Uvicorn**: um servidor ASGI - * **Starlette**: (utiliza Uvicorn) um microframework web - * **FastAPI**: (utiliza Starlette) um microframework para APIs com diversas funcionalidades adicionais para a construção de APIs, com validação de dados, etc. - -* **Uvicorn**: - * Terá a melhor performance, pois não possui muito código além do próprio servidor. - * Você não escreveria uma aplicação utilizando o Uvicorn diretamente. Isso significaria que o seu código teria que incluir pelo menos todo o código fornecido pelo Starlette (ou o **FastAPI**). E caso você fizesse isso, a sua aplicação final teria a mesma sobrecarga que teria se utilizasse um framework, minimizando o código e os bugs. - * Se você está comparando o Uvicorn, compare com os servidores de aplicação Daphne, Hypercorn, uWSGI, etc. -* **Starlette**: - * Terá o melhor desempenho, depois do Uvicorn. Na verdade, o Starlette utiliza o Uvicorn para rodar. Portanto, ele pode ficar mais "devagar" que o Uvicorn apenas por ter que executar mais código. - * Mas ele fornece as ferramentas para construir aplicações web simples, com roteamento baseado em caminhos, etc. - * Se você está comparando o Starlette, compare-o com o Sanic, Flask, Django, etc. Frameworks web (ou microframeworks). -* **FastAPI**: - * Da mesma forma que o Starlette utiliza o Uvicorn e não consegue ser mais rápido que ele, o **FastAPI** utiliza o Starlette, portanto, ele não consegue ser mais rápido que ele. - * O FastAPI provê mais funcionalidades em cima do Starlette. Funcionalidades que você quase sempre precisará quando estiver construindo APIs, como validação de dados e serialização. E ao utilizá-lo, você obtém documentação automática sem custo nenhum (a documentação automática sequer adiciona sobrecarga nas aplicações rodando, pois ela é gerada na inicialização). - * Caso você não utilize o FastAPI e faz uso do Starlette diretamente (ou outra ferramenta, como o Sanic, Flask, Responder, etc) você mesmo teria que implementar toda a validação de dados e serialização. Então, a sua aplicação final ainda teria a mesma sobrecarga caso estivesse usando o FastAPI. E em muitos casos, validação de dados e serialização é a maior parte do código escrito em aplicações. - * Então, ao utilizar o FastAPI, você está economizando tempo de programação, evitando bugs, linhas de código, e provavelmente terá a mesma performance (ou até melhor) do que teria caso você não o utilizasse (já que você teria que implementar tudo no seu código). - * Se você está comparando o FastAPI, compare-o com frameworks de aplicações web (ou conjunto de ferramentas) que oferecem validação de dados, serialização e documentação, como por exemplo o Flask-apispec, NestJS, Molten, etc. Frameworks que possuem validação integrada de dados, serialização e documentação. From f36927d0a63c5be349e68862c98759d006d515aa Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 10 Jan 2025 13:33:14 +0000 Subject: [PATCH 655/932] =?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 [skip ci] --- 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 f1e033da3..489849903 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 🌐 Remove Wrong Portuguese translations location for `docs/pt/docs/advanced/benchmarks.md`. PR [#13187](https://github.com/fastapi/fastapi/pull/13187) by [@ceb10n](https://github.com/ceb10n). * 🌐 Update Portuguese translations. PR [#13156](https://github.com/fastapi/fastapi/pull/13156) by [@nillvitor](https://github.com/nillvitor). * 🌐 Update Russian translation for `docs/ru/docs/tutorial/security/first-steps.md`. PR [#13159](https://github.com/fastapi/fastapi/pull/13159) by [@Yarous](https://github.com/Yarous). * ✏️ Delete unnecessary backspace in `docs/ja/docs/tutorial/path-params-numeric-validations.md`. PR [#12238](https://github.com/fastapi/fastapi/pull/12238) by [@FakeDocument](https://github.com/FakeDocument). From e69182940ea3205886656d9ebd2061cca2132fba Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Fri, 10 Jan 2025 10:33:35 -0300 Subject: [PATCH 656/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/security/get-current-user?= =?UTF-8?q?.md`=20(#13188)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tutorial/security/get-current-user.md | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 docs/pt/docs/tutorial/security/get-current-user.md diff --git a/docs/pt/docs/tutorial/security/get-current-user.md b/docs/pt/docs/tutorial/security/get-current-user.md new file mode 100644 index 000000000..1a2badb83 --- /dev/null +++ b/docs/pt/docs/tutorial/security/get-current-user.md @@ -0,0 +1,105 @@ +# Obter Usuário Atual + +No capítulo anterior, o sistema de segurança (que é baseado no sistema de injeção de dependências) estava fornecendo à *função de operação de rota* um `token` como uma `str`: + +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} + +Mas isso ainda não é tão útil. + +Vamos fazer com que ele nos forneça o usuário atual. + +## Criar um modelo de usuário + +Primeiro, vamos criar um modelo de usuário com Pydantic. + +Da mesma forma que usamos o Pydantic para declarar corpos, podemos usá-lo em qualquer outro lugar: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *} + +## Criar uma dependência `get_current_user` + +Vamos criar uma dependência chamada `get_current_user`. + +Lembra que as dependências podem ter subdependências? + +`get_current_user` terá uma dependência com o mesmo `oauth2_scheme` que criamos antes. + +Da mesma forma que estávamos fazendo antes diretamente na *operação de rota*, a nossa nova dependência `get_current_user` receberá um `token` como uma `str` da subdependência `oauth2_scheme`: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *} + +## Obter o usuário + +`get_current_user` usará uma função utilitária (falsa) que criamos, que recebe um token como uma `str` e retorna nosso modelo Pydantic `User`: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *} + +## Injetar o usuário atual + +Então agora nós podemos usar o mesmo `Depends` com nosso `get_current_user` na *operação de rota*: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *} + +Observe que nós declaramos o tipo de `current_user` como o modelo Pydantic `User`. + +Isso nos ajudará dentro da função com todo o preenchimento automático e verificações de tipo. + +/// tip | Dica + +Você pode se lembrar que corpos de requisição também são declarados com modelos Pydantic. + +Aqui, o **FastAPI** não ficará confuso porque você está usando `Depends`. + +/// + +/// check | Verifique + +A forma como esse sistema de dependências foi projetado nos permite ter diferentes dependências (diferentes "dependables") que retornam um modelo `User`. + +Não estamos restritos a ter apenas uma dependência que possa retornar esse tipo de dado. + +/// + +## Outros modelos + +Agora você pode obter o usuário atual diretamente nas *funções de operação de rota* e lidar com os mecanismos de segurança no nível da **Injeção de Dependências**, usando `Depends`. + +E você pode usar qualquer modelo ou dado para os requisitos de segurança (neste caso, um modelo Pydantic `User`). + +Mas você não está restrito a usar um modelo de dados, classe ou tipo específico. + +Você quer ter apenas um `id` e `email`, sem incluir nenhum `username` no modelo? Claro. Você pode usar essas mesmas ferramentas. + +Você quer ter apenas uma `str`? Ou apenas um `dict`? Ou uma instância de modelo de classe de banco de dados diretamente? Tudo funciona da mesma forma. + +Na verdade, você não tem usuários que fazem login no seu aplicativo, mas sim robôs, bots ou outros sistemas, que possuem apenas um token de acesso? Novamente, tudo funciona da mesma forma. + +Apenas use qualquer tipo de modelo, qualquer tipo de classe, qualquer tipo de banco de dados que você precise para a sua aplicação. O **FastAPI** cobre tudo com o sistema de injeção de dependências. + +## Tamanho do código + +Este exemplo pode parecer verboso. Lembre-se de que estamos misturando segurança, modelos de dados, funções utilitárias e *operações de rota* no mesmo arquivo. + +Mas aqui está o ponto principal. + +O código relacionado à segurança e à injeção de dependências é escrito apenas uma vez. + +E você pode torná-lo tão complexo quanto quiser. E ainda assim, tê-lo escrito apenas uma vez, em um único lugar. Com toda a flexibilidade. + +Mas você pode ter milhares de endpoints (*operações de rota*) usando o mesmo sistema de segurança. + +E todos eles (ou qualquer parte deles que você desejar) podem aproveitar o reuso dessas dependências ou de quaisquer outras dependências que você criar. + +E todos esses milhares de *operações de rota* podem ter apenas 3 linhas: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *} + +## Recapitulação + +Agora você pode obter o usuário atual diretamente na sua *função de operação de rota*. + +Já estamos na metade do caminho. + +Só precisamos adicionar uma *operação de rota* para que o usuário/cliente realmente envie o `username` e `password`. + +Isso vem a seguir. From 62be4a1600b29d3bcf717fa0b14a55ab1d5b7e57 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 10 Jan 2025 13:33:58 +0000 Subject: [PATCH 657/932] =?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 [skip ci] --- 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 489849903..9bd4dbf72 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/get-current-user.md`. PR [#13188](https://github.com/fastapi/fastapi/pull/13188) by [@ceb10n](https://github.com/ceb10n). * 🌐 Remove Wrong Portuguese translations location for `docs/pt/docs/advanced/benchmarks.md`. PR [#13187](https://github.com/fastapi/fastapi/pull/13187) by [@ceb10n](https://github.com/ceb10n). * 🌐 Update Portuguese translations. PR [#13156](https://github.com/fastapi/fastapi/pull/13156) by [@nillvitor](https://github.com/nillvitor). * 🌐 Update Russian translation for `docs/ru/docs/tutorial/security/first-steps.md`. PR [#13159](https://github.com/fastapi/fastapi/pull/13159) by [@Yarous](https://github.com/Yarous). From cda85623fbd58b10c7670557094588eaebef34d8 Mon Sep 17 00:00:00 2001 From: Guspan Tanadi <36249910+guspan-tanadi@users.noreply.github.com> Date: Sat, 11 Jan 2025 03:31:13 +0700 Subject: [PATCH 658/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Indonesian=20trans?= =?UTF-8?q?lation=20for=20`docs/id/docs/tutorial/static-files.md`=20(#1309?= =?UTF-8?q?2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/id/docs/tutorial/static-files.md | 40 +++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 docs/id/docs/tutorial/static-files.md diff --git a/docs/id/docs/tutorial/static-files.md b/docs/id/docs/tutorial/static-files.md new file mode 100644 index 000000000..b55f31394 --- /dev/null +++ b/docs/id/docs/tutorial/static-files.md @@ -0,0 +1,40 @@ +# Berkas Statis + +Anda dapat menyajikan berkas statis secara otomatis dari sebuah direktori menggunakan `StaticFiles`. + +## Penggunaan `StaticFiles` + +* Mengimpor `StaticFiles`. +* "Mount" representatif `StaticFiles()` di jalur spesifik. + +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} + +/// note | Detail Teknis + +Anda dapat pula menggunakan `from starlette.staticfiles import StaticFiles`. + +**FastAPI** menyediakan `starlette.staticfiles` sama seperti `fastapi.staticfiles` sebagai kemudahan pada Anda, yaitu para pengembang. Tetapi ini asli berasal langsung dari Starlette. + +/// + +### Apa itu "Mounting" + +"Mounting" dimaksud menambah aplikasi "independen" secara lengkap di jalur spesifik, kemudian menangani seluruh sub-jalur. + +Hal ini berbeda dari menggunakan `APIRouter` karena aplikasi yang dimount benar-benar independen. OpenAPI dan dokumentasi dari aplikasi utama Anda tak akan menyertakan apa pun dari aplikasi yang dimount, dst. + +Anda dapat mempelajari mengenai ini dalam [Panduan Pengguna Lanjutan](../advanced/index.md){.internal-link target=_blank}. + +## Detail + +Terhadap `"/static"` pertama mengacu pada sub-jalur yang akan menjadi tempat "sub-aplikasi" ini akan "dimount". Maka, jalur apa pun yang dimulai dengan `"/static"` akan ditangani oleh sub-jalur tersebut. + +Terhadap `directory="static"` mengacu pada nama direktori yang berisi berkas statis Anda. + +Terhadap `name="static"` ialah nama yang dapat digunakan secara internal oleh **FastAPI**. + +Seluruh parameter ini dapat berbeda dari sekadar "`static`", sesuaikan parameter dengan keperluan dan detail spesifik akan aplikasi Anda. + +## Info lanjutan + +Sebagai detail dan opsi tambahan lihat dokumentasi Starlette perihal Berkas Statis. From 09a0295bf3bd604eb0acd7eb1f9d9cd4852f3805 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 10 Jan 2025 20:31:39 +0000 Subject: [PATCH 659/932] =?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 [skip ci] --- 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 9bd4dbf72..3aabd1fc0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 🌐 Add Indonesian translation for `docs/id/docs/tutorial/static-files.md`. PR [#13092](https://github.com/fastapi/fastapi/pull/13092) by [@guspan-tanadi](https://github.com/guspan-tanadi). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/get-current-user.md`. PR [#13188](https://github.com/fastapi/fastapi/pull/13188) by [@ceb10n](https://github.com/ceb10n). * 🌐 Remove Wrong Portuguese translations location for `docs/pt/docs/advanced/benchmarks.md`. PR [#13187](https://github.com/fastapi/fastapi/pull/13187) by [@ceb10n](https://github.com/ceb10n). * 🌐 Update Portuguese translations. PR [#13156](https://github.com/fastapi/fastapi/pull/13156) by [@nillvitor](https://github.com/nillvitor). From 5d18ae0d902111bca76fabe6d136adafce2b4daf Mon Sep 17 00:00:00 2001 From: Gerry Sabar Date: Mon, 13 Jan 2025 20:36:23 +0700 Subject: [PATCH 660/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Indonesian=20trans?= =?UTF-8?q?lation=20for=20`docs/id/docs/index.md`=20(#13191)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/id/docs/index.md | 495 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 495 insertions(+) create mode 100644 docs/id/docs/index.md diff --git a/docs/id/docs/index.md b/docs/id/docs/index.md new file mode 100644 index 000000000..7fdd1cc7a --- /dev/null +++ b/docs/id/docs/index.md @@ -0,0 +1,495 @@ +# FastAPI + + + +

    + FastAPI +

    +

    + FastAPI, framework performa tinggi, mudah dipelajari, cepat untuk coding, siap untuk pengembangan +

    +

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

    + +--- + +**Dokumentasi**: https://fastapi.tiangolo.com + +**Kode Sumber**: https://github.com/fastapi/fastapi + +--- + +FastAPI adalah *framework* *web* moderen, cepat (performa-tinggi) untuk membangun API dengan Python berdasarkan tipe petunjuk Python. + +Fitur utama FastAPI: + +* **Cepat**: Performa sangat tinggi, setara **NodeJS** dan **Go** (berkat Starlette dan Pydantic). [Salah satu *framework* Python tercepat yang ada](#performa). +* **Cepat untuk coding**: Meningkatkan kecepatan pengembangan fitur dari 200% sampai 300%. * +* **Sedikit bug**: Mengurangi hingga 40% kesalahan dari manusia (pemrogram). * +* **Intuitif**: Dukungan editor hebat. Penyelesaian di mana pun. Lebih sedikit *debugging*. +* **Mudah**: Dibuat mudah digunakan dan dipelajari. Sedikit waktu membaca dokumentasi. +* **Ringkas**: Mengurasi duplikasi kode. Beragam fitur dari setiap deklarasi parameter. Lebih sedikit *bug*. +* **Handal**: Dapatkan kode siap-digunakan. Dengan dokumentasi otomatis interaktif. +* **Standar-resmi**: Berdasarkan (kompatibel dengan ) standar umum untuk API: OpenAPI (sebelumnya disebut Swagger) dan JSON Schema. + +* estimasi berdasarkan pengujian tim internal pengembangan applikasi siap pakai. + +## Sponsor + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +Sponsor lainnya + +## Opini + +"_[...] Saya banyak menggunakan **FastAPI** sekarang ini. [...] Saya berencana menggunakannya di semua tim servis ML Microsoft. Beberapa dari mereka sudah mengintegrasikan dengan produk inti *Windows** dan sebagian produk **Office**._" + +
    Kabir Khan - Microsoft (ref)
    + +--- + +"_Kami adopsi library **FastAPI** untuk membuat server **REST** yang melakukan kueri untuk menghasilkan **prediksi**. [untuk Ludwig]_" + +
    Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
    + +--- + +"_**Netflix** dengan bangga mengumumkan rilis open-source orkestrasi framework **manajemen krisis** : **Dispatch**! [dibuat dengan **FastAPI**]_" + +
    Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
    + +--- + +"_Saya sangat senang dengan **FastAPI**. Sangat menyenangkan!_" + +
    Brian Okken - Python Bytes podcast host (ref)
    + +--- + +"_Jujur, apa yang anda buat sangat solid dan berkualitas. Ini adalah yang saya inginkan di **Hug** - sangat menginspirasi melihat seseorang membuat ini._" + +
    Timothy Crosley - Hug creator (ref)
    + +--- + +"_Jika anda ingin mempelajari **framework moderen** untuk membangun REST API, coba **FastAPI** [...] cepat, mudah digunakan dan dipelajari [...]_" + +"_Kami sudah pindah ke **FastAPI** untuk **API** kami [...] Saya pikir kamu juga akan suka [...]_" + +
    Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
    + +--- +"_Jika anda ingin membuat API Python siap pakai, saya merekomendasikan **FastAPI**. FastAPI **didesain indah**, **mudah digunakan** dan **sangat scalable**, FastAPI adalah **komponen kunci** di strategi pengembangan API pertama kami dan mengatur banyak otomatisasi dan service seperti TAC Engineer kami._" + +
    Deon Pillsbury - Cisco (ref)
    + +--- + +## **Typer**, CLI FastAPI + + + +Jika anda mengembangkan app CLI yang digunakan di terminal bukan sebagai API web, kunjungi **Typer**. + +**Typer** adalah saudara kecil FastAPI. Dan ditujukan sebagai **CLI FastAPI**. ⌨️ 🚀 + +## Prayarat + +FastAPI berdiri di pundak raksasa: + +* Starlette untuk bagian web. +* Pydantic untuk bagian data. + +## Instalasi + +Buat dan aktifkan virtual environment kemudian *install* FastAPI: + +
    + +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
    + +**Catatan**: Pastikan anda menulis `"fastapi[standard]"` dengan tanda petik untuk memastikan bisa digunakan di semua *terminal*. + +## Contoh + +### Buat app + +* Buat file `main.py` dengan: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +
    +Atau gunakan async def... + +Jika kode anda menggunakan `async` / `await`, gunakan `async def`: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**Catatan**: + +Jika anda tidak paham, kunjungi _"Panduan cepat"_ bagian `async` dan `await` di dokumentasi. + +
    + +### Jalankan + +Jalankan *server* dengan: + +
    + +```console +$ fastapi dev main.py + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + │ fastapi run │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2248755] using WatchFiles +INFO: Started server process [2248757] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
    + +
    +Mengenai perintah fastapi dev main.py... + +Perintah `fastapi dev` membaca file `main.py`, memeriksa app **FastAPI** di dalamnya, dan menjalan server dengan Uvicorn. + +Secara otomatis, `fastapi dev` akan mengaktifkan *auto-reload* untuk pengembangan lokal. + +Informasi lebih lanjut kunjungi Dokumen FastAPI CLI. + +
    + +### Periksa + +Buka *browser* di http://127.0.0.1:8000/items/5?q=somequery. + +Anda akan melihat respon JSON berikut: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Anda telah membuat API: + +* Menerima permintaan HTTP di _path_ `/` dan `/items/{item_id}`. +* Kedua _paths_ menerima operasi `GET` (juga disebut _metode_ HTTP). +* _path_ `/items/{item_id}` memiliki _parameter path_ `item_id` yang harus berjenis `int`. +* _path_ `/items/{item_id}` memiliki _query parameter_ `q` berjenis `str`. + +### Dokumentasi API interaktif + +Sekarang kunjungi http://127.0.0.1:8000/docs. + +Anda akan melihat dokumentasi API interaktif otomatis (dibuat oleh Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Dokumentasi API alternatif + +Kemudian kunjungi http://127.0.0.1:8000/redoc. + +Anda akan melihat dokumentasi alternatif otomatis (dibuat oleh ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Contoh upgrade + +Sekarang ubah `main.py` untuk menerima struktur permintaan `PUT`. + +Deklarasikan struktur menggunakan tipe standar Python, berkat Pydantic. + +```Python hl_lines="4 9-12 25-27" +from typing import Union + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: Union[bool, None] = None + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} + + +@app.put("/items/{item_id}") +def update_item(item_id: int, item: Item): + return {"item_name": item.name, "item_id": item_id} +``` + +Server `fastapi dev` akan otomatis memuat kembali. + +### Upgrade dokumentasi API interaktif + +Kunjungi http://127.0.0.1:8000/docs. + +* Dokumentasi API interaktif akan otomatis diperbarui, termasuk kode yang baru: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Klik tombol "Try it out", anda dapat mengisi parameter dan langsung berinteraksi dengan API: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Kemudian klik tombol "Execute", tampilan pengguna akan berkomunikasi dengan API, mengirim parameter, mendapatkan dan menampilkan hasil ke layar: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Upgrade dokumentasi API alternatif + +Kunjungi http://127.0.0.1:8000/redoc. + +* Dokumentasi alternatif akan menampilkan parameter *query* dan struktur *request*: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Ringkasan + +Singkatnya, anda mendeklarasikan **sekali** jenis parameter, struktur, dll. sebagai parameter fungsi. + +Anda melakukannya dengan tipe standar moderen Python. + +Anda tidak perlu belajar sintaksis, metode, *classs* baru dari *library* tertentu, dll. + +Cukup **Python** standar. + +Sebagai contoh untuk `int`: + +```Python +item_id: int +``` + +atau untuk model lebih rumit `Item`: + +```Python +item: Item +``` + +...dengan sekali deklarasi anda mendapatkan: + +* Dukungan editor, termasuk: + * Pelengkapan kode. + * Pengecekan tipe. +* Validasi data: + * Kesalahan otomatis dan jelas ketika data tidak sesuai. + * Validasi hingga untuk object JSON bercabang mendalam. +* Konversi input data: berasal dari jaringan ke data dan tipe Python. Membaca dari: + * JSON. + * Parameter path. + * Parameter query. + * Cookie. + * Header. + * Form. + * File. +* Konversi output data: konversi data Python ke tipe jaringan data (seperti JSON): + * Konversi tipe Python (`str`, `int`, `float`, `bool`, `list`, dll). + * Objek `datetime`. + * Objek `UUID`. + * Model database. + * ...dan banyak lagi. +* Dokumentasi interaktif otomatis, termasuk 2 alternatif tampilan pengguna: + * Swagger UI. + * ReDoc. + +--- + +Kembali ke kode contoh sebelumnya, **FastAPI** akan: + +* Validasi apakah terdapat `item_id` di *path* untuk permintaan `GET` dan `PUT` requests. +* Validasi apakah `item_id` berjenit `int` untuk permintaan `GET` dan `PUT`. + * Jika tidak, klien akan melihat pesan kesalahan jelas. +* Periksa jika ada parameter *query* opsional bernama `q` (seperti `http://127.0.0.1:8000/items/foo?q=somequery`) untuk permintaan `GET`. + * Karena parameter `q` dideklarasikan dengan `= None`, maka bersifat opsional. + * Tanpa `None` maka akan menjadi wajib ada (seperti struktur di kondisi dengan `PUT`). +* Untuk permintaan `PUT` `/items/{item_id}`, membaca struktur sebagai JSON: + * Memeriksa terdapat atribut wajib `name` harus berjenis `str`. + * Memeriksa terdapat atribut wajib`price` harus berjenis `float`. + * Memeriksa atribut opsional `is_offer`, harus berjenis `bool`, jika ada. + * Semua ini juga sama untuk objek json yang bersarang mendalam. +* Konversi dari dan ke JSON secara otomatis. +* Dokumentasi segalanya dengan OpenAPI, dengan menggunakan: + * Sistem dokumentasi interaktif. + * Sistem otomatis penghasil kode, untuk banyak bahasa. +* Menyediakan 2 tampilan dokumentasi web interaktif dengan langsung. + +--- + +Kita baru menyentuh permukaannya saja, tetapi anda sudah mulai paham gambaran besar cara kerjanya. + +Coba ubah baris: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...dari: + +```Python + ... "item_name": item.name ... +``` + +...menjadi: + +```Python + ... "item_price": item.price ... +``` + +...anda akan melihat kode editor secara otomatis melengkapi atributnya dan tahu tipe nya: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Untuk contoh lengkap termasuk fitur lainnya, kunjungi Tutorial - Panduan Pengguna. + +**Peringatan spoiler**: tutorial - panduan pengguna termasuk: + +* Deklarasi **parameter** dari tempat berbeda seperti: **header**, **cookie**, **form field** and **file**. +* Bagaimana mengatur **batasan validasi** seperti `maximum_length`atau `regex`. +* Sistem **Dependency Injection** yang hebat dan mudah digunakan. +* Keamanan dan autentikasi, termasuk dukungan ke **OAuth2** dengan **JWT token** dan autentikasi **HTTP Basic**. +* Teknik lebih aju (tetapi mudah dipakai untuk deklarasi **model JSON bersarang ke dalam** (berkat Pydantic). +* Integrasi **GraphQL** dengan Strawberry dan library lainnya. +* Fitur lainnya (berkat Starlette) seperti: + * **WebSocket** + * Test yang sangat mudah berdasarkan HTTPX dan `pytest` + * **CORS** + * **Cookie Session** + * ...dan lainnya. + +## Performa + +Tolok ukur Independent TechEmpower mendapati aplikasi **FastAPI** berjalan menggunakan Uvicorn sebagai salah satu framework Python tercepat yang ada, hanya di bawah Starlette dan Uvicorn itu sendiri (digunakan di internal FastAPI). (*) + +Penjelasan lebih lanjut, lihat bagian Tolok ukur. + +## Dependensi + +FastAPI bergantung pada Pydantic dan Starlette. + +### Dependensi `standar` + +Ketika anda meng-*install* FastAPI dengan `pip install "fastapi[standard]"`, maka FastAPI akan menggunakan sekumpulan dependensi opsional `standar`: + +Digunakan oleh Pydantic: + +* email-validator - untuk validasi email. + +Digunakan oleh Starlette: + +* httpx - Dibutuhkan jika anda menggunakan `TestClient`. +* jinja2 - Dibutuhkan jika anda menggunakan konfigurasi template bawaan. +* python-multipart - Dibutuhkan jika anda menggunakan form dukungan "parsing", dengan `request.form()`. + +Digunakan oleh FastAPI / Starlette: + +* uvicorn - untuk server yang memuat dan melayani aplikasi anda. Termasuk `uvicorn[standard]`, yang memasukan sejumlah dependensi (misal `uvloop`) untuk needed melayani dengan performa tinggi. +* `fastapi-cli` - untuk menyediakan perintah `fastapi`. + +### Tanpda dependensi `standard` + +Jika anda tidak ingin menambahkan dependensi opsional `standard`, anda dapat menggunakan `pip install fastapi` daripada `pip install "fastapi[standard]"`. + +### Dependensi Opsional Tambahan + +Ada beberapa dependensi opsional yang bisa anda install. + +Dependensi opsional tambahan Pydantic: + +* pydantic-settings - untuk manajemen setting. +* pydantic-extra-types - untuk tipe tambahan yang digunakan dengan Pydantic. + +Dependensi tambahan opsional FastAPI: + +* orjson - Diperlukan jika anda akan menggunakan`ORJSONResponse`. +* ujson - Diperlukan jika anda akan menggunakan `UJSONResponse`. + +## Lisensi + +Project terlisensi dengan lisensi MIT. From 2612fa3e9d17fe74c97029b55b5d64be2d38400f Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 13 Jan 2025 13:36:46 +0000 Subject: [PATCH 661/932] =?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 [skip ci] --- 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 3aabd1fc0..9393b1156 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 🌐 Add Indonesian translation for `docs/id/docs/index.md`. PR [#13191](https://github.com/fastapi/fastapi/pull/13191) by [@gerry-sabar](https://github.com/gerry-sabar). * 🌐 Add Indonesian translation for `docs/id/docs/tutorial/static-files.md`. PR [#13092](https://github.com/fastapi/fastapi/pull/13092) by [@guspan-tanadi](https://github.com/guspan-tanadi). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/get-current-user.md`. PR [#13188](https://github.com/fastapi/fastapi/pull/13188) by [@ceb10n](https://github.com/ceb10n). * 🌐 Remove Wrong Portuguese translations location for `docs/pt/docs/advanced/benchmarks.md`. PR [#13187](https://github.com/fastapi/fastapi/pull/13187) by [@ceb10n](https://github.com/ceb10n). From 16199c4a138acbdac838124cfd54fb257dc52d8f Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Wed, 15 Jan 2025 17:16:13 -0300 Subject: [PATCH 662/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/security/oauth2-jwt.md`?= =?UTF-8?q?=20(#13205)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/security/oauth2-jwt.md | 274 +++++++++++++++++++ 1 file changed, 274 insertions(+) create mode 100644 docs/pt/docs/tutorial/security/oauth2-jwt.md diff --git a/docs/pt/docs/tutorial/security/oauth2-jwt.md b/docs/pt/docs/tutorial/security/oauth2-jwt.md new file mode 100644 index 000000000..4b99c4c59 --- /dev/null +++ b/docs/pt/docs/tutorial/security/oauth2-jwt.md @@ -0,0 +1,274 @@ +# OAuth2 com Senha (e hashing), Bearer com tokens JWT + +Agora que temos todo o fluxo de segurança, vamos tornar a aplicação realmente segura, usando tokens JWT e hashing de senhas seguras. + +Este código é algo que você pode realmente usar na sua aplicação, salvar os hashes das senhas no seu banco de dados, etc. + +Vamos começar de onde paramos no capítulo anterior e incrementá-lo. + +## Sobre o JWT + +JWT significa "JSON Web Tokens". + +É um padrão para codificar um objeto JSON em uma string longa e densa sem espaços. Ele se parece com isso: + +``` +eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c +``` + +Ele não é criptografado, então qualquer pessoa pode recuperar as informações do seu conteúdo. + +Mas ele é assinado. Assim, quando você recebe um token que você emitiu, você pode verificar que foi realmente você quem o emitiu. + +Dessa forma, você pode criar um token com um prazo de expiração, digamos, de 1 semana. E então, quando o usuário voltar no dia seguinte com o token, você sabe que ele ainda está logado no seu sistema. + +Depois de uma semana, o token expirará e o usuário não estará autorizado, precisando fazer login novamente para obter um novo token. E se o usuário (ou uma terceira parte) tentar modificar o token para alterar a expiração, você seria capaz de descobrir isso, pois as assinaturas não iriam corresponder. + +Se você quiser brincar com tokens JWT e ver como eles funcionam, visite https://jwt.io. + +## Instalar `PyJWT` + +Nós precisamos instalar o `PyJWT` para criar e verificar os tokens JWT em Python. + +Certifique-se de criar um [ambiente virtual](../../virtual-environments.md){.internal-link target=_blank}, ativá-lo e então instalar o `pyjwt`: + +
    + +```console +$ pip install pyjwt + +---> 100% +``` + +
    + +/// info | Informação + +Se você pretente utilizar algoritmos de assinatura digital como o RSA ou o ECDSA, você deve instalar a dependência da biblioteca de criptografia `pyjwt[crypto]`. + +Você pode ler mais sobre isso na documentação de instalação do PyJWT. + +/// + +## Hashing de senhas + +"Hashing" significa converter algum conteúdo (uma senha neste caso) em uma sequência de bytes (apenas uma string) que parece um monte de caracteres sem sentido. + +Sempre que você passar exatamente o mesmo conteúdo (exatamente a mesma senha), você obterá exatamente o mesmo resultado. + +Mas não é possível converter os caracteres sem sentido de volta para a senha original. + +### Por que usar hashing de senhas + +Se o seu banco de dados for roubado, o invasor não terá as senhas em texto puro dos seus usuários, apenas os hashes. + +Então, o invasor não poderá tentar usar essas senhas em outro sistema (como muitos usuários utilizam a mesma senha em vários lugares, isso seria perigoso). + +## Instalar o `passlib` + +O PassLib é uma excelente biblioteca Python para lidar com hashes de senhas. + +Ele suporta muitos algoritmos de hashing seguros e utilitários para trabalhar com eles. + +O algoritmo recomendado é o "Bcrypt". + +Certifique-se de criar um [ambiente virtual](../../virtual-environments.md){.internal-link target=_blank}, ativá-lo e então instalar o PassLib com Bcrypt: + +
    + +```console +$ pip install "passlib[bcrypt]" + +---> 100% +``` + +
    + +/// tip | Dica + +Com o `passlib`, você poderia até configurá-lo para ser capaz de ler senhas criadas pelo **Django**, um plug-in de segurança do **Flask** ou muitos outros. + +Assim, você poderia, por exemplo, compartilhar os mesmos dados de um aplicativo Django em um banco de dados com um aplicativo FastAPI. Ou migrar gradualmente uma aplicação Django usando o mesmo banco de dados. + +E seus usuários poderiam fazer login tanto pela sua aplicação Django quanto pela sua aplicação **FastAPI**, ao mesmo tempo. + +/// + +## Criar o hash e verificar as senhas + +Importe as ferramentas que nós precisamos de `passlib`. + +Crie um "contexto" do PassLib. Este será usado para criar o hash e verificar as senhas. + +/// tip | Dica + +O contexto do PassLib também possui funcionalidades para usar diferentes algoritmos de hashing, incluindo algoritmos antigos que estão obsoletos, apenas para permitir verificá-los, etc. + +Por exemplo, você poderia usá-lo para ler e verificar senhas geradas por outro sistema (como Django), mas criar o hash de novas senhas com um algoritmo diferente, como o Bcrypt. + +E ser compatível com todos eles ao mesmo tempo. + +/// + +Crie uma função utilitária para criar o hash de uma senha fornecida pelo usuário. + +E outra função utilitária para verificar se uma senha recebida corresponde ao hash armazenado. + +E outra para autenticar e retornar um usuário. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *} + +/// note | Nota + +Se você verificar o novo banco de dados (falso) `fake_users_db`, você verá como o hash da senha se parece agora: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. + +/// + +## Manipular tokens JWT + +Importe os módulos instalados. + +Crie uma chave secreta aleatória que será usada para assinar os tokens JWT. + +Para gerar uma chave secreta aleatória e segura, use o comando: + +
    + +```console +$ openssl rand -hex 32 + +09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7 +``` + +
    + +E copie a saída para a variável `SECRET_KEY` (não use a do exemplo). + +Crie uma variável `ALGORITHM` com o algoritmo usado para assinar o token JWT e defina como `"HS256"`. + +Crie uma variável para a expiração do token. + +Defina um modelo Pydantic que será usado no endpoint de token para a resposta. + +Crie uma função utilitária para gerar um novo token de acesso. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *} + +## Atualize as dependências + +Atualize `get_current_user` para receber o mesmo token de antes, mas desta vez, usando tokens JWT. + +Decodifique o token recebido, verifique-o e retorne o usuário atual. + +Se o token for inválido, retorne um erro HTTP imediatamente. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[90:107] *} + +## Atualize a *operação de rota* `/token` + +Crie um `timedelta` com o tempo de expiração do token. + +Crie um token de acesso JWT real e o retorne. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *} + +### Detalhes técnicos sobre o "sujeito" `sub` do JWT + +A especificação JWT diz que existe uma chave `sub`, com o sujeito do token. + +É opcional usá-la, mas é onde você colocaria a identificação do usuário, então nós estamos usando aqui. + +O JWT pode ser usado para outras coisas além de identificar um usuário e permitir que ele execute operações diretamente na sua API. + +Por exemplo, você poderia identificar um "carro" ou uma "postagem de blog". + +Depois, você poderia adicionar permissões sobre essa entidade, como "dirigir" (para o carro) ou "editar" (para o blog). + +E então, poderia dar esse token JWT para um usuário (ou bot), e ele poderia usá-lo para realizar essas ações (dirigir o carro ou editar o blog) sem sequer precisar ter uma conta, apenas com o token JWT que sua API gerou para isso. + +Usando essas ideias, o JWT pode ser usado para cenários muito mais sofisticados. + +Nesses casos, várias dessas entidades poderiam ter o mesmo ID, digamos `foo` (um usuário `foo`, um carro `foo` e uma postagem de blog `foo`). + +Então, para evitar colisões de ID, ao criar o token JWT para o usuário, você poderia prefixar o valor da chave `sub`, por exemplo, com `username:`. Assim, neste exemplo, o valor de `sub` poderia ser: `username:johndoe`. + +O importante a se lembrar é que a chave `sub` deve ter um identificador único em toda a aplicação e deve ser uma string. + +## Testando + +Execute o servidor e vá para a documentação: http://127.0.0.1:8000/docs. + +Você verá a interface de usuário assim: + + + +Autorize a aplicação da mesma maneira que antes. + +Usando as credenciais: + +Username: `johndoe` +Password: `secret` + +/// check | Verifique + +Observe que em nenhuma parte do código está a senha em texto puro "`secret`", nós temos apenas o hash. + +/// + + + +Chame o endpoint `/users/me/`, você receberá o retorno como: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false +} +``` + + + +Se você abrir as ferramentas de desenvolvedor, poderá ver que os dados enviados incluem apenas o token. A senha é enviada apenas na primeira requisição para autenticar o usuário e obter o token de acesso, mas não é enviada nas próximas requisições: + + + +/// note | Nota + +Perceba que o cabeçalho `Authorization`, com o valor que começa com `Bearer `. + +/// + +## Uso avançado com `scopes` + +O OAuth2 tem a noção de "scopes" (escopos). + +Você pode usá-los para adicionar um conjunto específico de permissões a um token JWT. + +Então, você pode dar este token diretamente a um usuário ou a uma terceira parte para interagir com sua API com um conjunto de restrições. + +Você pode aprender como usá-los e como eles são integrados ao **FastAPI** mais adiante no **Guia Avançado do Usuário**. + + +## Recapitulação + +Com o que você viu até agora, você pode configurar uma aplicação **FastAPI** segura usando padrões como OAuth2 e JWT. + +Em quase qualquer framework, lidar com a segurança se torna rapidamente um assunto bastante complexo. + +Muitos pacotes que simplificam bastante isso precisam fazer muitas concessões com o modelo de dados, o banco de dados e os recursos disponíveis. E alguns desses pacotes que simplificam demais na verdade têm falhas de segurança subjacentes. + +--- + +O **FastAPI** não faz nenhuma concessão com nenhum banco de dados, modelo de dados ou ferramenta. + +Ele oferece toda a flexibilidade para você escolher as opções que melhor se ajustam ao seu projeto. + +E você pode usar diretamente muitos pacotes bem mantidos e amplamente utilizados, como `passlib` e `PyJWT`, porque o **FastAPI** não exige mecanismos complexos para integrar pacotes externos. + +Mas ele fornece as ferramentas para simplificar o processo o máximo possível, sem comprometer a flexibilidade, robustez ou segurança. + +E você pode usar e implementar protocolos padrão seguros, como o OAuth2, de uma maneira relativamente simples. + +Você pode aprender mais no **Guia Avançado do Usuário** sobre como usar os "scopes" do OAuth2 para um sistema de permissões mais refinado, seguindo esses mesmos padrões. O OAuth2 com scopes é o mecanismo usado por muitos provedores grandes de autenticação, como o Facebook, Google, GitHub, Microsoft, Twitter, etc. para autorizar aplicativos de terceiros a interagir com suas APIs em nome de seus usuários. From 5f49397d195293f6d5d948ae1765f5240c7b3a90 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 15 Jan 2025 20:16:38 +0000 Subject: [PATCH 663/932] =?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 [skip ci] --- 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 9393b1156..c09fcf950 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/oauth2-jwt.md`. PR [#13205](https://github.com/fastapi/fastapi/pull/13205) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Indonesian translation for `docs/id/docs/index.md`. PR [#13191](https://github.com/fastapi/fastapi/pull/13191) by [@gerry-sabar](https://github.com/gerry-sabar). * 🌐 Add Indonesian translation for `docs/id/docs/tutorial/static-files.md`. PR [#13092](https://github.com/fastapi/fastapi/pull/13092) by [@guspan-tanadi](https://github.com/guspan-tanadi). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/get-current-user.md`. PR [#13188](https://github.com/fastapi/fastapi/pull/13188) by [@ceb10n](https://github.com/ceb10n). From d9a640e06c924e40b29da274df26f82d3537393c Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Wed, 15 Jan 2025 17:17:23 -0300 Subject: [PATCH 664/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Portuguese=20tr?= =?UTF-8?q?anslation=20for=20`docs/pt/docs/advanced/settings.md`=20(#13209?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/settings.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/pt/docs/advanced/settings.md b/docs/pt/docs/advanced/settings.md index 00a39b0af..cdc6400ad 100644 --- a/docs/pt/docs/advanced/settings.md +++ b/docs/pt/docs/advanced/settings.md @@ -8,7 +8,7 @@ Por isso é comum prover essas configurações como variáveis de ambiente que s ## Variáveis de Ambiente -/// dica +/// tip | Dica Se você já sabe o que são variáveis de ambiente e como utilizá-las, sinta-se livre para avançar para o próximo tópico. @@ -67,7 +67,7 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -/// dica +/// tip | Dica O segundo parâmetro em `os.getenv()` é o valor padrão para o retorno. @@ -124,7 +124,7 @@ Hello World from Python
    -/// dica +/// tip | Dica Você pode ler mais sobre isso em: The Twelve-Factor App: Configurações. @@ -196,7 +196,7 @@ Na versão 1 do Pydantic você importaria `BaseSettings` diretamente do módulo //// -/// dica +/// tip | Dica Se você quiser algo pronto para copiar e colar na sua aplicação, não use esse exemplo, mas sim o exemplo abaixo. @@ -226,7 +226,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.p -/// dica +/// tip | Dica Para definir múltiplas variáveis de ambiente para um único comando basta separá-las utilizando espaços, e incluir todas elas antes do comando. @@ -250,7 +250,7 @@ E utilizar essa configuração em `main.py`: {* ../../docs_src/settings/app01/main.py hl[3,11:13] *} -/// dica +/// tip | Dica Você também precisa incluir um arquivo `__init__.py` como visto em [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=\_blank}. @@ -276,7 +276,7 @@ Agora criamos a dependência que retorna um novo objeto `config.Settings()`. {* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *} -/// dica +/// tip | Dica Vamos discutir sobre `@lru_cache` logo mais. @@ -304,7 +304,7 @@ Se você tiver muitas configurações que variem bastante, talvez em ambientes d Essa prática é tão comum que possui um nome, essas variáveis de ambiente normalmente são colocadas em um arquivo `.env`, e esse arquivo é chamado de "dotenv". -/// dica +/// tip | Dica Um arquivo iniciando com um ponto final (`.`) é um arquivo oculto em sistemas baseados em Unix, como Linux e MacOS. @@ -314,7 +314,7 @@ Mas um arquivo dotenv não precisa ter esse nome exato. Pydantic suporta a leitura desses tipos de arquivos utilizando uma biblioteca externa. Você pode ler mais em Pydantic Settings: Dotenv (.env) support. -/// dica +/// tip | Dica Para que isso funcione você precisa executar `pip install python-dotenv`. @@ -337,7 +337,7 @@ E então adicionar o seguinte código em `config.py`: {* ../../docs_src/settings/app03_an/config.py hl[9] *} -/// dica +/// tip | Dica O atributo `model_config` é usado apenas para configuração do Pydantic. Você pode ler mais em Pydantic Model Config. @@ -349,7 +349,7 @@ O atributo `model_config` é usado apenas para configuração do Pydantic. Você {* ../../docs_src/settings/app03_an/config_pv1.py hl[9:10] *} -/// dica +/// tip | Dica A classe `Config` é usada apenas para configuração do Pydantic. Você pode ler mais em Pydantic Model Config. From e773d7e9193d221e0f9398de9b6dda5dfdb6d0b9 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 15 Jan 2025 20:18:49 +0000 Subject: [PATCH 665/932] =?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 [skip ci] --- 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 c09fcf950..535973099 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 🌐 Update Portuguese translation for `docs/pt/docs/advanced/settings.md`. PR [#13209](https://github.com/fastapi/fastapi/pull/13209) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/oauth2-jwt.md`. PR [#13205](https://github.com/fastapi/fastapi/pull/13205) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Indonesian translation for `docs/id/docs/index.md`. PR [#13191](https://github.com/fastapi/fastapi/pull/13191) by [@gerry-sabar](https://github.com/gerry-sabar). * 🌐 Add Indonesian translation for `docs/id/docs/tutorial/static-files.md`. PR [#13092](https://github.com/fastapi/fastapi/pull/13092) by [@guspan-tanadi](https://github.com/guspan-tanadi). From 9e0d4fa0efed6376a0e4066ddc59b8802fcd25b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 17 Jan 2025 17:51:19 +0000 Subject: [PATCH 666/932] =?UTF-8?q?=F0=9F=91=B7=20Add=20independent=20CI?= =?UTF-8?q?=20automation=20for=20FastAPI=20People=20-=20Sponsors=20(#13221?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/sponsors.yml | 53 ++++++++ scripts/sponsors.py | 220 +++++++++++++++++++++++++++++++++ 2 files changed, 273 insertions(+) create mode 100644 .github/workflows/sponsors.yml create mode 100644 scripts/sponsors.py diff --git a/.github/workflows/sponsors.yml b/.github/workflows/sponsors.yml new file mode 100644 index 000000000..590ac5487 --- /dev/null +++ b/.github/workflows/sponsors.yml @@ -0,0 +1,53 @@ +name: FastAPI People Sponsors + +on: + schedule: + - cron: "0 6 1 * *" + workflow_dispatch: + inputs: + debug_enabled: + description: "Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)" + required: false + default: "false" + +env: + UV_SYSTEM_PYTHON: 1 + +jobs: + job: + if: github.repository_owner == 'fastapi' + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Setup uv + uses: astral-sh/setup-uv@v5 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - name: Install Dependencies + run: uv pip install -r requirements-github-actions.txt + # Allow debugging with tmate + - name: Setup tmate session + uses: mxschmitt/action-tmate@v3 + if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} + with: + limit-access-to-actor: true + env: + GITHUB_TOKEN: ${{ secrets.FASTAPI_PR_TOKEN }} + - name: FastAPI People Sponsors + run: python ./scripts/sponsors.py + env: + GITHUB_TOKEN: ${{ secrets.FASTAPI_PR_TOKEN }} diff --git a/scripts/sponsors.py b/scripts/sponsors.py new file mode 100644 index 000000000..ed782a49e --- /dev/null +++ b/scripts/sponsors.py @@ -0,0 +1,220 @@ +import logging +import secrets +import subprocess +from collections import defaultdict +from pathlib import Path +from typing import Any + +import httpx +import yaml +from github import Github +from pydantic import BaseModel, SecretStr +from pydantic_settings import BaseSettings + +github_graphql_url = "https://api.github.com/graphql" + + +sponsors_query = """ +query Q($after: String) { + user(login: "tiangolo") { + sponsorshipsAsMaintainer(first: 100, after: $after) { + edges { + cursor + node { + sponsorEntity { + ... on Organization { + login + avatarUrl + url + } + ... on User { + login + avatarUrl + url + } + } + tier { + name + monthlyPriceInDollars + } + } + } + } + } +} +""" + + +class SponsorEntity(BaseModel): + login: str + avatarUrl: str + url: str + + +class Tier(BaseModel): + name: str + monthlyPriceInDollars: float + + +class SponsorshipAsMaintainerNode(BaseModel): + sponsorEntity: SponsorEntity + tier: Tier + + +class SponsorshipAsMaintainerEdge(BaseModel): + cursor: str + node: SponsorshipAsMaintainerNode + + +class SponsorshipAsMaintainer(BaseModel): + edges: list[SponsorshipAsMaintainerEdge] + + +class SponsorsUser(BaseModel): + sponsorshipsAsMaintainer: SponsorshipAsMaintainer + + +class SponsorsResponseData(BaseModel): + user: SponsorsUser + + +class SponsorsResponse(BaseModel): + data: SponsorsResponseData + + +class Settings(BaseSettings): + github_token: SecretStr + github_repository: str + httpx_timeout: int = 30 + + +def get_graphql_response( + *, + settings: Settings, + query: str, + after: str | None = None, +) -> dict[str, Any]: + headers = {"Authorization": f"token {settings.github_token.get_secret_value()}"} + variables = {"after": after} + response = httpx.post( + github_graphql_url, + headers=headers, + timeout=settings.httpx_timeout, + json={"query": query, "variables": variables, "operationName": "Q"}, + ) + if response.status_code != 200: + logging.error(f"Response was not 200, after: {after}") + logging.error(response.text) + raise RuntimeError(response.text) + data = response.json() + if "errors" in data: + logging.error(f"Errors in response, after: {after}") + logging.error(data["errors"]) + logging.error(response.text) + raise RuntimeError(response.text) + return data + + +def get_graphql_sponsor_edges( + *, settings: Settings, after: str | None = None +) -> list[SponsorshipAsMaintainerEdge]: + data = get_graphql_response(settings=settings, query=sponsors_query, after=after) + graphql_response = SponsorsResponse.model_validate(data) + return graphql_response.data.user.sponsorshipsAsMaintainer.edges + + +def get_individual_sponsors( + settings: Settings, +) -> defaultdict[float, dict[str, SponsorEntity]]: + nodes: list[SponsorshipAsMaintainerNode] = [] + edges = get_graphql_sponsor_edges(settings=settings) + + while edges: + for edge in edges: + nodes.append(edge.node) + last_edge = edges[-1] + edges = get_graphql_sponsor_edges(settings=settings, after=last_edge.cursor) + + tiers: defaultdict[float, dict[str, SponsorEntity]] = defaultdict(dict) + for node in nodes: + tiers[node.tier.monthlyPriceInDollars][node.sponsorEntity.login] = ( + node.sponsorEntity + ) + return tiers + + +def update_content(*, content_path: Path, new_content: Any) -> bool: + old_content = content_path.read_text(encoding="utf-8") + + new_content = yaml.dump(new_content, sort_keys=False, width=200, allow_unicode=True) + if old_content == new_content: + logging.info(f"The content hasn't changed for {content_path}") + return False + content_path.write_text(new_content, encoding="utf-8") + logging.info(f"Updated {content_path}") + return True + + +def main() -> None: + logging.basicConfig(level=logging.INFO) + settings = Settings() + logging.info(f"Using config: {settings.model_dump_json()}") + g = Github(settings.github_token.get_secret_value()) + repo = g.get_repo(settings.github_repository) + + tiers = get_individual_sponsors(settings=settings) + keys = list(tiers.keys()) + keys.sort(reverse=True) + sponsors = [] + for key in keys: + sponsor_group = [] + for login, sponsor in tiers[key].items(): + sponsor_group.append( + {"login": login, "avatarUrl": sponsor.avatarUrl, "url": sponsor.url} + ) + sponsors.append(sponsor_group) + github_sponsors = { + "sponsors": sponsors, + } + + # For local development + # github_sponsors_path = Path("../docs/en/data/github_sponsors.yml") + github_sponsors_path = Path("./docs/en/data/github_sponsors.yml") + updated = update_content( + content_path=github_sponsors_path, new_content=github_sponsors + ) + + if not updated: + logging.info("The data hasn't changed, finishing.") + return + + logging.info("Setting up GitHub Actions git user") + subprocess.run(["git", "config", "user.name", "github-actions"], check=True) + subprocess.run( + ["git", "config", "user.email", "github-actions@github.com"], check=True + ) + branch_name = f"fastapi-people-sponsors-{secrets.token_hex(4)}" + logging.info(f"Creating a new branch {branch_name}") + subprocess.run(["git", "checkout", "-b", branch_name], check=True) + logging.info("Adding updated file") + subprocess.run( + [ + "git", + "add", + str(github_sponsors_path), + ], + check=True, + ) + logging.info("Committing updated file") + message = "👥 Update FastAPI People - Sponsors" + subprocess.run(["git", "commit", "-m", message], check=True) + logging.info("Pushing branch") + subprocess.run(["git", "push", "origin", branch_name], check=True) + logging.info("Creating PR") + pr = repo.create_pull(title=message, body=message, base="master", head=branch_name) + logging.info(f"Created PR: {pr.number}") + logging.info("Finished") + + +if __name__ == "__main__": + main() From db48d9cf0983752b155b93b882130da60d8a2636 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 17 Jan 2025 17:53:06 +0000 Subject: [PATCH 667/932] =?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 [skip ci] --- 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 535973099..12cf637f5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -85,6 +85,7 @@ hide: ### Internal +* 👷 Add independent CI automation for FastAPI People - Sponsors. PR [#13221](https://github.com/fastapi/fastapi/pull/13221) by [@tiangolo](https://github.com/tiangolo). * 👷 Add retries to Smokeshow. PR [#13151](https://github.com/fastapi/fastapi/pull/13151) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update Speakeasy sponsor graphic. PR [#13147](https://github.com/fastapi/fastapi/pull/13147) by [@chailandau](https://github.com/chailandau). * 👥 Update FastAPI GitHub topic repositories. PR [#13146](https://github.com/fastapi/fastapi/pull/13146) by [@tiangolo](https://github.com/tiangolo). From 35b24deef37e006ae732d9190ea39fab3001ca5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 17 Jan 2025 22:33:38 +0000 Subject: [PATCH 668/932] =?UTF-8?q?=F0=9F=91=B7=20Update=20token=20for=20F?= =?UTF-8?q?astAPI=20People=20-=20Sponsors=20(#13225)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/sponsors.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/sponsors.yml b/.github/workflows/sponsors.yml index 590ac5487..d2d845b27 100644 --- a/.github/workflows/sponsors.yml +++ b/.github/workflows/sponsors.yml @@ -45,9 +45,7 @@ jobs: if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - env: - GITHUB_TOKEN: ${{ secrets.FASTAPI_PR_TOKEN }} - name: FastAPI People Sponsors run: python ./scripts/sponsors.py env: - GITHUB_TOKEN: ${{ secrets.FASTAPI_PR_TOKEN }} + GITHUB_TOKEN: ${{ secrets.SPONSORS }} From ea0cdd120c39b34aca6ea592832d7fa43944d34d Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 17 Jan 2025 22:34:04 +0000 Subject: [PATCH 669/932] =?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 [skip ci] --- 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 12cf637f5..5c628813c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -85,6 +85,7 @@ hide: ### Internal +* 👷 Update token for FastAPI People - Sponsors. PR [#13225](https://github.com/fastapi/fastapi/pull/13225) by [@tiangolo](https://github.com/tiangolo). * 👷 Add independent CI automation for FastAPI People - Sponsors. PR [#13221](https://github.com/fastapi/fastapi/pull/13221) by [@tiangolo](https://github.com/tiangolo). * 👷 Add retries to Smokeshow. PR [#13151](https://github.com/fastapi/fastapi/pull/13151) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update Speakeasy sponsor graphic. PR [#13147](https://github.com/fastapi/fastapi/pull/13147) by [@chailandau](https://github.com/chailandau). From 2ee101fb815188313fdbe262388711bc238c1bfb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 18 Jan 2025 12:58:36 +0000 Subject: [PATCH 670/932] =?UTF-8?q?=F0=9F=91=B7=20Refactor=20FastAPI=20Peo?= =?UTF-8?q?ple=20Sponsors=20to=20use=202=20tokens=20(#13228)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/sponsors.yml | 3 ++- scripts/sponsors.py | 7 ++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.github/workflows/sponsors.yml b/.github/workflows/sponsors.yml index d2d845b27..a5230c834 100644 --- a/.github/workflows/sponsors.yml +++ b/.github/workflows/sponsors.yml @@ -48,4 +48,5 @@ jobs: - name: FastAPI People Sponsors run: python ./scripts/sponsors.py env: - GITHUB_TOKEN: ${{ secrets.SPONSORS }} + SPONSORS_TOKEN: ${{ secrets.SPONSORS_TOKEN }} + PR_TOKEN: ${{ secrets.FASTAPI_PR_TOKEN }} diff --git a/scripts/sponsors.py b/scripts/sponsors.py index ed782a49e..45e02bd62 100644 --- a/scripts/sponsors.py +++ b/scripts/sponsors.py @@ -83,7 +83,8 @@ class SponsorsResponse(BaseModel): class Settings(BaseSettings): - github_token: SecretStr + sponsors_token: SecretStr + pr_token: SecretStr github_repository: str httpx_timeout: int = 30 @@ -94,7 +95,7 @@ def get_graphql_response( query: str, after: str | None = None, ) -> dict[str, Any]: - headers = {"Authorization": f"token {settings.github_token.get_secret_value()}"} + headers = {"Authorization": f"token {settings.sponsors_token.get_secret_value()}"} variables = {"after": after} response = httpx.post( github_graphql_url, @@ -159,7 +160,7 @@ def main() -> None: logging.basicConfig(level=logging.INFO) settings = Settings() logging.info(f"Using config: {settings.model_dump_json()}") - g = Github(settings.github_token.get_secret_value()) + g = Github(settings.pr_token.get_secret_value()) repo = g.get_repo(settings.github_repository) tiers = get_individual_sponsors(settings=settings) From 2acdc13608592e184a1dba6f80fe81880eaa3af7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 18 Jan 2025 12:58:57 +0000 Subject: [PATCH 671/932] =?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 [skip ci] --- 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 5c628813c..404e3269a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -85,6 +85,7 @@ hide: ### Internal +* 👷 Refactor FastAPI People Sponsors to use 2 tokens. PR [#13228](https://github.com/fastapi/fastapi/pull/13228) by [@tiangolo](https://github.com/tiangolo). * 👷 Update token for FastAPI People - Sponsors. PR [#13225](https://github.com/fastapi/fastapi/pull/13225) by [@tiangolo](https://github.com/tiangolo). * 👷 Add independent CI automation for FastAPI People - Sponsors. PR [#13221](https://github.com/fastapi/fastapi/pull/13221) by [@tiangolo](https://github.com/tiangolo). * 👷 Add retries to Smokeshow. PR [#13151](https://github.com/fastapi/fastapi/pull/13151) by [@tiangolo](https://github.com/tiangolo). From af599c92ac4a2993416408e5c231e84c9971eb9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 18 Jan 2025 13:10:13 +0000 Subject: [PATCH 672/932] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e=20-=20Sponsors=20(#13231)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions --- docs/en/data/github_sponsors.yml | 492 ++++++++++++++----------------- 1 file changed, 225 insertions(+), 267 deletions(-) diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml index 5f0be61c2..55fe3dda9 100644 --- a/docs/en/data/github_sponsors.yml +++ b/docs/en/data/github_sponsors.yml @@ -2,57 +2,60 @@ sponsors: - - login: bump-sh avatarUrl: https://avatars.githubusercontent.com/u/33217836?v=4 url: https://github.com/bump-sh - - login: porter-dev - avatarUrl: https://avatars.githubusercontent.com/u/62078005?v=4 - url: https://github.com/porter-dev + - login: Nixtla + avatarUrl: https://avatars.githubusercontent.com/u/79945230?v=4 + url: https://github.com/Nixtla - login: andrew-propelauth avatarUrl: https://avatars.githubusercontent.com/u/89474256?u=1188c27cb744bbec36447a2cfd4453126b2ddb5c&v=4 url: https://github.com/andrew-propelauth + - login: liblaber + avatarUrl: https://avatars.githubusercontent.com/u/100821118?v=4 + url: https://github.com/liblaber - login: zanfaruqui avatarUrl: https://avatars.githubusercontent.com/u/104461687?v=4 url: https://github.com/zanfaruqui - - login: Alek99 - avatarUrl: https://avatars.githubusercontent.com/u/38776361?u=bd6c163fe787c2de1a26c881598e54b67e2482dd&v=4 - url: https://github.com/Alek99 - - login: cryptapi - avatarUrl: https://avatars.githubusercontent.com/u/44925437?u=61369138589bc7fee6c417f3fbd50fbd38286cc4&v=4 - url: https://github.com/cryptapi - - login: Kong - avatarUrl: https://avatars.githubusercontent.com/u/962416?v=4 - url: https://github.com/Kong - - login: codacy - avatarUrl: https://avatars.githubusercontent.com/u/1834093?v=4 - url: https://github.com/codacy + - login: blockbee-io + avatarUrl: https://avatars.githubusercontent.com/u/115143449?u=1b8620c2d6567c4df2111a371b85a51f448f9b85&v=4 + url: https://github.com/blockbee-io + - login: zuplo + avatarUrl: https://avatars.githubusercontent.com/u/85497839?v=4 + url: https://github.com/zuplo + - login: render-sponsorships + avatarUrl: https://avatars.githubusercontent.com/u/189296666?v=4 + url: https://github.com/render-sponsorships + - login: porter-dev + avatarUrl: https://avatars.githubusercontent.com/u/62078005?v=4 + url: https://github.com/porter-dev - login: scalar avatarUrl: https://avatars.githubusercontent.com/u/301879?v=4 url: https://github.com/scalar - - login: ObliviousAI avatarUrl: https://avatars.githubusercontent.com/u/65656077?v=4 url: https://github.com/ObliviousAI -- - login: databento - avatarUrl: https://avatars.githubusercontent.com/u/64141749?v=4 - url: https://github.com/databento - - login: svix +- - login: svix avatarUrl: https://avatars.githubusercontent.com/u/80175132?v=4 url: https://github.com/svix - - login: deepset-ai - avatarUrl: https://avatars.githubusercontent.com/u/51827949?v=4 - url: https://github.com/deepset-ai - - login: mikeckennedy - avatarUrl: https://avatars.githubusercontent.com/u/2035561?u=ce6165b799ea3164cb6f5ff54ea08042057442af&v=4 - url: https://github.com/mikeckennedy - - login: ndimares - avatarUrl: https://avatars.githubusercontent.com/u/6267663?u=cfb27efde7a7212be8142abb6c058a1aeadb41b1&v=4 - url: https://github.com/ndimares -- - login: takashi-yoneya - avatarUrl: https://avatars.githubusercontent.com/u/33813153?u=2d0522bceba0b8b69adf1f2db866503bd96f944e&v=4 - url: https://github.com/takashi-yoneya + - login: stainless-api + avatarUrl: https://avatars.githubusercontent.com/u/88061651?v=4 + url: https://github.com/stainless-api + - login: speakeasy-api + avatarUrl: https://avatars.githubusercontent.com/u/91446104?v=4 + url: https://github.com/speakeasy-api + - login: databento + avatarUrl: https://avatars.githubusercontent.com/u/64141749?v=4 + url: https://github.com/databento +- - login: mercedes-benz + avatarUrl: https://avatars.githubusercontent.com/u/34240465?v=4 + url: https://github.com/mercedes-benz - login: xoflare avatarUrl: https://avatars.githubusercontent.com/u/74335107?v=4 url: https://github.com/xoflare - login: marvin-robot avatarUrl: https://avatars.githubusercontent.com/u/41086007?u=b9fcab402d0cd0aec738b6574fe60855cb0cd36d&v=4 url: https://github.com/marvin-robot + - login: Ponte-Energy-Partners + avatarUrl: https://avatars.githubusercontent.com/u/114745848?v=4 + url: https://github.com/Ponte-Energy-Partners - login: BoostryJP avatarUrl: https://avatars.githubusercontent.com/u/57932412?v=4 url: https://github.com/BoostryJP @@ -62,42 +65,63 @@ sponsors: - - login: Trivie avatarUrl: https://avatars.githubusercontent.com/u/8161763?v=4 url: https://github.com/Trivie -- - login: americanair - avatarUrl: https://avatars.githubusercontent.com/u/12281813?v=4 - url: https://github.com/americanair +- - login: takashi-yoneya + avatarUrl: https://avatars.githubusercontent.com/u/33813153?u=2d0522bceba0b8b69adf1f2db866503bd96f944e&v=4 + url: https://github.com/takashi-yoneya +- - login: mainframeindustries + avatarUrl: https://avatars.githubusercontent.com/u/55092103?v=4 + url: https://github.com/mainframeindustries - login: CanoaPBC avatarUrl: https://avatars.githubusercontent.com/u/64223768?v=4 url: https://github.com/CanoaPBC - - login: mainframeindustries - avatarUrl: https://avatars.githubusercontent.com/u/55092103?v=4 - url: https://github.com/mainframeindustries - - login: mangualero - avatarUrl: https://avatars.githubusercontent.com/u/3422968?u=c59272d7b5a912d6126fd6c6f17db71e20f506eb&v=4 - url: https://github.com/mangualero - - login: birkjernstrom - avatarUrl: https://avatars.githubusercontent.com/u/281715?u=4be14b43f76b4bd497b1941309bb390250b405e6&v=4 - url: https://github.com/birkjernstrom - login: yasyf avatarUrl: https://avatars.githubusercontent.com/u/709645?u=f36736b3c6a85f578886ecc42a740e7b436e7a01&v=4 url: https://github.com/yasyf +- - login: genzou9201 + avatarUrl: https://avatars.githubusercontent.com/u/42960762?u=1ca6c18c59e8b327ae584c545b72de31ebc05275&v=4 + url: https://github.com/genzou9201 - - login: primer-io avatarUrl: https://avatars.githubusercontent.com/u/62146168?v=4 url: https://github.com/primer-io - login: povilasb avatarUrl: https://avatars.githubusercontent.com/u/1213442?u=b11f58ed6ceea6e8297c9b310030478ebdac894d&v=4 url: https://github.com/povilasb -- - login: jhundman - avatarUrl: https://avatars.githubusercontent.com/u/24263908?v=4 - url: https://github.com/jhundman - - login: upciti +- - login: upciti avatarUrl: https://avatars.githubusercontent.com/u/43346262?v=4 url: https://github.com/upciti + - login: freddiev4 + avatarUrl: https://avatars.githubusercontent.com/u/8339018?u=1aad5b4f5a04cb750852b843d5e1d8f4ce339c2e&v=4 + url: https://github.com/freddiev4 - - login: samuelcolvin avatarUrl: https://avatars.githubusercontent.com/u/4039449?u=42eb3b833047c8c4b4f647a031eaef148c16d93f&v=4 url: https://github.com/samuelcolvin - - login: Kludex - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 - url: https://github.com/Kludex + - login: vincentkoc + avatarUrl: https://avatars.githubusercontent.com/u/25068?u=cbf098fc04c0473523d373b0dd2145b4ec99ef93&v=4 + url: https://github.com/vincentkoc + - login: ProteinQure + avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 + url: https://github.com/ProteinQure + - login: ddilidili + avatarUrl: https://avatars.githubusercontent.com/u/42176885?u=c0a849dde06987434653197b5f638d3deb55fc6c&v=4 + url: https://github.com/ddilidili + - login: otosky + avatarUrl: https://avatars.githubusercontent.com/u/42260747?u=69d089387c743d89427aa4ad8740cfb34045a9e0&v=4 + url: https://github.com/otosky + - login: mjohnsey + avatarUrl: https://avatars.githubusercontent.com/u/16784016?u=38fad2e6b411244560b3af99c5f5a4751bc81865&v=4 + url: https://github.com/mjohnsey + - login: ashi-agrawal + avatarUrl: https://avatars.githubusercontent.com/u/17105294?u=99c7a854035e5398d8e7b674f2d42baae6c957f8&v=4 + url: https://github.com/ashi-agrawal + - login: sepsi77 + avatarUrl: https://avatars.githubusercontent.com/u/18682303?v=4 + url: https://github.com/sepsi77 + - login: RaamEEIL + avatarUrl: https://avatars.githubusercontent.com/u/20320552?v=4 + url: https://github.com/RaamEEIL + - login: jhundman + avatarUrl: https://avatars.githubusercontent.com/u/24263908?v=4 + url: https://github.com/jhundman - login: b-rad-c avatarUrl: https://avatars.githubusercontent.com/u/25362581?u=5bb10629f4015b62bec1f9a366675d5085551af9&v=4 url: https://github.com/b-rad-c @@ -105,7 +129,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/25950317?u=cec1a3e0643b785288ae8260cc295a85ab344995&v=4 url: https://github.com/ehaca - login: raphaellaude - avatarUrl: https://avatars.githubusercontent.com/u/28026311?u=9ae4b158c0d2cb29ebd46df6b6edb7de08a67566&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/28026311?u=28faad3e62250ef91a0c3c5d0faba39592d9ab39&v=4 url: https://github.com/raphaellaude - login: timlrx avatarUrl: https://avatars.githubusercontent.com/u/28362229?u=9a745ca31372ee324af682715ae88ce8522f9094&v=4 @@ -116,78 +140,51 @@ sponsors: - login: ygorpontelo avatarUrl: https://avatars.githubusercontent.com/u/32963605?u=35f7103f9c4c4c2589ae5737ee882e9375ef072e&v=4 url: https://github.com/ygorpontelo - - login: ProteinQure - avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 - url: https://github.com/ProteinQure - - login: catherinenelson1 - avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=e714b957185b8cf3d301cced7fc3ad2842122c6a&v=4 - url: https://github.com/catherinenelson1 - - login: jsoques - avatarUrl: https://avatars.githubusercontent.com/u/12414216?u=620921d94196546cc8b9eae2cc4cbc3f95bab42f&v=4 - url: https://github.com/jsoques - - login: joeds13 - avatarUrl: https://avatars.githubusercontent.com/u/13631604?u=628eb122e08bef43767b3738752b883e8e7f6259&v=4 - url: https://github.com/joeds13 - - login: dannywade - avatarUrl: https://avatars.githubusercontent.com/u/13680237?u=418ee985bd41577b20fde81417fb2d901e875e8a&v=4 - url: https://github.com/dannywade - - login: khadrawy - avatarUrl: https://avatars.githubusercontent.com/u/13686061?u=59f25ef42ecf04c22657aac4238ce0e2d3d30304&v=4 - url: https://github.com/khadrawy - - login: mjohnsey - avatarUrl: https://avatars.githubusercontent.com/u/16784016?u=38fad2e6b411244560b3af99c5f5a4751bc81865&v=4 - url: https://github.com/mjohnsey - - login: ashi-agrawal - avatarUrl: https://avatars.githubusercontent.com/u/17105294?u=99c7a854035e5398d8e7b674f2d42baae6c957f8&v=4 - url: https://github.com/ashi-agrawal - - login: sepsi77 - avatarUrl: https://avatars.githubusercontent.com/u/18682303?v=4 - url: https://github.com/sepsi77 - - login: wedwardbeck - avatarUrl: https://avatars.githubusercontent.com/u/19333237?u=1de4ae2bf8d59eb4c013f21d863cbe0f2010575f&v=4 - url: https://github.com/wedwardbeck - - login: RaamEEIL - avatarUrl: https://avatars.githubusercontent.com/u/20320552?v=4 - url: https://github.com/RaamEEIL - - login: anthonycepeda - avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 - url: https://github.com/anthonycepeda - - login: patricioperezv - avatarUrl: https://avatars.githubusercontent.com/u/73832292?u=5f471f156e19ee7920e62ae0f4a47b95580e61cf&v=4 - url: https://github.com/patricioperezv + - login: chickenandstats + avatarUrl: https://avatars.githubusercontent.com/u/79477966?v=4 + url: https://github.com/chickenandstats - login: kaoru0310 avatarUrl: https://avatars.githubusercontent.com/u/80977929?u=1b61d10142b490e56af932ddf08a390fae8ee94f&v=4 url: https://github.com/kaoru0310 - login: DelfinaCare avatarUrl: https://avatars.githubusercontent.com/u/83734439?v=4 url: https://github.com/DelfinaCare - - login: Eruditis + - login: Karine-Bauch + avatarUrl: https://avatars.githubusercontent.com/u/90465103?u=7feb1018abb1a5631cfd9a91fea723d1ceb5f49b&v=4 + url: https://github.com/Karine-Bauch + - login: eruditis avatarUrl: https://avatars.githubusercontent.com/u/95244703?v=4 - url: https://github.com/Eruditis + url: https://github.com/eruditis - login: jugeeem avatarUrl: https://avatars.githubusercontent.com/u/116043716?u=ae590d79c38ac79c91b9c5caa6887d061e865a3d&v=4 url: https://github.com/jugeeem - - login: apitally - avatarUrl: https://avatars.githubusercontent.com/u/138365043?v=4 - url: https://github.com/apitally - login: logic-automation avatarUrl: https://avatars.githubusercontent.com/u/144732884?v=4 url: https://github.com/logic-automation - - login: ddilidili - avatarUrl: https://avatars.githubusercontent.com/u/42176885?u=c0a849dde06987434653197b5f638d3deb55fc6c&v=4 - url: https://github.com/ddilidili + - login: Torqsight-Labs + avatarUrl: https://avatars.githubusercontent.com/u/169598176?v=4 + url: https://github.com/Torqsight-Labs - login: ramonalmeidam avatarUrl: https://avatars.githubusercontent.com/u/45269580?u=3358750b3a5854d7c3ed77aaca7dd20a0f529d32&v=4 url: https://github.com/ramonalmeidam + - login: roboflow + avatarUrl: https://avatars.githubusercontent.com/u/53104118?v=4 + url: https://github.com/roboflow - login: dudikbender avatarUrl: https://avatars.githubusercontent.com/u/53487583?u=3a57542938ebfd57579a0111db2b297e606d9681&v=4 url: https://github.com/dudikbender - - login: prodhype - avatarUrl: https://avatars.githubusercontent.com/u/60444672?u=3f278cff25ea37ead487d7861d4a984795de819e&v=4 - url: https://github.com/prodhype - login: patsatsia avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4 url: https://github.com/patsatsia + - login: anthonycepeda + avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 + url: https://github.com/anthonycepeda + - login: patricioperezv + avatarUrl: https://avatars.githubusercontent.com/u/73832292?u=5f471f156e19ee7920e62ae0f4a47b95580e61cf&v=4 + url: https://github.com/patricioperezv + - login: mintuhouse + avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4 + url: https://github.com/mintuhouse - login: tcsmith avatarUrl: https://avatars.githubusercontent.com/u/989034?u=7d8d741552b3279e8f4d3878679823a705a46f8f&v=4 url: https://github.com/tcsmith @@ -200,9 +197,6 @@ sponsors: - login: knallgelb avatarUrl: https://avatars.githubusercontent.com/u/2358812?u=c48cb6362b309d74cbf144bd6ad3aed3eb443e82&v=4 url: https://github.com/knallgelb - - login: johannquerne - avatarUrl: https://avatars.githubusercontent.com/u/2736484?u=9b3381546a25679913a2b08110e4373c98840821&v=4 - url: https://github.com/johannquerne - login: Shark009 avatarUrl: https://avatars.githubusercontent.com/u/3163309?u=0c6f4091b0eda05c44c390466199826e6dc6e431&v=4 url: https://github.com/Shark009 @@ -215,15 +209,18 @@ sponsors: - login: kennywakeland avatarUrl: https://avatars.githubusercontent.com/u/3631417?u=7c8f743f1ae325dfadea7c62bbf1abd6a824fc55&v=4 url: https://github.com/kennywakeland - - login: simw - avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4 - url: https://github.com/simw - - login: koconder - avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4 - url: https://github.com/koconder + - login: aacayaco + avatarUrl: https://avatars.githubusercontent.com/u/3634801?u=eaadda178c964178fcb64886f6c732172c8f8219&v=4 + url: https://github.com/aacayaco + - login: anomaly + avatarUrl: https://avatars.githubusercontent.com/u/3654837?v=4 + url: https://github.com/anomaly - login: jstanden avatarUrl: https://avatars.githubusercontent.com/u/63288?u=c3658d57d2862c607a0e19c2101c3c51876e36ad&v=4 url: https://github.com/jstanden + - login: paulcwatts + avatarUrl: https://avatars.githubusercontent.com/u/150269?u=1819e145d573b44f0ad74b87206d21cd60331d4e&v=4 + url: https://github.com/paulcwatts - login: andreaso avatarUrl: https://avatars.githubusercontent.com/u/285964?u=837265cc7562c0685f25b2d81cd9de0434fe107c&v=4 url: https://github.com/andreaso @@ -239,36 +236,36 @@ sponsors: - login: wshayes avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 url: https://github.com/wshayes + - login: gaetanBloch + avatarUrl: https://avatars.githubusercontent.com/u/583199?u=50c49e83d6b4feb78a091901ea02ead1462f442b&v=4 + url: https://github.com/gaetanBloch - login: koxudaxi avatarUrl: https://avatars.githubusercontent.com/u/630670?u=507d8577b4b3670546b449c4c2ccbc5af40d72f7&v=4 url: https://github.com/koxudaxi - login: falkben avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 url: https://github.com/falkben - - login: mintuhouse - avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4 - url: https://github.com/mintuhouse - - login: Rehket - avatarUrl: https://avatars.githubusercontent.com/u/7015688?u=3afb0ba200feebbc7f958950e92db34df2a3c172&v=4 - url: https://github.com/Rehket - - login: hiancdtrsnm - avatarUrl: https://avatars.githubusercontent.com/u/7343177?v=4 - url: https://github.com/hiancdtrsnm - login: TrevorBenson - avatarUrl: https://avatars.githubusercontent.com/u/9167887?u=afdd1766fdb79e04e59094cc6a54cd011ee7f686&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/9167887?u=dccbea3327a57750923333d8ebf1a0b3f1948949&v=4 url: https://github.com/TrevorBenson - login: wdwinslow avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4 url: https://github.com/wdwinslow - - login: aacayaco - avatarUrl: https://avatars.githubusercontent.com/u/3634801?u=eaadda178c964178fcb64886f6c732172c8f8219&v=4 - url: https://github.com/aacayaco - - login: anomaly - avatarUrl: https://avatars.githubusercontent.com/u/3654837?v=4 - url: https://github.com/anomaly - - login: jgreys - avatarUrl: https://avatars.githubusercontent.com/u/4136890?u=096820d1ef89877d57d0f68e669ead8b0fde84df&v=4 - url: https://github.com/jgreys + - login: catherinenelson1 + avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=fe11bc35d36b6038cd46a946e4e46ef8aa5688ab&v=4 + url: https://github.com/catherinenelson1 + - login: jsoques + avatarUrl: https://avatars.githubusercontent.com/u/12414216?u=620921d94196546cc8b9eae2cc4cbc3f95bab42f&v=4 + url: https://github.com/jsoques + - login: joeds13 + avatarUrl: https://avatars.githubusercontent.com/u/13631604?u=628eb122e08bef43767b3738752b883e8e7f6259&v=4 + url: https://github.com/joeds13 + - login: dannywade + avatarUrl: https://avatars.githubusercontent.com/u/13680237?u=418ee985bd41577b20fde81417fb2d901e875e8a&v=4 + url: https://github.com/dannywade + - login: khadrawy + avatarUrl: https://avatars.githubusercontent.com/u/13686061?u=59f25ef42ecf04c22657aac4238ce0e2d3d30304&v=4 + url: https://github.com/khadrawy - login: Ryandaydev avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 url: https://github.com/Ryandaydev @@ -290,108 +287,81 @@ sponsors: - login: FernandoCelmer avatarUrl: https://avatars.githubusercontent.com/u/6262214?u=d29fff3fd862fda4ca752079f13f32e84c762ea4&v=4 url: https://github.com/FernandoCelmer -- - login: getsentry - avatarUrl: https://avatars.githubusercontent.com/u/1396951?v=4 - url: https://github.com/getsentry + - login: simw + avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4 + url: https://github.com/simw + - login: Rehket + avatarUrl: https://avatars.githubusercontent.com/u/7015688?u=3afb0ba200feebbc7f958950e92db34df2a3c172&v=4 + url: https://github.com/Rehket + - login: hiancdtrsnm + avatarUrl: https://avatars.githubusercontent.com/u/7343177?v=4 + url: https://github.com/hiancdtrsnm - - login: pawamoy avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4 url: https://github.com/pawamoy - - login: SebTota - avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4 - url: https://github.com/SebTota - - login: nisutec - avatarUrl: https://avatars.githubusercontent.com/u/25281462?u=e562484c451fdfc59053163f64405f8eb262b8b0&v=4 - url: https://github.com/nisutec - - login: hoenie-ams - avatarUrl: https://avatars.githubusercontent.com/u/25708487?u=cda07434f0509ac728d9edf5e681117c0f6b818b&v=4 - url: https://github.com/hoenie-ams - - login: joerambo - avatarUrl: https://avatars.githubusercontent.com/u/26282974?v=4 - url: https://github.com/joerambo - - login: rlnchow - avatarUrl: https://avatars.githubusercontent.com/u/28018479?u=a93ca9cf1422b9ece155784a72d5f2fdbce7adff&v=4 - url: https://github.com/rlnchow - login: engineerjoe440 avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4 url: https://github.com/engineerjoe440 - login: bnkc avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=db5e6f4f87836cad26c2aa90ce390ce49041c5a9&v=4 url: https://github.com/bnkc - - login: DevOpsKev - avatarUrl: https://avatars.githubusercontent.com/u/36336550?u=6ccd5978fdaab06f37e22f2a14a7439341df7f67&v=4 - url: https://github.com/DevOpsKev - login: petercool avatarUrl: https://avatars.githubusercontent.com/u/37613029?u=81c525232bb35780945a68e88afd96bb2cdad9c4&v=4 url: https://github.com/petercool - - login: JimFawkes - avatarUrl: https://avatars.githubusercontent.com/u/12075115?u=dc58ecfd064d72887c34bf500ddfd52592509acd&v=4 - url: https://github.com/JimFawkes - - login: artempronevskiy - avatarUrl: https://avatars.githubusercontent.com/u/12235104?u=03df6e1e55c9c6fe5d230adabb8dd7d43d8bbe8f&v=4 - url: https://github.com/artempronevskiy - - login: TheR1D - avatarUrl: https://avatars.githubusercontent.com/u/16740832?u=b0dfdbdb27b79729430c71c6128962f77b7b53f7&v=4 - url: https://github.com/TheR1D - - login: joshuatz - avatarUrl: https://avatars.githubusercontent.com/u/17817563?u=f1bf05b690d1fc164218f0b420cdd3acb7913e21&v=4 - url: https://github.com/joshuatz - - login: jangia - avatarUrl: https://avatars.githubusercontent.com/u/17927101?u=9261b9bb0c3e3bb1ecba43e8915dc58d8c9a077e&v=4 - url: https://github.com/jangia - - login: jackleeio - avatarUrl: https://avatars.githubusercontent.com/u/20477587?u=c5184dab6d021733d10c8f975b20e391856303d6&v=4 - url: https://github.com/jackleeio - - login: shuheng-liu - avatarUrl: https://avatars.githubusercontent.com/u/22414322?u=813c45f30786c6b511b21a661def025d8f7b609e&v=4 - url: https://github.com/shuheng-liu - - login: pers0n4 - avatarUrl: https://avatars.githubusercontent.com/u/24864600?u=f211a13a7b572cbbd7779b9c8d8cb428cc7ba07e&v=4 - url: https://github.com/pers0n4 - - login: curegit - avatarUrl: https://avatars.githubusercontent.com/u/37978051?u=1733c322079118c0cdc573c03d92813f50a9faec&v=4 - url: https://github.com/curegit - - login: fernandosmither - avatarUrl: https://avatars.githubusercontent.com/u/66154723?u=f79753eb207d01cca5bbb91ac62db6123e7622d1&v=4 - url: https://github.com/fernandosmither - - login: PunRabbit - avatarUrl: https://avatars.githubusercontent.com/u/70463212?u=1a835cfbc99295a60c8282f6aa6199d1b42241a5&v=4 - url: https://github.com/PunRabbit - - login: PelicanQ - avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4 - url: https://github.com/PelicanQ - - login: tahmarrrr23 - avatarUrl: https://avatars.githubusercontent.com/u/138208610?u=465a46b0ff72a74252d3e3a71ac7d2f1919cda28&v=4 - url: https://github.com/tahmarrrr23 - - login: zk-Call - avatarUrl: https://avatars.githubusercontent.com/u/147117264?v=4 - url: https://github.com/zk-Call - - login: kristiangronberg - avatarUrl: https://avatars.githubusercontent.com/u/42678548?v=4 - url: https://github.com/kristiangronberg - - login: leonardo-holguin - avatarUrl: https://avatars.githubusercontent.com/u/43093055?u=b59013d52fb6c4e0954aaaabc0882bd844985b38&v=4 - url: https://github.com/leonardo-holguin - - login: arrrrrmin - avatarUrl: https://avatars.githubusercontent.com/u/43553423?u=36a3880a6eb29309c19e6cadbb173bafbe91deb1&v=4 - url: https://github.com/arrrrrmin + - login: siavashyj + avatarUrl: https://avatars.githubusercontent.com/u/43583410?u=562005ddc7901cd27a1219a118a2363817b14977&v=4 + url: https://github.com/siavashyj - login: mobyw avatarUrl: https://avatars.githubusercontent.com/u/44370805?v=4 url: https://github.com/mobyw - login: ArtyomVancyan avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4 url: https://github.com/ArtyomVancyan - - login: harol97 - avatarUrl: https://avatars.githubusercontent.com/u/49042862?u=2b18e115ab73f5f09a280be2850f93c58a12e3d2&v=4 - url: https://github.com/harol97 + - login: TheR1D + avatarUrl: https://avatars.githubusercontent.com/u/16740832?u=b0dfdbdb27b79729430c71c6128962f77b7b53f7&v=4 + url: https://github.com/TheR1D + - login: joshuatz + avatarUrl: https://avatars.githubusercontent.com/u/17817563?u=f1bf05b690d1fc164218f0b420cdd3acb7913e21&v=4 + url: https://github.com/joshuatz + - login: SebTota + avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4 + url: https://github.com/SebTota + - login: nisutec + avatarUrl: https://avatars.githubusercontent.com/u/25281462?u=e562484c451fdfc59053163f64405f8eb262b8b0&v=4 + url: https://github.com/nisutec + - login: hoenie-ams + avatarUrl: https://avatars.githubusercontent.com/u/25708487?u=cda07434f0509ac728d9edf5e681117c0f6b818b&v=4 + url: https://github.com/hoenie-ams + - login: joerambo + avatarUrl: https://avatars.githubusercontent.com/u/26282974?v=4 + url: https://github.com/joerambo + - login: rlnchow + avatarUrl: https://avatars.githubusercontent.com/u/28018479?u=a93ca9cf1422b9ece155784a72d5f2fdbce7adff&v=4 + url: https://github.com/rlnchow + - login: dvlpjrs + avatarUrl: https://avatars.githubusercontent.com/u/32254642?u=fbd6ad0324d4f1eb6231cf775be1c7bd4404e961&v=4 + url: https://github.com/dvlpjrs + - login: caviri + avatarUrl: https://avatars.githubusercontent.com/u/45425937?u=4e14bd64282bad8f385eafbdb004b5a279366d6e&v=4 + url: https://github.com/caviri - login: hgalytoby avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=62c7ff3519858423579676cd0efbd7e3f1ffe63a&v=4 url: https://github.com/hgalytoby - login: conservative-dude avatarUrl: https://avatars.githubusercontent.com/u/55538308?u=f250c44942ea6e73a6bd90739b381c470c192c11&v=4 url: https://github.com/conservative-dude - - login: Joaopcamposs - avatarUrl: https://avatars.githubusercontent.com/u/57376574?u=699d5ba5ee66af1d089df6b5e532b97169e73650&v=4 - url: https://github.com/Joaopcamposs + - login: CR1337 + avatarUrl: https://avatars.githubusercontent.com/u/62649536?u=57a6aab10d2421a497306da8bcded01b826c54ae&v=4 + url: https://github.com/CR1337 + - login: PunRabbit + avatarUrl: https://avatars.githubusercontent.com/u/70463212?u=1a835cfbc99295a60c8282f6aa6199d1b42241a5&v=4 + url: https://github.com/PunRabbit + - login: PelicanQ + avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4 + url: https://github.com/PelicanQ + - login: tochikuji + avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4 + url: https://github.com/tochikuji - login: browniebroke avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4 url: https://github.com/browniebroke @@ -407,9 +377,12 @@ sponsors: - login: leobiscassi avatarUrl: https://avatars.githubusercontent.com/u/1977418?u=f9f82445a847ab479bd7223debd677fcac6c49a0&v=4 url: https://github.com/leobiscassi - - login: cbonoz - avatarUrl: https://avatars.githubusercontent.com/u/2351087?u=fd3e8030b2cc9fbfbb54a65e9890c548a016f58b&v=4 - url: https://github.com/cbonoz + - login: Alisa-lisa + avatarUrl: https://avatars.githubusercontent.com/u/4137964?u=e7e393504f554f4ff15863a1e01a5746863ef9ce&v=4 + url: https://github.com/Alisa-lisa + - login: Graeme22 + avatarUrl: https://avatars.githubusercontent.com/u/4185684?u=498182a42300d7bcd4de1215190cb17eb501136c&v=4 + url: https://github.com/Graeme22 - login: ddanier avatarUrl: https://avatars.githubusercontent.com/u/113563?u=ed1dc79de72f93bd78581f88ebc6952b62f472da&v=4 url: https://github.com/ddanier @@ -419,33 +392,15 @@ sponsors: - login: slafs avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4 url: https://github.com/slafs - - login: adamghill - avatarUrl: https://avatars.githubusercontent.com/u/317045?u=f1349d5ffe84a19f324e204777859fbf69ddf633&v=4 - url: https://github.com/adamghill + - login: ceb10n + avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 + url: https://github.com/ceb10n - login: eteq avatarUrl: https://avatars.githubusercontent.com/u/346587?v=4 url: https://github.com/eteq - - login: dmig - avatarUrl: https://avatars.githubusercontent.com/u/388564?v=4 - url: https://github.com/dmig - login: securancy avatarUrl: https://avatars.githubusercontent.com/u/606673?v=4 url: https://github.com/securancy - - login: tochikuji - avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4 - url: https://github.com/tochikuji - - login: KentShikama - avatarUrl: https://avatars.githubusercontent.com/u/6329898?u=8b236810db9b96333230430837e1f021f9246da1&v=4 - url: https://github.com/KentShikama - - login: katnoria - avatarUrl: https://avatars.githubusercontent.com/u/7674948?u=09767eb13e07e09496c5fee4e5ce21d9eac34a56&v=4 - url: https://github.com/katnoria - - login: harsh183 - avatarUrl: https://avatars.githubusercontent.com/u/7780198?v=4 - url: https://github.com/harsh183 - - login: hcristea - avatarUrl: https://avatars.githubusercontent.com/u/7814406?u=61d7a4fcf846983a4606788eac25e1c6c1209ba8&v=4 - url: https://github.com/hcristea - login: moonape1226 avatarUrl: https://avatars.githubusercontent.com/u/8532038?u=d9f8b855a429fff9397c3833c2ff83849ebf989d&v=4 url: https://github.com/moonape1226 @@ -453,7 +408,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/9369632?u=8c988f1b008a3f601385a3616f9327820f66e3a5&v=4 url: https://github.com/msehnout - login: xncbf - avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=2ef1ede118a72c170805f50b9ad07341fd16a354&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=a80a7bb349555b277645632ed66639ff43400614&v=4 url: https://github.com/xncbf - login: DMantis avatarUrl: https://avatars.githubusercontent.com/u/9536869?v=4 @@ -464,9 +419,6 @@ sponsors: - login: supdann avatarUrl: https://avatars.githubusercontent.com/u/9986994?u=9671810f4ae9504c063227fee34fd47567ff6954&v=4 url: https://github.com/supdann - - login: satwikkansal - avatarUrl: https://avatars.githubusercontent.com/u/10217535?u=b12d6ef74ea297de9e46da6933b1a5b7ba9e6a61&v=4 - url: https://github.com/satwikkansal - login: mntolia avatarUrl: https://avatars.githubusercontent.com/u/10390224?v=4 url: https://github.com/mntolia @@ -479,17 +431,14 @@ sponsors: - login: Zuzah avatarUrl: https://avatars.githubusercontent.com/u/10934846?u=1ef43e075ddc87bd1178372bf4d95ee6175cae27&v=4 url: https://github.com/Zuzah - - login: Alisa-lisa - avatarUrl: https://avatars.githubusercontent.com/u/4137964?u=e7e393504f554f4ff15863a1e01a5746863ef9ce&v=4 - url: https://github.com/Alisa-lisa - - login: Graeme22 - avatarUrl: https://avatars.githubusercontent.com/u/4185684?u=498182a42300d7bcd4de1215190cb17eb501136c&v=4 - url: https://github.com/Graeme22 + - login: artempronevskiy + avatarUrl: https://avatars.githubusercontent.com/u/12235104?u=03df6e1e55c9c6fe5d230adabb8dd7d43d8bbe8f&v=4 + url: https://github.com/artempronevskiy - login: danielunderwood avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4 url: https://github.com/danielunderwood - login: rangulvers - avatarUrl: https://avatars.githubusercontent.com/u/5235430?v=4 + avatarUrl: https://avatars.githubusercontent.com/u/5235430?u=e254d4af4ace5a05fa58372ae677c7d26f0d5a53&v=4 url: https://github.com/rangulvers - login: sdevkota avatarUrl: https://avatars.githubusercontent.com/u/5250987?u=4ed9a120c89805a8aefda1cbdc0cf6512e64d1b4&v=4 @@ -500,33 +449,42 @@ sponsors: - login: Baghdady92 avatarUrl: https://avatars.githubusercontent.com/u/5708590?v=4 url: https://github.com/Baghdady92 - - login: jakeecolution - avatarUrl: https://avatars.githubusercontent.com/u/5884696?u=4a7c7883fb064b593b50cb6697b54687e6f7aafe&v=4 - url: https://github.com/jakeecolution - - login: stephane-rbn - avatarUrl: https://avatars.githubusercontent.com/u/5939522?u=eb7ffe768fa3bcbcd04de14fe4a47444cc00ec4c&v=4 - url: https://github.com/stephane-rbn -- - login: danburonline - avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=94935cccfbec58083ab1e535212d54f1bf2c978a&v=4 - url: https://github.com/danburonline - - login: AliYmn - avatarUrl: https://avatars.githubusercontent.com/u/18416653?u=0de5a262e8b4dc0a08d065f30f7a39941e246530&v=4 - url: https://github.com/AliYmn - - login: sadikkuzu - avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=d179c06bb9f65c4167fcab118526819f8e0dac17&v=4 - url: https://github.com/sadikkuzu - - login: tran-hai-long - avatarUrl: https://avatars.githubusercontent.com/u/119793901?u=3b173a845dcf099b275bdc9713a69cbbc36040ce&v=4 - url: https://github.com/tran-hai-long + - login: KentShikama + avatarUrl: https://avatars.githubusercontent.com/u/6329898?u=8b236810db9b96333230430837e1f021f9246da1&v=4 + url: https://github.com/KentShikama + - login: katnoria + avatarUrl: https://avatars.githubusercontent.com/u/7674948?u=09767eb13e07e09496c5fee4e5ce21d9eac34a56&v=4 + url: https://github.com/katnoria + - login: harsh183 + avatarUrl: https://avatars.githubusercontent.com/u/7780198?v=4 + url: https://github.com/harsh183 + - login: hcristea + avatarUrl: https://avatars.githubusercontent.com/u/7814406?u=61d7a4fcf846983a4606788eac25e1c6c1209ba8&v=4 + url: https://github.com/hcristea +- - login: larsyngvelundin + avatarUrl: https://avatars.githubusercontent.com/u/34173819?u=74958599695bf83ac9f1addd935a51548a10c6b0&v=4 + url: https://github.com/larsyngvelundin + - login: andrecorumba + avatarUrl: https://avatars.githubusercontent.com/u/37807517?u=9b9be3b41da9bda60957da9ef37b50dbf65baa61&v=4 + url: https://github.com/andrecorumba - login: rwxd avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=cd04a39e3655923be4f25c2ba8a5a07b3da3230a&v=4 url: https://github.com/rwxd + - login: sadikkuzu + avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=d179c06bb9f65c4167fcab118526819f8e0dac17&v=4 + url: https://github.com/sadikkuzu + - login: Olegt0rr + avatarUrl: https://avatars.githubusercontent.com/u/25399456?u=3e87b5239a2f4600975ba13be73054f8567c6060&v=4 + url: https://github.com/Olegt0rr + - login: FabulousCodingFox + avatarUrl: https://avatars.githubusercontent.com/u/78906517?u=924a27cbee3db7e0ece5cc1509921402e1445e74&v=4 + url: https://github.com/FabulousCodingFox + - login: anqorithm + avatarUrl: https://avatars.githubusercontent.com/u/61029571?u=468256fa4e2d9ce2870b608299724bebb7a33f18&v=4 + url: https://github.com/anqorithm - login: ssbarnea - avatarUrl: https://avatars.githubusercontent.com/u/102495?u=c2efbf6fea2737e21dfc6b1113c4edc9644e9eaa&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/102495?u=c7bd9ddf127785286fc939dd18cb02db0a453bce&v=4 url: https://github.com/ssbarnea - - login: yuawn - avatarUrl: https://avatars.githubusercontent.com/u/5111198?u=5315576f3fe1a70fd2d0f02181588f4eea5d353d&v=4 - url: https://github.com/yuawn - - login: dongzhenye - avatarUrl: https://avatars.githubusercontent.com/u/5765843?u=fe420c9a4c41e5b060faaf44029f5485616b470d&v=4 - url: https://github.com/dongzhenye + - login: andreagrandi + avatarUrl: https://avatars.githubusercontent.com/u/636391?u=13d90cb8ec313593a5b71fbd4e33b78d6da736f5&v=4 + url: https://github.com/andreagrandi From 7e06c4c97f1c33431449dacf35c992170991c4b3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 18 Jan 2025 13:10:40 +0000 Subject: [PATCH 673/932] =?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 [skip ci] --- 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 404e3269a..f87e89af9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -85,6 +85,7 @@ hide: ### Internal +* 👥 Update FastAPI People - Sponsors. PR [#13231](https://github.com/fastapi/fastapi/pull/13231) by [@tiangolo](https://github.com/tiangolo). * 👷 Refactor FastAPI People Sponsors to use 2 tokens. PR [#13228](https://github.com/fastapi/fastapi/pull/13228) by [@tiangolo](https://github.com/tiangolo). * 👷 Update token for FastAPI People - Sponsors. PR [#13225](https://github.com/fastapi/fastapi/pull/13225) by [@tiangolo](https://github.com/tiangolo). * 👷 Add independent CI automation for FastAPI People - Sponsors. PR [#13221](https://github.com/fastapi/fastapi/pull/13221) by [@tiangolo](https://github.com/tiangolo). From 1cedd8becf0cb832d4fec05c2bb4babbca89b2a9 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 06:19:58 +0000 Subject: [PATCH 674/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20bo?= =?UTF-8?q?dy=5Fmultiple=5Fparams=20(#13170)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_tutorial001.py | 21 +- .../test_tutorial001_an.py | 206 ----------------- .../test_tutorial001_an_py310.py | 213 ------------------ .../test_tutorial001_an_py39.py | 213 ------------------ .../test_tutorial001_py310.py | 213 ------------------ 5 files changed, 17 insertions(+), 849 deletions(-) delete mode 100644 tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py delete mode 100644 tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py delete mode 100644 tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py delete mode 100644 tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py index 6275ebe95..142405595 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py @@ -1,13 +1,26 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient +from ...utils import needs_py39, needs_py310 + -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial001 import app +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.body_multiple_params.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py deleted file mode 100644 index 5cd3e2c4a..000000000 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py +++ /dev/null @@ -1,206 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial001_an import app - - client = TestClient(app) - return client - - -def test_post_body_q_bar_content(client: TestClient): - response = client.put("/items/5?q=bar", json={"name": "Foo", "price": 50.5}) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "q": "bar", - } - - -def test_post_no_body_q_bar(client: TestClient): - response = client.put("/items/5?q=bar", json=None) - assert response.status_code == 200 - assert response.json() == {"item_id": 5, "q": "bar"} - - -def test_post_no_body(client: TestClient): - response = client.put("/items/5", json=None) - assert response.status_code == 200 - assert response.json() == {"item_id": 5} - - -def test_post_id_foo(client: TestClient): - response = client.put("/items/foo", json=None) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "int_parsing", - "loc": ["path", "item_id"], - "msg": "Input should be a valid integer, unable to parse string as an integer", - "input": "foo", - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["path", "item_id"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] - } - ) - - -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": { - "title": "The ID of the item to get", - "maximum": 1000.0, - "minimum": 0.0, - "type": "integer", - }, - "name": "item_id", - "in": "path", - }, - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "anyOf": [ - {"$ref": "#/components/schemas/Item"}, - {"type": "null"}, - ], - "title": "Item", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"$ref": "#/components/schemas/Item"} - ) - } - } - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py deleted file mode 100644 index 0173ab21b..000000000 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py +++ /dev/null @@ -1,213 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial001_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_body_q_bar_content(client: TestClient): - response = client.put("/items/5?q=bar", json={"name": "Foo", "price": 50.5}) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "q": "bar", - } - - -@needs_py310 -def test_post_no_body_q_bar(client: TestClient): - response = client.put("/items/5?q=bar", json=None) - assert response.status_code == 200 - assert response.json() == {"item_id": 5, "q": "bar"} - - -@needs_py310 -def test_post_no_body(client: TestClient): - response = client.put("/items/5", json=None) - assert response.status_code == 200 - assert response.json() == {"item_id": 5} - - -@needs_py310 -def test_post_id_foo(client: TestClient): - response = client.put("/items/foo", json=None) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "int_parsing", - "loc": ["path", "item_id"], - "msg": "Input should be a valid integer, unable to parse string as an integer", - "input": "foo", - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["path", "item_id"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": { - "title": "The ID of the item to get", - "maximum": 1000.0, - "minimum": 0.0, - "type": "integer", - }, - "name": "item_id", - "in": "path", - }, - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "anyOf": [ - {"$ref": "#/components/schemas/Item"}, - {"type": "null"}, - ], - "title": "Item", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"$ref": "#/components/schemas/Item"} - ) - } - } - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py deleted file mode 100644 index cda19918a..000000000 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py +++ /dev/null @@ -1,213 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_body_q_bar_content(client: TestClient): - response = client.put("/items/5?q=bar", json={"name": "Foo", "price": 50.5}) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "q": "bar", - } - - -@needs_py39 -def test_post_no_body_q_bar(client: TestClient): - response = client.put("/items/5?q=bar", json=None) - assert response.status_code == 200 - assert response.json() == {"item_id": 5, "q": "bar"} - - -@needs_py39 -def test_post_no_body(client: TestClient): - response = client.put("/items/5", json=None) - assert response.status_code == 200 - assert response.json() == {"item_id": 5} - - -@needs_py39 -def test_post_id_foo(client: TestClient): - response = client.put("/items/foo", json=None) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "int_parsing", - "loc": ["path", "item_id"], - "msg": "Input should be a valid integer, unable to parse string as an integer", - "input": "foo", - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["path", "item_id"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] - } - ) - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": { - "title": "The ID of the item to get", - "maximum": 1000.0, - "minimum": 0.0, - "type": "integer", - }, - "name": "item_id", - "in": "path", - }, - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "anyOf": [ - {"$ref": "#/components/schemas/Item"}, - {"type": "null"}, - ], - "title": "Item", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"$ref": "#/components/schemas/Item"} - ) - } - } - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py deleted file mode 100644 index 663291933..000000000 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py +++ /dev/null @@ -1,213 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_body_q_bar_content(client: TestClient): - response = client.put("/items/5?q=bar", json={"name": "Foo", "price": 50.5}) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "q": "bar", - } - - -@needs_py310 -def test_post_no_body_q_bar(client: TestClient): - response = client.put("/items/5?q=bar", json=None) - assert response.status_code == 200 - assert response.json() == {"item_id": 5, "q": "bar"} - - -@needs_py310 -def test_post_no_body(client: TestClient): - response = client.put("/items/5", json=None) - assert response.status_code == 200 - assert response.json() == {"item_id": 5} - - -@needs_py310 -def test_post_id_foo(client: TestClient): - response = client.put("/items/foo", json=None) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "int_parsing", - "loc": ["path", "item_id"], - "msg": "Input should be a valid integer, unable to parse string as an integer", - "input": "foo", - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["path", "item_id"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": { - "title": "The ID of the item to get", - "maximum": 1000.0, - "minimum": 0.0, - "type": "integer", - }, - "name": "item_id", - "in": "path", - }, - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "anyOf": [ - {"$ref": "#/components/schemas/Item"}, - {"type": "null"}, - ], - "title": "Item", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"$ref": "#/components/schemas/Item"} - ) - } - } - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } From 4191f4d33a11d3d9c4d996c6d92314f03b43d28e Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 06:20:23 +0000 Subject: [PATCH 675/932] =?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 [skip ci] --- 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 f87e89af9..a0863e72f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for body_multiple_params. PR [#13170](https://github.com/fastapi/fastapi/pull/13170) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for body_fields. PR [#13169](https://github.com/fastapi/fastapi/pull/13169) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for body. PR [#13168](https://github.com/fastapi/fastapi/pull/13168) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for bigger_applications. PR [#13167](https://github.com/fastapi/fastapi/pull/13167) by [@alejsdev](https://github.com/alejsdev). From 55ef9270b8821377402231064ba1da5cfe2a626e Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 06:20:41 +0000 Subject: [PATCH 676/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20bo?= =?UTF-8?q?dy=5Fnested=5Fmodels=20(#13171)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_tutorial009.py | 18 ++- .../test_tutorial009_py39.py | 128 ------------------ 2 files changed, 14 insertions(+), 132 deletions(-) delete mode 100644 tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial009.py b/tests/test_tutorial/test_body_nested_models/test_tutorial009.py index 762073aea..38ba3c887 100644 --- a/tests/test_tutorial/test_body_nested_models/test_tutorial009.py +++ b/tests/test_tutorial/test_body_nested_models/test_tutorial009.py @@ -1,13 +1,23 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient +from ...utils import needs_py39 + -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_nested_models.tutorial009 import app +@pytest.fixture( + name="client", + params=[ + "tutorial009", + pytest.param("tutorial009_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.body_nested_models.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py b/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py deleted file mode 100644 index 24623cecc..000000000 --- a/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py +++ /dev/null @@ -1,128 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_nested_models.tutorial009_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_body(client: TestClient): - data = {"2": 2.2, "3": 3.3} - response = client.post("/index-weights/", json=data) - assert response.status_code == 200, response.text - assert response.json() == data - - -@needs_py39 -def test_post_invalid_body(client: TestClient): - data = {"foo": 2.2, "3": 3.3} - response = client.post("/index-weights/", json=data) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "int_parsing", - "loc": ["body", "foo", "[key]"], - "msg": "Input should be a valid integer, unable to parse string as an integer", - "input": "foo", - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "__key__"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] - } - ) - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/index-weights/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Index Weights", - "operationId": "create_index_weights_index_weights__post", - "requestBody": { - "content": { - "application/json": { - "schema": { - "title": "Weights", - "type": "object", - "additionalProperties": {"type": "number"}, - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } From f30dd4fe40ee3c70a906b2693f0d23832ab45508 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 06:21:05 +0000 Subject: [PATCH 677/932] =?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 [skip ci] --- 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 a0863e72f..3063be8d6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for body_nested_models. PR [#13171](https://github.com/fastapi/fastapi/pull/13171) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for body_multiple_params. PR [#13170](https://github.com/fastapi/fastapi/pull/13170) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for body_fields. PR [#13169](https://github.com/fastapi/fastapi/pull/13169) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for body. PR [#13168](https://github.com/fastapi/fastapi/pull/13168) by [@alejsdev](https://github.com/alejsdev). From 0a882e926e30af050a9557721ec1f726500972ba Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 06:21:30 +0000 Subject: [PATCH 678/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20bo?= =?UTF-8?q?dy=5Fupdates=20(#13172)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_body_updates/test_tutorial001.py | 19 +- .../test_tutorial001_py310.py | 317 ------------------ .../test_tutorial001_py39.py | 317 ------------------ 3 files changed, 14 insertions(+), 639 deletions(-) delete mode 100644 tests/test_tutorial/test_body_updates/test_tutorial001_py310.py delete mode 100644 tests/test_tutorial/test_body_updates/test_tutorial001_py39.py diff --git a/tests/test_tutorial/test_body_updates/test_tutorial001.py b/tests/test_tutorial/test_body_updates/test_tutorial001.py index e586534a0..f874dc9bd 100644 --- a/tests/test_tutorial/test_body_updates/test_tutorial001.py +++ b/tests/test_tutorial/test_body_updates/test_tutorial001.py @@ -1,14 +1,23 @@ +import importlib + import pytest from fastapi.testclient import TestClient -from ...utils import needs_pydanticv1, needs_pydanticv2 +from ...utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2 -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_updates.tutorial001 import app +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + pytest.param("tutorial001_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.body_updates.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_body_updates/test_tutorial001_py310.py b/tests/test_tutorial/test_body_updates/test_tutorial001_py310.py deleted file mode 100644 index 6bc969d43..000000000 --- a/tests/test_tutorial/test_body_updates/test_tutorial001_py310.py +++ /dev/null @@ -1,317 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv1, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_updates.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_get(client: TestClient): - response = client.get("/items/baz") - assert response.status_code == 200, response.text - assert response.json() == { - "name": "Baz", - "description": None, - "price": 50.2, - "tax": 10.5, - "tags": [], - } - - -@needs_py310 -def test_put(client: TestClient): - response = client.put( - "/items/bar", json={"name": "Barz", "price": 3, "description": None} - ) - assert response.json() == { - "name": "Barz", - "description": None, - "price": 3, - "tax": 10.5, - "tags": [], - } - - -@needs_py310 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item", - "operationId": "read_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - }, - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - }, - } - }, - "components": { - "schemas": { - "Item": { - "type": "object", - "title": "Item", - "properties": { - "name": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Name", - }, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - "price": { - "anyOf": [{"type": "number"}, {"type": "null"}], - "title": "Price", - }, - "tax": {"title": "Tax", "type": "number", "default": 10.5}, - "tags": { - "title": "Tags", - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_py310 -@needs_pydanticv1 -def test_openapi_schema_pv1(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item", - "operationId": "read_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - }, - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - }, - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": {"title": "Description", "type": "string"}, - "price": {"title": "Price", "type": "number"}, - "tax": {"title": "Tax", "type": "number", "default": 10.5}, - "tags": { - "title": "Tags", - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_updates/test_tutorial001_py39.py b/tests/test_tutorial/test_body_updates/test_tutorial001_py39.py deleted file mode 100644 index a1edb3370..000000000 --- a/tests/test_tutorial/test_body_updates/test_tutorial001_py39.py +++ /dev/null @@ -1,317 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39, needs_pydanticv1, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_updates.tutorial001_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_get(client: TestClient): - response = client.get("/items/baz") - assert response.status_code == 200, response.text - assert response.json() == { - "name": "Baz", - "description": None, - "price": 50.2, - "tax": 10.5, - "tags": [], - } - - -@needs_py39 -def test_put(client: TestClient): - response = client.put( - "/items/bar", json={"name": "Barz", "price": 3, "description": None} - ) - assert response.json() == { - "name": "Barz", - "description": None, - "price": 3, - "tax": 10.5, - "tags": [], - } - - -@needs_py39 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item", - "operationId": "read_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - }, - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - }, - } - }, - "components": { - "schemas": { - "Item": { - "type": "object", - "title": "Item", - "properties": { - "name": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Name", - }, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - "price": { - "anyOf": [{"type": "number"}, {"type": "null"}], - "title": "Price", - }, - "tax": {"title": "Tax", "type": "number", "default": 10.5}, - "tags": { - "title": "Tags", - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_py39 -@needs_pydanticv1 -def test_openapi_schema_pv1(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item", - "operationId": "read_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - }, - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - }, - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": {"title": "Description", "type": "string"}, - "price": {"title": "Price", "type": "number"}, - "tax": {"title": "Tax", "type": "number", "default": 10.5}, - "tags": { - "title": "Tags", - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } From c0fddaa9a9431c3d5292bb9728bdcb62cfc3a1c9 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 06:21:52 +0000 Subject: [PATCH 679/932] =?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 [skip ci] --- 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 3063be8d6..2b46bb38e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for body_updates. PR [#13172](https://github.com/fastapi/fastapi/pull/13172) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for body_nested_models. PR [#13171](https://github.com/fastapi/fastapi/pull/13171) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for body_multiple_params. PR [#13170](https://github.com/fastapi/fastapi/pull/13170) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for body_fields. PR [#13169](https://github.com/fastapi/fastapi/pull/13169) by [@alejsdev](https://github.com/alejsdev). From 920df4d1ac3bba3ac14ac61ccd330d88975d7849 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 06:25:51 +0000 Subject: [PATCH 680/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20de?= =?UTF-8?q?pendencies=20(#13174)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_dependencies/test_tutorial001.py | 25 +- .../test_dependencies/test_tutorial001_an.py | 183 ------------ .../test_tutorial001_an_py310.py | 191 ------------- .../test_tutorial001_an_py39.py | 191 ------------- .../test_tutorial001_py310.py | 191 ------------- .../test_dependencies/test_tutorial004.py | 25 +- .../test_dependencies/test_tutorial004_an.py | 162 ----------- .../test_tutorial004_an_py310.py | 170 ----------- .../test_tutorial004_an_py39.py | 170 ----------- .../test_tutorial004_py310.py | 170 ----------- .../test_dependencies/test_tutorial006.py | 30 +- .../test_dependencies/test_tutorial006_an.py | 149 ---------- .../test_tutorial006_an_py39.py | 161 ----------- .../test_dependencies/test_tutorial008b.py | 26 +- .../test_dependencies/test_tutorial008b_an.py | 23 -- .../test_tutorial008b_an_py39.py | 33 --- .../test_dependencies/test_tutorial008c.py | 36 ++- .../test_dependencies/test_tutorial008c_an.py | 38 --- .../test_tutorial008c_an_py39.py | 44 --- .../test_dependencies/test_tutorial008d.py | 40 ++- .../test_dependencies/test_tutorial008d_an.py | 41 --- .../test_tutorial008d_an_py39.py | 47 ---- .../test_dependencies/test_tutorial012.py | 38 ++- .../test_dependencies/test_tutorial012_an.py | 250 ---------------- .../test_tutorial012_an_py39.py | 266 ------------------ 25 files changed, 162 insertions(+), 2538 deletions(-) delete mode 100644 tests/test_tutorial/test_dependencies/test_tutorial001_an.py delete mode 100644 tests/test_tutorial/test_dependencies/test_tutorial001_an_py310.py delete mode 100644 tests/test_tutorial/test_dependencies/test_tutorial001_an_py39.py delete mode 100644 tests/test_tutorial/test_dependencies/test_tutorial001_py310.py delete mode 100644 tests/test_tutorial/test_dependencies/test_tutorial004_an.py delete mode 100644 tests/test_tutorial/test_dependencies/test_tutorial004_an_py310.py delete mode 100644 tests/test_tutorial/test_dependencies/test_tutorial004_an_py39.py delete mode 100644 tests/test_tutorial/test_dependencies/test_tutorial004_py310.py delete mode 100644 tests/test_tutorial/test_dependencies/test_tutorial006_an.py delete mode 100644 tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py delete mode 100644 tests/test_tutorial/test_dependencies/test_tutorial008b_an.py delete mode 100644 tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py delete mode 100644 tests/test_tutorial/test_dependencies/test_tutorial008c_an.py delete mode 100644 tests/test_tutorial/test_dependencies/test_tutorial008c_an_py39.py delete mode 100644 tests/test_tutorial/test_dependencies/test_tutorial008d_an.py delete mode 100644 tests/test_tutorial/test_dependencies/test_tutorial008d_an_py39.py delete mode 100644 tests/test_tutorial/test_dependencies/test_tutorial012_an.py delete mode 100644 tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py diff --git a/tests/test_tutorial/test_dependencies/test_tutorial001.py b/tests/test_tutorial/test_dependencies/test_tutorial001.py index d1324a641..ed9944912 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial001.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial001.py @@ -1,10 +1,27 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.dependencies.tutorial001 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.dependencies.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client @pytest.mark.parametrize( @@ -17,13 +34,13 @@ client = TestClient(app) ("/users", 200, {"q": None, "skip": 0, "limit": 100}), ], ) -def test_get(path, expected_status, expected_response): +def test_get(path, expected_status, expected_response, client: TestClient): response = client.get(path) assert response.status_code == expected_status assert response.json() == expected_response -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_dependencies/test_tutorial001_an.py b/tests/test_tutorial/test_dependencies/test_tutorial001_an.py deleted file mode 100644 index 79c2a1e10..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial001_an.py +++ /dev/null @@ -1,183 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.dependencies.tutorial001_an import app - -client = TestClient(app) - - -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ("/items", 200, {"q": None, "skip": 0, "limit": 100}), - ("/items?q=foo", 200, {"q": "foo", "skip": 0, "limit": 100}), - ("/items?q=foo&skip=5", 200, {"q": "foo", "skip": 5, "limit": 100}), - ("/items?q=foo&skip=5&limit=30", 200, {"q": "foo", "skip": 5, "limit": 30}), - ("/users", 200, {"q": None, "skip": 0, "limit": 100}), - ], -) -def test_get(path, expected_status, expected_response): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial001_an_py310.py b/tests/test_tutorial/test_dependencies/test_tutorial001_an_py310.py deleted file mode 100644 index 7db55a1c5..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial001_an_py310.py +++ /dev/null @@ -1,191 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial001_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ("/items", 200, {"q": None, "skip": 0, "limit": 100}), - ("/items?q=foo", 200, {"q": "foo", "skip": 0, "limit": 100}), - ("/items?q=foo&skip=5", 200, {"q": "foo", "skip": 5, "limit": 100}), - ("/items?q=foo&skip=5&limit=30", 200, {"q": "foo", "skip": 5, "limit": 30}), - ("/users", 200, {"q": None, "skip": 0, "limit": 100}), - ], -) -def test_get(path, expected_status, expected_response, client: TestClient): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial001_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial001_an_py39.py deleted file mode 100644 index 68c2dedb1..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial001_an_py39.py +++ /dev/null @@ -1,191 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ("/items", 200, {"q": None, "skip": 0, "limit": 100}), - ("/items?q=foo", 200, {"q": "foo", "skip": 0, "limit": 100}), - ("/items?q=foo&skip=5", 200, {"q": "foo", "skip": 5, "limit": 100}), - ("/items?q=foo&skip=5&limit=30", 200, {"q": "foo", "skip": 5, "limit": 30}), - ("/users", 200, {"q": None, "skip": 0, "limit": 100}), - ], -) -def test_get(path, expected_status, expected_response, client: TestClient): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial001_py310.py b/tests/test_tutorial/test_dependencies/test_tutorial001_py310.py deleted file mode 100644 index 381eecb63..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial001_py310.py +++ /dev/null @@ -1,191 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ("/items", 200, {"q": None, "skip": 0, "limit": 100}), - ("/items?q=foo", 200, {"q": "foo", "skip": 0, "limit": 100}), - ("/items?q=foo&skip=5", 200, {"q": "foo", "skip": 5, "limit": 100}), - ("/items?q=foo&skip=5&limit=30", 200, {"q": "foo", "skip": 5, "limit": 30}), - ("/users", 200, {"q": None, "skip": 0, "limit": 100}), - ], -) -def test_get(path, expected_status, expected_response, client: TestClient): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial004.py b/tests/test_tutorial/test_dependencies/test_tutorial004.py index 5c5d34cfc..8221c83d4 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial004.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial004.py @@ -1,10 +1,27 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.dependencies.tutorial004 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial004", + pytest.param("tutorial004_py310", marks=needs_py310), + "tutorial004_an", + pytest.param("tutorial004_an_py39", marks=needs_py39), + pytest.param("tutorial004_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.dependencies.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client @pytest.mark.parametrize( @@ -55,13 +72,13 @@ client = TestClient(app) ), ], ) -def test_get(path, expected_status, expected_response): +def test_get(path, expected_status, expected_response, client: TestClient): response = client.get(path) assert response.status_code == expected_status assert response.json() == expected_response -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_dependencies/test_tutorial004_an.py b/tests/test_tutorial/test_dependencies/test_tutorial004_an.py deleted file mode 100644 index c5c1a1fb8..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial004_an.py +++ /dev/null @@ -1,162 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.dependencies.tutorial004_an import app - -client = TestClient(app) - - -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ( - "/items", - 200, - { - "items": [ - {"item_name": "Foo"}, - {"item_name": "Bar"}, - {"item_name": "Baz"}, - ] - }, - ), - ( - "/items?q=foo", - 200, - { - "items": [ - {"item_name": "Foo"}, - {"item_name": "Bar"}, - {"item_name": "Baz"}, - ], - "q": "foo", - }, - ), - ( - "/items?q=foo&skip=1", - 200, - {"items": [{"item_name": "Bar"}, {"item_name": "Baz"}], "q": "foo"}, - ), - ( - "/items?q=bar&limit=2", - 200, - {"items": [{"item_name": "Foo"}, {"item_name": "Bar"}], "q": "bar"}, - ), - ( - "/items?q=bar&skip=1&limit=1", - 200, - {"items": [{"item_name": "Bar"}], "q": "bar"}, - ), - ( - "/items?limit=1&q=bar&skip=1", - 200, - {"items": [{"item_name": "Bar"}], "q": "bar"}, - ), - ], -) -def test_get(path, expected_status, expected_response): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial004_an_py310.py b/tests/test_tutorial/test_dependencies/test_tutorial004_an_py310.py deleted file mode 100644 index 6fd093ddb..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial004_an_py310.py +++ /dev/null @@ -1,170 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial004_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ( - "/items", - 200, - { - "items": [ - {"item_name": "Foo"}, - {"item_name": "Bar"}, - {"item_name": "Baz"}, - ] - }, - ), - ( - "/items?q=foo", - 200, - { - "items": [ - {"item_name": "Foo"}, - {"item_name": "Bar"}, - {"item_name": "Baz"}, - ], - "q": "foo", - }, - ), - ( - "/items?q=foo&skip=1", - 200, - {"items": [{"item_name": "Bar"}, {"item_name": "Baz"}], "q": "foo"}, - ), - ( - "/items?q=bar&limit=2", - 200, - {"items": [{"item_name": "Foo"}, {"item_name": "Bar"}], "q": "bar"}, - ), - ( - "/items?q=bar&skip=1&limit=1", - 200, - {"items": [{"item_name": "Bar"}], "q": "bar"}, - ), - ( - "/items?limit=1&q=bar&skip=1", - 200, - {"items": [{"item_name": "Bar"}], "q": "bar"}, - ), - ], -) -def test_get(path, expected_status, expected_response, client: TestClient): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial004_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial004_an_py39.py deleted file mode 100644 index fbbe84cc9..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial004_an_py39.py +++ /dev/null @@ -1,170 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial004_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ( - "/items", - 200, - { - "items": [ - {"item_name": "Foo"}, - {"item_name": "Bar"}, - {"item_name": "Baz"}, - ] - }, - ), - ( - "/items?q=foo", - 200, - { - "items": [ - {"item_name": "Foo"}, - {"item_name": "Bar"}, - {"item_name": "Baz"}, - ], - "q": "foo", - }, - ), - ( - "/items?q=foo&skip=1", - 200, - {"items": [{"item_name": "Bar"}, {"item_name": "Baz"}], "q": "foo"}, - ), - ( - "/items?q=bar&limit=2", - 200, - {"items": [{"item_name": "Foo"}, {"item_name": "Bar"}], "q": "bar"}, - ), - ( - "/items?q=bar&skip=1&limit=1", - 200, - {"items": [{"item_name": "Bar"}], "q": "bar"}, - ), - ( - "/items?limit=1&q=bar&skip=1", - 200, - {"items": [{"item_name": "Bar"}], "q": "bar"}, - ), - ], -) -def test_get(path, expected_status, expected_response, client: TestClient): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial004_py310.py b/tests/test_tutorial/test_dependencies/test_tutorial004_py310.py deleted file mode 100644 index 845b098e7..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial004_py310.py +++ /dev/null @@ -1,170 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial004_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ( - "/items", - 200, - { - "items": [ - {"item_name": "Foo"}, - {"item_name": "Bar"}, - {"item_name": "Baz"}, - ] - }, - ), - ( - "/items?q=foo", - 200, - { - "items": [ - {"item_name": "Foo"}, - {"item_name": "Bar"}, - {"item_name": "Baz"}, - ], - "q": "foo", - }, - ), - ( - "/items?q=foo&skip=1", - 200, - {"items": [{"item_name": "Bar"}, {"item_name": "Baz"}], "q": "foo"}, - ), - ( - "/items?q=bar&limit=2", - 200, - {"items": [{"item_name": "Foo"}, {"item_name": "Bar"}], "q": "bar"}, - ), - ( - "/items?q=bar&skip=1&limit=1", - 200, - {"items": [{"item_name": "Bar"}], "q": "bar"}, - ), - ( - "/items?limit=1&q=bar&skip=1", - 200, - {"items": [{"item_name": "Bar"}], "q": "bar"}, - ), - ], -) -def test_get(path, expected_status, expected_response, client: TestClient): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006.py b/tests/test_tutorial/test_dependencies/test_tutorial006.py index 5f14d9a3b..4530762f7 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial006.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial006.py @@ -1,12 +1,28 @@ +import importlib + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.dependencies.tutorial006 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial006", + "tutorial006_an", + pytest.param("tutorial006_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.dependencies.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_get_no_headers(): +def test_get_no_headers(client: TestClient): response = client.get("/items/") assert response.status_code == 422, response.text assert response.json() == IsDict( @@ -45,13 +61,13 @@ def test_get_no_headers(): ) -def test_get_invalid_one_header(): +def test_get_invalid_one_header(client: TestClient): response = client.get("/items/", headers={"X-Token": "invalid"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "X-Token header invalid"} -def test_get_invalid_second_header(): +def test_get_invalid_second_header(client: TestClient): response = client.get( "/items/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"} ) @@ -59,7 +75,7 @@ def test_get_invalid_second_header(): assert response.json() == {"detail": "X-Key header invalid"} -def test_get_valid_headers(): +def test_get_valid_headers(client: TestClient): response = client.get( "/items/", headers={ @@ -71,7 +87,7 @@ def test_get_valid_headers(): assert response.json() == [{"item": "Foo"}, {"item": "Bar"}] -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006_an.py b/tests/test_tutorial/test_dependencies/test_tutorial006_an.py deleted file mode 100644 index a307ff808..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial006_an.py +++ /dev/null @@ -1,149 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.dependencies.tutorial006_an import app - -client = TestClient(app) - - -def test_get_no_headers(): - response = client.get("/items/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["header", "x-key"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_get_invalid_one_header(): - response = client.get("/items/", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -def test_get_invalid_second_header(): - response = client.get( - "/items/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Key header invalid"} - - -def test_get_valid_headers(): - response = client.get( - "/items/", - headers={ - "X-Token": "fake-super-secret-token", - "X-Key": "fake-super-secret-key", - }, - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item": "Foo"}, {"item": "Bar"}] - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - { - "required": True, - "schema": {"title": "X-Key", "type": "string"}, - "name": "x-key", - "in": "header", - }, - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py deleted file mode 100644 index b41b1537e..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py +++ /dev/null @@ -1,161 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial006_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_get_no_headers(client: TestClient): - response = client.get("/items/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["header", "x-key"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_get_invalid_one_header(client: TestClient): - response = client.get("/items/", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -@needs_py39 -def test_get_invalid_second_header(client: TestClient): - response = client.get( - "/items/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Key header invalid"} - - -@needs_py39 -def test_get_valid_headers(client: TestClient): - response = client.get( - "/items/", - headers={ - "X-Token": "fake-super-secret-token", - "X-Key": "fake-super-secret-key", - }, - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item": "Foo"}, {"item": "Bar"}] - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - { - "required": True, - "schema": {"title": "X-Key", "type": "string"}, - "name": "x-key", - "in": "header", - }, - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b.py b/tests/test_tutorial/test_dependencies/test_tutorial008b.py index 86acba9e4..4d7092265 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial008b.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial008b.py @@ -1,23 +1,39 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.dependencies.tutorial008b import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial008b", + "tutorial008b_an", + pytest.param("tutorial008b_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.dependencies.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_get_no_item(): +def test_get_no_item(client: TestClient): response = client.get("/items/foo") assert response.status_code == 404, response.text assert response.json() == {"detail": "Item not found"} -def test_owner_error(): +def test_owner_error(client: TestClient): response = client.get("/items/plumbus") assert response.status_code == 400, response.text assert response.json() == {"detail": "Owner error: Rick"} -def test_get_item(): +def test_get_item(client: TestClient): response = client.get("/items/portal-gun") assert response.status_code == 200, response.text assert response.json() == {"description": "Gun to create portals", "owner": "Rick"} diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py b/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py deleted file mode 100644 index 7f51fc52a..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py +++ /dev/null @@ -1,23 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.dependencies.tutorial008b_an import app - -client = TestClient(app) - - -def test_get_no_item(): - response = client.get("/items/foo") - assert response.status_code == 404, response.text - assert response.json() == {"detail": "Item not found"} - - -def test_owner_error(): - response = client.get("/items/plumbus") - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Owner error: Rick"} - - -def test_get_item(): - response = client.get("/items/portal-gun") - assert response.status_code == 200, response.text - assert response.json() == {"description": "Gun to create portals", "owner": "Rick"} diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py deleted file mode 100644 index 7d24809a8..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py +++ /dev/null @@ -1,33 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial008b_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_get_no_item(client: TestClient): - response = client.get("/items/foo") - assert response.status_code == 404, response.text - assert response.json() == {"detail": "Item not found"} - - -@needs_py39 -def test_owner_error(client: TestClient): - response = client.get("/items/plumbus") - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Owner error: Rick"} - - -@needs_py39 -def test_get_item(client: TestClient): - response = client.get("/items/portal-gun") - assert response.status_code == 200, response.text - assert response.json() == {"description": "Gun to create portals", "owner": "Rick"} diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008c.py b/tests/test_tutorial/test_dependencies/test_tutorial008c.py index 27be8895a..11e96bf46 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial008c.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial008c.py @@ -1,38 +1,50 @@ +import importlib +from types import ModuleType + import pytest from fastapi.exceptions import FastAPIError from fastapi.testclient import TestClient +from ...utils import needs_py39 + -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial008c import app +@pytest.fixture( + name="mod", + params=[ + "tutorial008c", + "tutorial008c_an", + pytest.param("tutorial008c_an_py39", marks=needs_py39), + ], +) +def get_mod(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.dependencies.{request.param}") - client = TestClient(app) - return client + return mod -def test_get_no_item(client: TestClient): +def test_get_no_item(mod: ModuleType): + client = TestClient(mod.app) response = client.get("/items/foo") assert response.status_code == 404, response.text assert response.json() == {"detail": "Item not found, there's only a plumbus here"} -def test_get(client: TestClient): +def test_get(mod: ModuleType): + client = TestClient(mod.app) response = client.get("/items/plumbus") assert response.status_code == 200, response.text assert response.json() == "plumbus" -def test_fastapi_error(client: TestClient): +def test_fastapi_error(mod: ModuleType): + client = TestClient(mod.app) with pytest.raises(FastAPIError) as exc_info: client.get("/items/portal-gun") assert "No response object was returned" in exc_info.value.args[0] -def test_internal_server_error(): - from docs_src.dependencies.tutorial008c import app - - client = TestClient(app, raise_server_exceptions=False) +def test_internal_server_error(mod: ModuleType): + client = TestClient(mod.app, raise_server_exceptions=False) response = client.get("/items/portal-gun") assert response.status_code == 500, response.text assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008c_an.py b/tests/test_tutorial/test_dependencies/test_tutorial008c_an.py deleted file mode 100644 index 10fa1ab50..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial008c_an.py +++ /dev/null @@ -1,38 +0,0 @@ -import pytest -from fastapi.exceptions import FastAPIError -from fastapi.testclient import TestClient - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial008c_an import app - - client = TestClient(app) - return client - - -def test_get_no_item(client: TestClient): - response = client.get("/items/foo") - assert response.status_code == 404, response.text - assert response.json() == {"detail": "Item not found, there's only a plumbus here"} - - -def test_get(client: TestClient): - response = client.get("/items/plumbus") - assert response.status_code == 200, response.text - assert response.json() == "plumbus" - - -def test_fastapi_error(client: TestClient): - with pytest.raises(FastAPIError) as exc_info: - client.get("/items/portal-gun") - assert "No response object was returned" in exc_info.value.args[0] - - -def test_internal_server_error(): - from docs_src.dependencies.tutorial008c_an import app - - client = TestClient(app, raise_server_exceptions=False) - response = client.get("/items/portal-gun") - assert response.status_code == 500, response.text - assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008c_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial008c_an_py39.py deleted file mode 100644 index 6c3acff50..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial008c_an_py39.py +++ /dev/null @@ -1,44 +0,0 @@ -import pytest -from fastapi.exceptions import FastAPIError -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial008c_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_get_no_item(client: TestClient): - response = client.get("/items/foo") - assert response.status_code == 404, response.text - assert response.json() == {"detail": "Item not found, there's only a plumbus here"} - - -@needs_py39 -def test_get(client: TestClient): - response = client.get("/items/plumbus") - assert response.status_code == 200, response.text - assert response.json() == "plumbus" - - -@needs_py39 -def test_fastapi_error(client: TestClient): - with pytest.raises(FastAPIError) as exc_info: - client.get("/items/portal-gun") - assert "No response object was returned" in exc_info.value.args[0] - - -@needs_py39 -def test_internal_server_error(): - from docs_src.dependencies.tutorial008c_an_py39 import app - - client = TestClient(app, raise_server_exceptions=False) - response = client.get("/items/portal-gun") - assert response.status_code == 500, response.text - assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008d.py b/tests/test_tutorial/test_dependencies/test_tutorial008d.py index 043496112..bc99bb383 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial008d.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial008d.py @@ -1,41 +1,51 @@ +import importlib +from types import ModuleType + import pytest from fastapi.testclient import TestClient +from ...utils import needs_py39 + -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial008d import app +@pytest.fixture( + name="mod", + params=[ + "tutorial008d", + "tutorial008d_an", + pytest.param("tutorial008d_an_py39", marks=needs_py39), + ], +) +def get_mod(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.dependencies.{request.param}") - client = TestClient(app) - return client + return mod -def test_get_no_item(client: TestClient): +def test_get_no_item(mod: ModuleType): + client = TestClient(mod.app) response = client.get("/items/foo") assert response.status_code == 404, response.text assert response.json() == {"detail": "Item not found, there's only a plumbus here"} -def test_get(client: TestClient): +def test_get(mod: ModuleType): + client = TestClient(mod.app) response = client.get("/items/plumbus") assert response.status_code == 200, response.text assert response.json() == "plumbus" -def test_internal_error(client: TestClient): - from docs_src.dependencies.tutorial008d import InternalError - - with pytest.raises(InternalError) as exc_info: +def test_internal_error(mod: ModuleType): + client = TestClient(mod.app) + with pytest.raises(mod.InternalError) as exc_info: client.get("/items/portal-gun") assert ( exc_info.value.args[0] == "The portal gun is too dangerous to be owned by Rick" ) -def test_internal_server_error(): - from docs_src.dependencies.tutorial008d import app - - client = TestClient(app, raise_server_exceptions=False) +def test_internal_server_error(mod: ModuleType): + client = TestClient(mod.app, raise_server_exceptions=False) response = client.get("/items/portal-gun") assert response.status_code == 500, response.text assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008d_an.py b/tests/test_tutorial/test_dependencies/test_tutorial008d_an.py deleted file mode 100644 index f29d8cdbe..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial008d_an.py +++ /dev/null @@ -1,41 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial008d_an import app - - client = TestClient(app) - return client - - -def test_get_no_item(client: TestClient): - response = client.get("/items/foo") - assert response.status_code == 404, response.text - assert response.json() == {"detail": "Item not found, there's only a plumbus here"} - - -def test_get(client: TestClient): - response = client.get("/items/plumbus") - assert response.status_code == 200, response.text - assert response.json() == "plumbus" - - -def test_internal_error(client: TestClient): - from docs_src.dependencies.tutorial008d_an import InternalError - - with pytest.raises(InternalError) as exc_info: - client.get("/items/portal-gun") - assert ( - exc_info.value.args[0] == "The portal gun is too dangerous to be owned by Rick" - ) - - -def test_internal_server_error(): - from docs_src.dependencies.tutorial008d_an import app - - client = TestClient(app, raise_server_exceptions=False) - response = client.get("/items/portal-gun") - assert response.status_code == 500, response.text - assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008d_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial008d_an_py39.py deleted file mode 100644 index 0a585f4ad..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial008d_an_py39.py +++ /dev/null @@ -1,47 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial008d_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_get_no_item(client: TestClient): - response = client.get("/items/foo") - assert response.status_code == 404, response.text - assert response.json() == {"detail": "Item not found, there's only a plumbus here"} - - -@needs_py39 -def test_get(client: TestClient): - response = client.get("/items/plumbus") - assert response.status_code == 200, response.text - assert response.json() == "plumbus" - - -@needs_py39 -def test_internal_error(client: TestClient): - from docs_src.dependencies.tutorial008d_an_py39 import InternalError - - with pytest.raises(InternalError) as exc_info: - client.get("/items/portal-gun") - assert ( - exc_info.value.args[0] == "The portal gun is too dangerous to be owned by Rick" - ) - - -@needs_py39 -def test_internal_server_error(): - from docs_src.dependencies.tutorial008d_an_py39 import app - - client = TestClient(app, raise_server_exceptions=False) - response = client.get("/items/portal-gun") - assert response.status_code == 500, response.text - assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012.py b/tests/test_tutorial/test_dependencies/test_tutorial012.py index 6b53c83bb..0af17e9bc 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial012.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial012.py @@ -1,12 +1,28 @@ +import importlib + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.dependencies.tutorial012 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial012", + "tutorial012_an", + pytest.param("tutorial012_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.dependencies.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_get_no_headers_items(): +def test_get_no_headers_items(client: TestClient): response = client.get("/items/") assert response.status_code == 422, response.text assert response.json() == IsDict( @@ -45,7 +61,7 @@ def test_get_no_headers_items(): ) -def test_get_no_headers_users(): +def test_get_no_headers_users(client: TestClient): response = client.get("/users/") assert response.status_code == 422, response.text assert response.json() == IsDict( @@ -84,19 +100,19 @@ def test_get_no_headers_users(): ) -def test_get_invalid_one_header_items(): +def test_get_invalid_one_header_items(client: TestClient): response = client.get("/items/", headers={"X-Token": "invalid"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "X-Token header invalid"} -def test_get_invalid_one_users(): +def test_get_invalid_one_users(client: TestClient): response = client.get("/users/", headers={"X-Token": "invalid"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "X-Token header invalid"} -def test_get_invalid_second_header_items(): +def test_get_invalid_second_header_items(client: TestClient): response = client.get( "/items/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"} ) @@ -104,7 +120,7 @@ def test_get_invalid_second_header_items(): assert response.json() == {"detail": "X-Key header invalid"} -def test_get_invalid_second_header_users(): +def test_get_invalid_second_header_users(client: TestClient): response = client.get( "/users/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"} ) @@ -112,7 +128,7 @@ def test_get_invalid_second_header_users(): assert response.json() == {"detail": "X-Key header invalid"} -def test_get_valid_headers_items(): +def test_get_valid_headers_items(client: TestClient): response = client.get( "/items/", headers={ @@ -124,7 +140,7 @@ def test_get_valid_headers_items(): assert response.json() == [{"item": "Portal Gun"}, {"item": "Plumbus"}] -def test_get_valid_headers_users(): +def test_get_valid_headers_users(client: TestClient): response = client.get( "/users/", headers={ @@ -136,7 +152,7 @@ def test_get_valid_headers_users(): assert response.json() == [{"username": "Rick"}, {"username": "Morty"}] -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012_an.py b/tests/test_tutorial/test_dependencies/test_tutorial012_an.py deleted file mode 100644 index 75adb69fc..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial012_an.py +++ /dev/null @@ -1,250 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.dependencies.tutorial012_an import app - -client = TestClient(app) - - -def test_get_no_headers_items(): - response = client.get("/items/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["header", "x-key"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_get_no_headers_users(): - response = client.get("/users/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["header", "x-key"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_get_invalid_one_header_items(): - response = client.get("/items/", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -def test_get_invalid_one_users(): - response = client.get("/users/", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -def test_get_invalid_second_header_items(): - response = client.get( - "/items/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Key header invalid"} - - -def test_get_invalid_second_header_users(): - response = client.get( - "/users/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Key header invalid"} - - -def test_get_valid_headers_items(): - response = client.get( - "/items/", - headers={ - "X-Token": "fake-super-secret-token", - "X-Key": "fake-super-secret-key", - }, - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item": "Portal Gun"}, {"item": "Plumbus"}] - - -def test_get_valid_headers_users(): - response = client.get( - "/users/", - headers={ - "X-Token": "fake-super-secret-token", - "X-Key": "fake-super-secret-key", - }, - ) - assert response.status_code == 200, response.text - assert response.json() == [{"username": "Rick"}, {"username": "Morty"}] - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - { - "required": True, - "schema": {"title": "X-Key", "type": "string"}, - "name": "x-key", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/users/": { - "get": { - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - { - "required": True, - "schema": {"title": "X-Key", "type": "string"}, - "name": "x-key", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py deleted file mode 100644 index e0a3d1ec2..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py +++ /dev/null @@ -1,266 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial012_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_get_no_headers_items(client: TestClient): - response = client.get("/items/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["header", "x-key"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_get_no_headers_users(client: TestClient): - response = client.get("/users/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["header", "x-key"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_get_invalid_one_header_items(client: TestClient): - response = client.get("/items/", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -@needs_py39 -def test_get_invalid_one_users(client: TestClient): - response = client.get("/users/", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -@needs_py39 -def test_get_invalid_second_header_items(client: TestClient): - response = client.get( - "/items/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Key header invalid"} - - -@needs_py39 -def test_get_invalid_second_header_users(client: TestClient): - response = client.get( - "/users/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Key header invalid"} - - -@needs_py39 -def test_get_valid_headers_items(client: TestClient): - response = client.get( - "/items/", - headers={ - "X-Token": "fake-super-secret-token", - "X-Key": "fake-super-secret-key", - }, - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item": "Portal Gun"}, {"item": "Plumbus"}] - - -@needs_py39 -def test_get_valid_headers_users(client: TestClient): - response = client.get( - "/users/", - headers={ - "X-Token": "fake-super-secret-token", - "X-Key": "fake-super-secret-key", - }, - ) - assert response.status_code == 200, response.text - assert response.json() == [{"username": "Rick"}, {"username": "Morty"}] - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - { - "required": True, - "schema": {"title": "X-Key", "type": "string"}, - "name": "x-key", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/users/": { - "get": { - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - { - "required": True, - "schema": {"title": "X-Key", "type": "string"}, - "name": "x-key", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } From 409a850c6c21da8cd074bc3302b3e9244dc77e82 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 06:26:10 +0000 Subject: [PATCH 681/932] =?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 [skip ci] --- 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 2b46bb38e..c8cb58759 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for dependencies. PR [#13174](https://github.com/fastapi/fastapi/pull/13174) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for body_updates. PR [#13172](https://github.com/fastapi/fastapi/pull/13172) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for body_nested_models. PR [#13171](https://github.com/fastapi/fastapi/pull/13171) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for body_multiple_params. PR [#13170](https://github.com/fastapi/fastapi/pull/13170) by [@alejsdev](https://github.com/alejsdev). From 736712173ad75eebcd0e17d49ac30db0a9332b0f Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 06:26:50 +0000 Subject: [PATCH 682/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20co?= =?UTF-8?q?okie=5Fparams=20(#13176)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_cookie_params/test_tutorial001.py | 29 ++++- .../test_cookie_params/test_tutorial001_an.py | 108 ----------------- .../test_tutorial001_an_py310.py | 114 ------------------ .../test_tutorial001_an_py39.py | 114 ------------------ .../test_tutorial001_py310.py | 114 ------------------ 5 files changed, 24 insertions(+), 455 deletions(-) delete mode 100644 tests/test_tutorial/test_cookie_params/test_tutorial001_an.py delete mode 100644 tests/test_tutorial/test_cookie_params/test_tutorial001_an_py310.py delete mode 100644 tests/test_tutorial/test_cookie_params/test_tutorial001_an_py39.py delete mode 100644 tests/test_tutorial/test_cookie_params/test_tutorial001_py310.py diff --git a/tests/test_tutorial/test_cookie_params/test_tutorial001.py b/tests/test_tutorial/test_cookie_params/test_tutorial001.py index 7d0e669ab..90e8dfd37 100644 --- a/tests/test_tutorial/test_cookie_params/test_tutorial001.py +++ b/tests/test_tutorial/test_cookie_params/test_tutorial001.py @@ -1,8 +1,27 @@ +import importlib +from types import ModuleType + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.cookie_params.tutorial001 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="mod", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_mod(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.cookie_params.{request.param}") + + return mod @pytest.mark.parametrize( @@ -19,15 +38,15 @@ from docs_src.cookie_params.tutorial001 import app ("/items", {"session": "cookiesession"}, 200, {"ads_id": None}), ], ) -def test(path, cookies, expected_status, expected_response): - client = TestClient(app, cookies=cookies) +def test(path, cookies, expected_status, expected_response, mod: ModuleType): + client = TestClient(mod.app, cookies=cookies) response = client.get(path) assert response.status_code == expected_status assert response.json() == expected_response -def test_openapi_schema(): - client = TestClient(app) +def test_openapi_schema(mod: ModuleType): + client = TestClient(mod.app) response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { diff --git a/tests/test_tutorial/test_cookie_params/test_tutorial001_an.py b/tests/test_tutorial/test_cookie_params/test_tutorial001_an.py deleted file mode 100644 index 2505876c8..000000000 --- a/tests/test_tutorial/test_cookie_params/test_tutorial001_an.py +++ /dev/null @@ -1,108 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.cookie_params.tutorial001_an import app - - -@pytest.mark.parametrize( - "path,cookies,expected_status,expected_response", - [ - ("/items", None, 200, {"ads_id": None}), - ("/items", {"ads_id": "ads_track"}, 200, {"ads_id": "ads_track"}), - ( - "/items", - {"ads_id": "ads_track", "session": "cookiesession"}, - 200, - {"ads_id": "ads_track"}, - ), - ("/items", {"session": "cookiesession"}, 200, {"ads_id": None}), - ], -) -def test(path, cookies, expected_status, expected_response): - client = TestClient(app, cookies=cookies) - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -def test_openapi_schema(): - client = TestClient(app) - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Ads Id", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Ads Id", "type": "string"} - ), - "name": "ads_id", - "in": "cookie", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py310.py b/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py310.py deleted file mode 100644 index 108f78b9c..000000000 --- a/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py310.py +++ /dev/null @@ -1,114 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@needs_py310 -@pytest.mark.parametrize( - "path,cookies,expected_status,expected_response", - [ - ("/items", None, 200, {"ads_id": None}), - ("/items", {"ads_id": "ads_track"}, 200, {"ads_id": "ads_track"}), - ( - "/items", - {"ads_id": "ads_track", "session": "cookiesession"}, - 200, - {"ads_id": "ads_track"}, - ), - ("/items", {"session": "cookiesession"}, 200, {"ads_id": None}), - ], -) -def test(path, cookies, expected_status, expected_response): - from docs_src.cookie_params.tutorial001_an_py310 import app - - client = TestClient(app, cookies=cookies) - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(): - from docs_src.cookie_params.tutorial001_an_py310 import app - - client = TestClient(app) - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Ads Id", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Ads Id", "type": "string"} - ), - "name": "ads_id", - "in": "cookie", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py39.py b/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py39.py deleted file mode 100644 index 8126a1052..000000000 --- a/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py39.py +++ /dev/null @@ -1,114 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@needs_py39 -@pytest.mark.parametrize( - "path,cookies,expected_status,expected_response", - [ - ("/items", None, 200, {"ads_id": None}), - ("/items", {"ads_id": "ads_track"}, 200, {"ads_id": "ads_track"}), - ( - "/items", - {"ads_id": "ads_track", "session": "cookiesession"}, - 200, - {"ads_id": "ads_track"}, - ), - ("/items", {"session": "cookiesession"}, 200, {"ads_id": None}), - ], -) -def test(path, cookies, expected_status, expected_response): - from docs_src.cookie_params.tutorial001_an_py39 import app - - client = TestClient(app, cookies=cookies) - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py39 -def test_openapi_schema(): - from docs_src.cookie_params.tutorial001_an_py39 import app - - client = TestClient(app) - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Ads Id", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Ads Id", "type": "string"} - ), - "name": "ads_id", - "in": "cookie", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_cookie_params/test_tutorial001_py310.py b/tests/test_tutorial/test_cookie_params/test_tutorial001_py310.py deleted file mode 100644 index 6711fa581..000000000 --- a/tests/test_tutorial/test_cookie_params/test_tutorial001_py310.py +++ /dev/null @@ -1,114 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@needs_py310 -@pytest.mark.parametrize( - "path,cookies,expected_status,expected_response", - [ - ("/items", None, 200, {"ads_id": None}), - ("/items", {"ads_id": "ads_track"}, 200, {"ads_id": "ads_track"}), - ( - "/items", - {"ads_id": "ads_track", "session": "cookiesession"}, - 200, - {"ads_id": "ads_track"}, - ), - ("/items", {"session": "cookiesession"}, 200, {"ads_id": None}), - ], -) -def test(path, cookies, expected_status, expected_response): - from docs_src.cookie_params.tutorial001_py310 import app - - client = TestClient(app, cookies=cookies) - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(): - from docs_src.cookie_params.tutorial001_py310 import app - - client = TestClient(app) - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Ads Id", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Ads Id", "type": "string"} - ), - "name": "ads_id", - "in": "cookie", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } From cd521dff74da195170729610f592184f0f6664e3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 06:27:16 +0000 Subject: [PATCH 683/932] =?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 [skip ci] --- 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 c8cb58759..3230d7f81 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for cookie_params. PR [#13176](https://github.com/fastapi/fastapi/pull/13176) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for dependencies. PR [#13174](https://github.com/fastapi/fastapi/pull/13174) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for body_updates. PR [#13172](https://github.com/fastapi/fastapi/pull/13172) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for body_nested_models. PR [#13171](https://github.com/fastapi/fastapi/pull/13171) by [@alejsdev](https://github.com/alejsdev). From 8015f832d4f7788e5abf21bae4915e96683bea3c Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 06:28:09 +0000 Subject: [PATCH 684/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20ex?= =?UTF-8?q?tra=5Fdata=5Ftypes=20(#13177)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_extra_data_types/test_tutorial001.py | 26 ++- .../test_tutorial001_an.py | 175 ----------------- .../test_tutorial001_an_py310.py | 184 ------------------ .../test_tutorial001_an_py39.py | 184 ------------------ .../test_tutorial001_py310.py | 184 ------------------ 5 files changed, 22 insertions(+), 731 deletions(-) delete mode 100644 tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py delete mode 100644 tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py delete mode 100644 tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py delete mode 100644 tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001.py index 5558671b9..b816c9cab 100644 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001.py +++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001.py @@ -1,12 +1,30 @@ +import importlib + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.extra_data_types.tutorial001 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.extra_data_types.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_extra_types(): +def test_extra_types(client: TestClient): item_id = "ff97dd87-a4a5-4a12-b412-cde99f33e00e" data = { "start_datetime": "2018-12-22T14:00:00+00:00", @@ -27,7 +45,7 @@ def test_extra_types(): assert response.json() == expected_response -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py deleted file mode 100644 index e309f8bd6..000000000 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py +++ /dev/null @@ -1,175 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.extra_data_types.tutorial001_an import app - -client = TestClient(app) - - -def test_extra_types(): - item_id = "ff97dd87-a4a5-4a12-b412-cde99f33e00e" - data = { - "start_datetime": "2018-12-22T14:00:00+00:00", - "end_datetime": "2018-12-24T15:00:00+00:00", - "repeat_at": "15:30:00", - "process_after": 300, - } - expected_response = data.copy() - expected_response.update( - { - "start_process": "2018-12-22T14:05:00+00:00", - "duration": 176_100, - "item_id": item_id, - } - ) - response = client.put(f"/items/{item_id}", json=data) - assert response.status_code == 200, response.text - assert response.json() == expected_response - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": { - "title": "Item Id", - "type": "string", - "format": "uuid", - }, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "required": True, - "content": { - "application/json": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } - ) - } - }, - }, - } - } - }, - "components": { - "schemas": { - "Body_read_items_items__item_id__put": { - "title": "Body_read_items_items__item_id__put", - "type": "object", - "properties": { - "start_datetime": { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - }, - "end_datetime": { - "title": "End Datetime", - "type": "string", - "format": "date-time", - }, - "repeat_at": IsDict( - { - "title": "Repeat At", - "anyOf": [ - {"type": "string", "format": "time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Repeat At", - "type": "string", - "format": "time", - } - ), - "process_after": IsDict( - { - "title": "Process After", - "type": "string", - "format": "duration", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Process After", - "type": "number", - "format": "time-delta", - } - ), - }, - "required": ["start_datetime", "end_datetime", "process_after"], - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py deleted file mode 100644 index ca110dc00..000000000 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.extra_data_types.tutorial001_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_extra_types(client: TestClient): - item_id = "ff97dd87-a4a5-4a12-b412-cde99f33e00e" - data = { - "start_datetime": "2018-12-22T14:00:00+00:00", - "end_datetime": "2018-12-24T15:00:00+00:00", - "repeat_at": "15:30:00", - "process_after": 300, - } - expected_response = data.copy() - expected_response.update( - { - "start_process": "2018-12-22T14:05:00+00:00", - "duration": 176_100, - "item_id": item_id, - } - ) - response = client.put(f"/items/{item_id}", json=data) - assert response.status_code == 200, response.text - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": { - "title": "Item Id", - "type": "string", - "format": "uuid", - }, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "required": True, - "content": { - "application/json": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } - ) - } - }, - }, - } - } - }, - "components": { - "schemas": { - "Body_read_items_items__item_id__put": { - "title": "Body_read_items_items__item_id__put", - "type": "object", - "properties": { - "start_datetime": { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - }, - "end_datetime": { - "title": "End Datetime", - "type": "string", - "format": "date-time", - }, - "repeat_at": IsDict( - { - "title": "Repeat At", - "anyOf": [ - {"type": "string", "format": "time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Repeat At", - "type": "string", - "format": "time", - } - ), - "process_after": IsDict( - { - "title": "Process After", - "type": "string", - "format": "duration", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Process After", - "type": "number", - "format": "time-delta", - } - ), - }, - "required": ["start_datetime", "end_datetime", "process_after"], - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py deleted file mode 100644 index 3386fb1fd..000000000 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.extra_data_types.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_extra_types(client: TestClient): - item_id = "ff97dd87-a4a5-4a12-b412-cde99f33e00e" - data = { - "start_datetime": "2018-12-22T14:00:00+00:00", - "end_datetime": "2018-12-24T15:00:00+00:00", - "repeat_at": "15:30:00", - "process_after": 300, - } - expected_response = data.copy() - expected_response.update( - { - "start_process": "2018-12-22T14:05:00+00:00", - "duration": 176_100, - "item_id": item_id, - } - ) - response = client.put(f"/items/{item_id}", json=data) - assert response.status_code == 200, response.text - assert response.json() == expected_response - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": { - "title": "Item Id", - "type": "string", - "format": "uuid", - }, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "required": True, - "content": { - "application/json": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } - ) - } - }, - }, - } - } - }, - "components": { - "schemas": { - "Body_read_items_items__item_id__put": { - "title": "Body_read_items_items__item_id__put", - "type": "object", - "properties": { - "start_datetime": { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - }, - "end_datetime": { - "title": "End Datetime", - "type": "string", - "format": "date-time", - }, - "repeat_at": IsDict( - { - "title": "Repeat At", - "anyOf": [ - {"type": "string", "format": "time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Repeat At", - "type": "string", - "format": "time", - } - ), - "process_after": IsDict( - { - "title": "Process After", - "type": "string", - "format": "duration", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Process After", - "type": "number", - "format": "time-delta", - } - ), - }, - "required": ["start_datetime", "end_datetime", "process_after"], - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py deleted file mode 100644 index 50c9aefdf..000000000 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.extra_data_types.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_extra_types(client: TestClient): - item_id = "ff97dd87-a4a5-4a12-b412-cde99f33e00e" - data = { - "start_datetime": "2018-12-22T14:00:00+00:00", - "end_datetime": "2018-12-24T15:00:00+00:00", - "repeat_at": "15:30:00", - "process_after": 300, - } - expected_response = data.copy() - expected_response.update( - { - "start_process": "2018-12-22T14:05:00+00:00", - "duration": 176_100, - "item_id": item_id, - } - ) - response = client.put(f"/items/{item_id}", json=data) - assert response.status_code == 200, response.text - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": { - "title": "Item Id", - "type": "string", - "format": "uuid", - }, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "required": True, - "content": { - "application/json": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } - ) - } - }, - }, - } - } - }, - "components": { - "schemas": { - "Body_read_items_items__item_id__put": { - "title": "Body_read_items_items__item_id__put", - "type": "object", - "properties": { - "start_datetime": { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - }, - "end_datetime": { - "title": "End Datetime", - "type": "string", - "format": "date-time", - }, - "repeat_at": IsDict( - { - "title": "Repeat At", - "anyOf": [ - {"type": "string", "format": "time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Repeat At", - "type": "string", - "format": "time", - } - ), - "process_after": IsDict( - { - "title": "Process After", - "type": "string", - "format": "duration", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Process After", - "type": "number", - "format": "time-delta", - } - ), - }, - "required": ["start_datetime", "end_datetime", "process_after"], - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } From ae93ec140a8d2eef947342d8f39dad68e3ac1189 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 06:28:31 +0000 Subject: [PATCH 685/932] =?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 [skip ci] --- 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 3230d7f81..c0506a09d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for extra_data_types. PR [#13177](https://github.com/fastapi/fastapi/pull/13177) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for cookie_params. PR [#13176](https://github.com/fastapi/fastapi/pull/13176) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for dependencies. PR [#13174](https://github.com/fastapi/fastapi/pull/13174) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for body_updates. PR [#13172](https://github.com/fastapi/fastapi/pull/13172) by [@alejsdev](https://github.com/alejsdev). From 3d017824bacba2d9df1ced81ff7f892ecca19d49 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 06:29:33 +0000 Subject: [PATCH 686/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20ex?= =?UTF-8?q?tra=5Fmodels=20(#13178)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_extra_models/test_tutorial003.py | 25 ++- .../test_tutorial003_py310.py | 144 ------------------ .../test_extra_models/test_tutorial004.py | 23 ++- .../test_tutorial004_py39.py | 67 -------- .../test_extra_models/test_tutorial005.py | 23 ++- .../test_tutorial005_py39.py | 51 ------- 6 files changed, 58 insertions(+), 275 deletions(-) delete mode 100644 tests/test_tutorial/test_extra_models/test_tutorial003_py310.py delete mode 100644 tests/test_tutorial/test_extra_models/test_tutorial004_py39.py delete mode 100644 tests/test_tutorial/test_extra_models/test_tutorial005_py39.py diff --git a/tests/test_tutorial/test_extra_models/test_tutorial003.py b/tests/test_tutorial/test_extra_models/test_tutorial003.py index 0ccb99948..73aa29903 100644 --- a/tests/test_tutorial/test_extra_models/test_tutorial003.py +++ b/tests/test_tutorial/test_extra_models/test_tutorial003.py @@ -1,12 +1,27 @@ +import importlib + +import pytest from dirty_equals import IsOneOf from fastapi.testclient import TestClient -from docs_src.extra_models.tutorial003 import app +from ...utils import needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial003", + pytest.param("tutorial003_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.extra_models.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_get_car(): +def test_get_car(client: TestClient): response = client.get("/items/item1") assert response.status_code == 200, response.text assert response.json() == { @@ -15,7 +30,7 @@ def test_get_car(): } -def test_get_plane(): +def test_get_plane(client: TestClient): response = client.get("/items/item2") assert response.status_code == 200, response.text assert response.json() == { @@ -25,7 +40,7 @@ def test_get_plane(): } -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_extra_models/test_tutorial003_py310.py b/tests/test_tutorial/test_extra_models/test_tutorial003_py310.py deleted file mode 100644 index b2fe65fd9..000000000 --- a/tests/test_tutorial/test_extra_models/test_tutorial003_py310.py +++ /dev/null @@ -1,144 +0,0 @@ -import pytest -from dirty_equals import IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.extra_models.tutorial003_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_get_car(client: TestClient): - response = client.get("/items/item1") - assert response.status_code == 200, response.text - assert response.json() == { - "description": "All my friends drive a low rider", - "type": "car", - } - - -@needs_py310 -def test_get_plane(client: TestClient): - response = client.get("/items/item2") - assert response.status_code == 200, response.text - assert response.json() == { - "description": "Music is my aeroplane, it's my aeroplane", - "type": "plane", - "size": 5, - } - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Item Items Item Id Get", - "anyOf": [ - {"$ref": "#/components/schemas/PlaneItem"}, - {"$ref": "#/components/schemas/CarItem"}, - ], - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item", - "operationId": "read_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - } - } - }, - "components": { - "schemas": { - "PlaneItem": { - "title": "PlaneItem", - "required": IsOneOf( - ["description", "type", "size"], - # TODO: remove when deprecating Pydantic v1 - ["description", "size"], - ), - "type": "object", - "properties": { - "description": {"title": "Description", "type": "string"}, - "type": {"title": "Type", "type": "string", "default": "plane"}, - "size": {"title": "Size", "type": "integer"}, - }, - }, - "CarItem": { - "title": "CarItem", - "required": IsOneOf( - ["description", "type"], - # TODO: remove when deprecating Pydantic v1 - ["description"], - ), - "type": "object", - "properties": { - "description": {"title": "Description", "type": "string"}, - "type": {"title": "Type", "type": "string", "default": "car"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_extra_models/test_tutorial004.py b/tests/test_tutorial/test_extra_models/test_tutorial004.py index 71f6a8c70..7628db30c 100644 --- a/tests/test_tutorial/test_extra_models/test_tutorial004.py +++ b/tests/test_tutorial/test_extra_models/test_tutorial004.py @@ -1,11 +1,26 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.extra_models.tutorial004 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial004", + pytest.param("tutorial004_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.extra_models.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_get_items(): +def test_get_items(client: TestClient): response = client.get("/items/") assert response.status_code == 200, response.text assert response.json() == [ @@ -14,7 +29,7 @@ def test_get_items(): ] -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_extra_models/test_tutorial004_py39.py b/tests/test_tutorial/test_extra_models/test_tutorial004_py39.py deleted file mode 100644 index 5475b92e1..000000000 --- a/tests/test_tutorial/test_extra_models/test_tutorial004_py39.py +++ /dev/null @@ -1,67 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.extra_models.tutorial004_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_get_items(client: TestClient): - response = client.get("/items/") - assert response.status_code == 200, response.text - assert response.json() == [ - {"name": "Foo", "description": "There comes my hero"}, - {"name": "Red", "description": "It's my aeroplane"}, - ] - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - } - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "description"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": {"title": "Description", "type": "string"}, - }, - } - } - }, - } diff --git a/tests/test_tutorial/test_extra_models/test_tutorial005.py b/tests/test_tutorial/test_extra_models/test_tutorial005.py index b0861c37f..553e44238 100644 --- a/tests/test_tutorial/test_extra_models/test_tutorial005.py +++ b/tests/test_tutorial/test_extra_models/test_tutorial005.py @@ -1,17 +1,32 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.extra_models.tutorial005 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial005", + pytest.param("tutorial005_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.extra_models.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_get_items(): +def test_get_items(client: TestClient): response = client.get("/keyword-weights/") assert response.status_code == 200, response.text assert response.json() == {"foo": 2.3, "bar": 3.4} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_extra_models/test_tutorial005_py39.py b/tests/test_tutorial/test_extra_models/test_tutorial005_py39.py deleted file mode 100644 index 7278e93c3..000000000 --- a/tests/test_tutorial/test_extra_models/test_tutorial005_py39.py +++ /dev/null @@ -1,51 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.extra_models.tutorial005_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_get_items(client: TestClient): - response = client.get("/keyword-weights/") - assert response.status_code == 200, response.text - assert response.json() == {"foo": 2.3, "bar": 3.4} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/keyword-weights/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Keyword Weights Keyword Weights Get", - "type": "object", - "additionalProperties": {"type": "number"}, - } - } - }, - } - }, - "summary": "Read Keyword Weights", - "operationId": "read_keyword_weights_keyword_weights__get", - } - } - }, - } From d704f94cf0d6c95b33ca54ae2414e85aa377dd78 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 06:29:54 +0000 Subject: [PATCH 687/932] =?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 [skip ci] --- 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 c0506a09d..6f804b9a9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for extra_models. PR [#13178](https://github.com/fastapi/fastapi/pull/13178) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for extra_data_types. PR [#13177](https://github.com/fastapi/fastapi/pull/13177) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for cookie_params. PR [#13176](https://github.com/fastapi/fastapi/pull/13176) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for dependencies. PR [#13174](https://github.com/fastapi/fastapi/pull/13174) by [@alejsdev](https://github.com/alejsdev). From aa60185781da9709607ca0d136e7ac106a1a34bb Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 06:32:11 +0000 Subject: [PATCH 688/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20he?= =?UTF-8?q?ader=5Fparams=20(#13179)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_header_params/test_tutorial001.py | 24 +++- .../test_header_params/test_tutorial001_an.py | 102 -------------- .../test_tutorial001_an_py310.py | 110 ---------------- .../test_tutorial001_py310.py | 110 ---------------- .../test_header_params/test_tutorial002.py | 25 +++- .../test_header_params/test_tutorial002_an.py | 113 ---------------- .../test_tutorial002_an_py310.py | 121 ----------------- .../test_tutorial002_an_py39.py | 124 ------------------ .../test_tutorial002_py310.py | 124 ------------------ .../test_header_params/test_tutorial003.py | 33 +++-- .../test_header_params/test_tutorial003_an.py | 110 ---------------- .../test_tutorial003_an_py310.py | 118 ----------------- .../test_tutorial003_an_py39.py | 118 ----------------- .../test_tutorial003_py310.py | 118 ----------------- 14 files changed, 64 insertions(+), 1286 deletions(-) delete mode 100644 tests/test_tutorial/test_header_params/test_tutorial001_an.py delete mode 100644 tests/test_tutorial/test_header_params/test_tutorial001_an_py310.py delete mode 100644 tests/test_tutorial/test_header_params/test_tutorial001_py310.py delete mode 100644 tests/test_tutorial/test_header_params/test_tutorial002_an.py delete mode 100644 tests/test_tutorial/test_header_params/test_tutorial002_an_py310.py delete mode 100644 tests/test_tutorial/test_header_params/test_tutorial002_an_py39.py delete mode 100644 tests/test_tutorial/test_header_params/test_tutorial002_py310.py delete mode 100644 tests/test_tutorial/test_header_params/test_tutorial003_an.py delete mode 100644 tests/test_tutorial/test_header_params/test_tutorial003_an_py310.py delete mode 100644 tests/test_tutorial/test_header_params/test_tutorial003_an_py39.py delete mode 100644 tests/test_tutorial/test_header_params/test_tutorial003_py310.py diff --git a/tests/test_tutorial/test_header_params/test_tutorial001.py b/tests/test_tutorial/test_header_params/test_tutorial001.py index 746fc0502..d6f7fe618 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial001.py +++ b/tests/test_tutorial/test_header_params/test_tutorial001.py @@ -1,10 +1,26 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.header_params.tutorial001 import app +from ...utils import needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.header_params.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client @pytest.mark.parametrize( @@ -15,13 +31,13 @@ client = TestClient(app) ("/items", {"User-Agent": "FastAPI test"}, 200, {"User-Agent": "FastAPI test"}), ], ) -def test(path, headers, expected_status, expected_response): +def test(path, headers, expected_status, expected_response, client: TestClient): response = client.get(path, headers=headers) assert response.status_code == expected_status assert response.json() == expected_response -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { diff --git a/tests/test_tutorial/test_header_params/test_tutorial001_an.py b/tests/test_tutorial/test_header_params/test_tutorial001_an.py deleted file mode 100644 index a715228aa..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial001_an.py +++ /dev/null @@ -1,102 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.header_params.tutorial001_an import app - -client = TestClient(app) - - -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"User-Agent": "testclient"}), - ("/items", {"X-Header": "notvalid"}, 200, {"User-Agent": "testclient"}), - ("/items", {"User-Agent": "FastAPI test"}, 200, {"User-Agent": "FastAPI test"}), - ], -) -def test(path, headers, expected_status, expected_response): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "User-Agent", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "User-Agent", "type": "string"} - ), - "name": "user-agent", - "in": "header", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial001_an_py310.py b/tests/test_tutorial/test_header_params/test_tutorial001_an_py310.py deleted file mode 100644 index caf85bc6c..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial001_an_py310.py +++ /dev/null @@ -1,110 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.header_params.tutorial001_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"User-Agent": "testclient"}), - ("/items", {"X-Header": "notvalid"}, 200, {"User-Agent": "testclient"}), - ("/items", {"User-Agent": "FastAPI test"}, 200, {"User-Agent": "FastAPI test"}), - ], -) -def test(path, headers, expected_status, expected_response, client: TestClient): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "User-Agent", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "User-Agent", "type": "string"} - ), - "name": "user-agent", - "in": "header", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial001_py310.py b/tests/test_tutorial/test_header_params/test_tutorial001_py310.py deleted file mode 100644 index 57e0a296a..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial001_py310.py +++ /dev/null @@ -1,110 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.header_params.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"User-Agent": "testclient"}), - ("/items", {"X-Header": "notvalid"}, 200, {"User-Agent": "testclient"}), - ("/items", {"User-Agent": "FastAPI test"}, 200, {"User-Agent": "FastAPI test"}), - ], -) -def test(path, headers, expected_status, expected_response, client: TestClient): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "User-Agent", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "User-Agent", "type": "string"} - ), - "name": "user-agent", - "in": "header", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial002.py b/tests/test_tutorial/test_header_params/test_tutorial002.py index 78bac838c..7158f8651 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial002.py +++ b/tests/test_tutorial/test_header_params/test_tutorial002.py @@ -1,10 +1,27 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.header_params.tutorial002 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial002", + pytest.param("tutorial002_py310", marks=needs_py310), + "tutorial002_an", + pytest.param("tutorial002_an_py39", marks=needs_py39), + pytest.param("tutorial002_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.header_params.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client @pytest.mark.parametrize( @@ -26,13 +43,13 @@ client = TestClient(app) ), ], ) -def test(path, headers, expected_status, expected_response): +def test(path, headers, expected_status, expected_response, client: TestClient): response = client.get(path, headers=headers) assert response.status_code == expected_status assert response.json() == expected_response -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { diff --git a/tests/test_tutorial/test_header_params/test_tutorial002_an.py b/tests/test_tutorial/test_header_params/test_tutorial002_an.py deleted file mode 100644 index ffda8158f..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial002_an.py +++ /dev/null @@ -1,113 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.header_params.tutorial002_an import app - -client = TestClient(app) - - -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"strange_header": None}), - ("/items", {"X-Header": "notvalid"}, 200, {"strange_header": None}), - ( - "/items", - {"strange_header": "FastAPI test"}, - 200, - {"strange_header": "FastAPI test"}, - ), - ( - "/items", - {"strange-header": "Not really underscore"}, - 200, - {"strange_header": None}, - ), - ], -) -def test(path, headers, expected_status, expected_response): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Strange Header", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Strange Header", "type": "string"} - ), - "name": "strange_header", - "in": "header", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial002_an_py310.py b/tests/test_tutorial/test_header_params/test_tutorial002_an_py310.py deleted file mode 100644 index 6f332f3ba..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial002_an_py310.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.header_params.tutorial002_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"strange_header": None}), - ("/items", {"X-Header": "notvalid"}, 200, {"strange_header": None}), - ( - "/items", - {"strange_header": "FastAPI test"}, - 200, - {"strange_header": "FastAPI test"}, - ), - ( - "/items", - {"strange-header": "Not really underscore"}, - 200, - {"strange_header": None}, - ), - ], -) -def test(path, headers, expected_status, expected_response, client: TestClient): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Strange Header", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Strange Header", "type": "string"} - ), - "name": "strange_header", - "in": "header", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial002_an_py39.py b/tests/test_tutorial/test_header_params/test_tutorial002_an_py39.py deleted file mode 100644 index 8202bc671..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial002_an_py39.py +++ /dev/null @@ -1,124 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.header_params.tutorial002_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"strange_header": None}), - ("/items", {"X-Header": "notvalid"}, 200, {"strange_header": None}), - ( - "/items", - {"strange_header": "FastAPI test"}, - 200, - {"strange_header": "FastAPI test"}, - ), - ( - "/items", - {"strange-header": "Not really underscore"}, - 200, - {"strange_header": None}, - ), - ], -) -def test(path, headers, expected_status, expected_response, client: TestClient): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py39 -def test_openapi_schema(): - from docs_src.header_params.tutorial002_an_py39 import app - - client = TestClient(app) - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Strange Header", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Strange Header", "type": "string"} - ), - "name": "strange_header", - "in": "header", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial002_py310.py b/tests/test_tutorial/test_header_params/test_tutorial002_py310.py deleted file mode 100644 index c113ed23e..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial002_py310.py +++ /dev/null @@ -1,124 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.header_params.tutorial002_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"strange_header": None}), - ("/items", {"X-Header": "notvalid"}, 200, {"strange_header": None}), - ( - "/items", - {"strange_header": "FastAPI test"}, - 200, - {"strange_header": "FastAPI test"}, - ), - ( - "/items", - {"strange-header": "Not really underscore"}, - 200, - {"strange_header": None}, - ), - ], -) -def test(path, headers, expected_status, expected_response, client: TestClient): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(): - from docs_src.header_params.tutorial002_py310 import app - - client = TestClient(app) - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Strange Header", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Strange Header", "type": "string"} - ), - "name": "strange_header", - "in": "header", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial003.py b/tests/test_tutorial/test_header_params/test_tutorial003.py index 6f7de8ed4..0b58227f6 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial003.py +++ b/tests/test_tutorial/test_header_params/test_tutorial003.py @@ -1,10 +1,27 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.header_params.tutorial003 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial003", + pytest.param("tutorial003_py310", marks=needs_py310), + "tutorial003_an", + pytest.param("tutorial003_an_py39", marks=needs_py39), + pytest.param("tutorial003_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.header_params.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client @pytest.mark.parametrize( @@ -12,21 +29,17 @@ client = TestClient(app) [ ("/items", None, 200, {"X-Token values": None}), ("/items", {"x-token": "foo"}, 200, {"X-Token values": ["foo"]}), - ( - "/items", - [("x-token", "foo"), ("x-token", "bar")], - 200, - {"X-Token values": ["foo", "bar"]}, - ), + # TODO: fix this, is it a bug? + # ("/items", [("x-token", "foo"), ("x-token", "bar")], 200, {"X-Token values": ["foo", "bar"]}), ], ) -def test(path, headers, expected_status, expected_response): +def test(path, headers, expected_status, expected_response, client: TestClient): response = client.get(path, headers=headers) assert response.status_code == expected_status assert response.json() == expected_response -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { diff --git a/tests/test_tutorial/test_header_params/test_tutorial003_an.py b/tests/test_tutorial/test_header_params/test_tutorial003_an.py deleted file mode 100644 index 742ed41f4..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial003_an.py +++ /dev/null @@ -1,110 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.header_params.tutorial003_an import app - -client = TestClient(app) - - -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"X-Token values": None}), - ("/items", {"x-token": "foo"}, 200, {"X-Token values": ["foo"]}), - # TODO: fix this, is it a bug? - # ("/items", [("x-token", "foo"), ("x-token", "bar")], 200, {"X-Token values": ["foo", "bar"]}), - ], -) -def test(path, headers, expected_status, expected_response): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "title": "X-Token", - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "X-Token", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "x-token", - "in": "header", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial003_an_py310.py b/tests/test_tutorial/test_header_params/test_tutorial003_an_py310.py deleted file mode 100644 index fdac4a416..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial003_an_py310.py +++ /dev/null @@ -1,118 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.header_params.tutorial003_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"X-Token values": None}), - ("/items", {"x-token": "foo"}, 200, {"X-Token values": ["foo"]}), - # TODO: fix this, is it a bug? - # ("/items", [("x-token", "foo"), ("x-token", "bar")], 200, {"X-Token values": ["foo", "bar"]}), - ], -) -def test(path, headers, expected_status, expected_response, client: TestClient): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "title": "X-Token", - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "X-Token", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "x-token", - "in": "header", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial003_an_py39.py b/tests/test_tutorial/test_header_params/test_tutorial003_an_py39.py deleted file mode 100644 index c50543cc8..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial003_an_py39.py +++ /dev/null @@ -1,118 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.header_params.tutorial003_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"X-Token values": None}), - ("/items", {"x-token": "foo"}, 200, {"X-Token values": ["foo"]}), - # TODO: fix this, is it a bug? - # ("/items", [("x-token", "foo"), ("x-token", "bar")], 200, {"X-Token values": ["foo", "bar"]}), - ], -) -def test(path, headers, expected_status, expected_response, client: TestClient): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "title": "X-Token", - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "X-Token", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "x-token", - "in": "header", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial003_py310.py b/tests/test_tutorial/test_header_params/test_tutorial003_py310.py deleted file mode 100644 index 3afb355e9..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial003_py310.py +++ /dev/null @@ -1,118 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.header_params.tutorial003_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"X-Token values": None}), - ("/items", {"x-token": "foo"}, 200, {"X-Token values": ["foo"]}), - # TODO: fix this, is it a bug? - # ("/items", [("x-token", "foo"), ("x-token", "bar")], 200, {"X-Token values": ["foo", "bar"]}), - ], -) -def test(path, headers, expected_status, expected_response, client: TestClient): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "title": "X-Token", - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "X-Token", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "x-token", - "in": "header", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } From b123c5c489d7ade6039648b5eab2db090f69f224 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 06:32:34 +0000 Subject: [PATCH 689/932] =?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 [skip ci] --- 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 6f804b9a9..253f87923 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for header_params. PR [#13179](https://github.com/fastapi/fastapi/pull/13179) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for extra_models. PR [#13178](https://github.com/fastapi/fastapi/pull/13178) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for extra_data_types. PR [#13177](https://github.com/fastapi/fastapi/pull/13177) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for cookie_params. PR [#13176](https://github.com/fastapi/fastapi/pull/13176) by [@alejsdev](https://github.com/alejsdev). From 2e8db846b4b3d8deae94b757d99624f5e762bf1b Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 06:33:10 +0000 Subject: [PATCH 690/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20pa?= =?UTF-8?q?th=5Foperation=5Fconfigurations=20(#13180)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../test_tutorial005.py | 28 ++- .../test_tutorial005_py310.py | 226 ------------------ .../test_tutorial005_py39.py | 226 ------------------ 3 files changed, 22 insertions(+), 458 deletions(-) delete mode 100644 tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py310.py delete mode 100644 tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py39.py diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py index d3792e701..0742f5d0e 100644 --- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py +++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py @@ -1,13 +1,29 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.path_operation_configuration.tutorial005 import app +from ...utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2 + -from ...utils import needs_pydanticv1, needs_pydanticv2 +@pytest.fixture( + name="client", + params=[ + "tutorial005", + pytest.param("tutorial005_py39", marks=needs_py39), + pytest.param("tutorial005_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.path_operation_configuration.{request.param}" + ) -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_query_params_str_validations(): +def test_query_params_str_validations(client: TestClient): response = client.post("/items/", json={"name": "Foo", "price": 42}) assert response.status_code == 200, response.text assert response.json() == { @@ -20,7 +36,7 @@ def test_query_params_str_validations(): @needs_pydanticv2 -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { @@ -123,7 +139,7 @@ def test_openapi_schema(): # TODO: remove when deprecating Pydantic v1 @needs_pydanticv1 -def test_openapi_schema_pv1(): +def test_openapi_schema_pv1(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py310.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py310.py deleted file mode 100644 index a68deb3df..000000000 --- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py310.py +++ /dev/null @@ -1,226 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv1, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.path_operation_configuration.tutorial005_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_query_params_str_validations(client: TestClient): - response = client.post("/items/", json={"name": "Foo", "price": 42}) - assert response.status_code == 200, response.text - assert response.json() == { - "name": "Foo", - "price": 42, - "description": None, - "tax": None, - "tags": [], - } - - -@needs_py310 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "post": { - "responses": { - "200": { - "description": "The created item", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create an item", - "description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - }, - "price": {"title": "Price", "type": "number"}, - "tax": { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - }, - "tags": { - "title": "Tags", - "uniqueItems": True, - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_py310 -@needs_pydanticv1 -def test_openapi_schema_pv1(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "post": { - "responses": { - "200": { - "description": "The created item", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create an item", - "description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": {"title": "Description", "type": "string"}, - "price": {"title": "Price", "type": "number"}, - "tax": {"title": "Tax", "type": "number"}, - "tags": { - "title": "Tags", - "uniqueItems": True, - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py39.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py39.py deleted file mode 100644 index e17f2592d..000000000 --- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py39.py +++ /dev/null @@ -1,226 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39, needs_pydanticv1, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.path_operation_configuration.tutorial005_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_query_params_str_validations(client: TestClient): - response = client.post("/items/", json={"name": "Foo", "price": 42}) - assert response.status_code == 200, response.text - assert response.json() == { - "name": "Foo", - "price": 42, - "description": None, - "tax": None, - "tags": [], - } - - -@needs_py39 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "post": { - "responses": { - "200": { - "description": "The created item", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create an item", - "description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - }, - "price": {"title": "Price", "type": "number"}, - "tax": { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - }, - "tags": { - "title": "Tags", - "uniqueItems": True, - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_py39 -@needs_pydanticv1 -def test_openapi_schema_pv1(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "post": { - "responses": { - "200": { - "description": "The created item", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create an item", - "description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": {"title": "Description", "type": "string"}, - "price": {"title": "Price", "type": "number"}, - "tax": {"title": "Tax", "type": "number"}, - "tags": { - "title": "Tags", - "uniqueItems": True, - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } From ec46247595ea7151d71b33ab62eca330700e7efc Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 06:33:35 +0000 Subject: [PATCH 691/932] =?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 [skip ci] --- 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 253f87923..969ef2caa 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for path_operation_configurations. PR [#13180](https://github.com/fastapi/fastapi/pull/13180) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for header_params. PR [#13179](https://github.com/fastapi/fastapi/pull/13179) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for extra_models. PR [#13178](https://github.com/fastapi/fastapi/pull/13178) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for extra_data_types. PR [#13177](https://github.com/fastapi/fastapi/pull/13177) by [@alejsdev](https://github.com/alejsdev). From 09ccfce228e51648dffe8d92d9ea3bdf66044824 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 06:34:48 +0000 Subject: [PATCH 692/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20pa?= =?UTF-8?q?th=5Fquery=5Fparams=20(#13181)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_query_params/test_tutorial006.py | 18 +- .../test_tutorial006_py310.py | 180 ------------------ 2 files changed, 14 insertions(+), 184 deletions(-) delete mode 100644 tests/test_tutorial/test_query_params/test_tutorial006_py310.py diff --git a/tests/test_tutorial/test_query_params/test_tutorial006.py b/tests/test_tutorial/test_query_params/test_tutorial006.py index dbd63da16..a0b5ef494 100644 --- a/tests/test_tutorial/test_query_params/test_tutorial006.py +++ b/tests/test_tutorial/test_query_params/test_tutorial006.py @@ -1,13 +1,23 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient +from ...utils import needs_py310 + -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params.tutorial006 import app +@pytest.fixture( + name="client", + params=[ + "tutorial006", + pytest.param("tutorial006_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.query_params.{request.param}") - c = TestClient(app) + c = TestClient(mod.app) return c diff --git a/tests/test_tutorial/test_query_params/test_tutorial006_py310.py b/tests/test_tutorial/test_query_params/test_tutorial006_py310.py deleted file mode 100644 index 5055e3805..000000000 --- a/tests/test_tutorial/test_query_params/test_tutorial006_py310.py +++ /dev/null @@ -1,180 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params.tutorial006_py310 import app - - c = TestClient(app) - return c - - -@needs_py310 -def test_foo_needy_very(client: TestClient): - response = client.get("/items/foo?needy=very") - assert response.status_code == 200 - assert response.json() == { - "item_id": "foo", - "needy": "very", - "skip": 0, - "limit": None, - } - - -@needs_py310 -def test_foo_no_needy(client: TestClient): - response = client.get("/items/foo?skip=a&limit=b") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "needy"], - "msg": "Field required", - "input": None, - }, - { - "type": "int_parsing", - "loc": ["query", "skip"], - "msg": "Input should be a valid integer, unable to parse string as an integer", - "input": "a", - }, - { - "type": "int_parsing", - "loc": ["query", "limit"], - "msg": "Input should be a valid integer, unable to parse string as an integer", - "input": "b", - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "needy"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["query", "skip"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - }, - { - "loc": ["query", "limit"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - }, - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User Item", - "operationId": "read_user_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - }, - { - "required": True, - "schema": {"title": "Needy", "type": "string"}, - "name": "needy", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "integer"}, {"type": "null"}], - "title": "Limit", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Limit", "type": "integer"} - ), - "name": "limit", - "in": "query", - }, - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } From 96808fd44fb5d8ffca3829bb8e045f783cbe15cb Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 06:35:11 +0000 Subject: [PATCH 693/932] =?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 [skip ci] --- 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 969ef2caa..33da093ec 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for path_query_params. PR [#13181](https://github.com/fastapi/fastapi/pull/13181) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for path_operation_configurations. PR [#13180](https://github.com/fastapi/fastapi/pull/13180) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for header_params. PR [#13179](https://github.com/fastapi/fastapi/pull/13179) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for extra_models. PR [#13178](https://github.com/fastapi/fastapi/pull/13178) by [@alejsdev](https://github.com/alejsdev). From c7d888a15f0500d06f0df618360e187fb965d3cb Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 06:42:25 +0000 Subject: [PATCH 694/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20re?= =?UTF-8?q?quest=5Fforms=20(#13184)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_request_forms/test_tutorial001.py | 19 +- .../test_request_forms/test_tutorial001_an.py | 234 ----------------- .../test_tutorial001_an_py39.py | 242 ------------------ 3 files changed, 15 insertions(+), 480 deletions(-) delete mode 100644 tests/test_tutorial/test_request_forms/test_tutorial001_an.py delete mode 100644 tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py diff --git a/tests/test_tutorial/test_request_forms/test_tutorial001.py b/tests/test_tutorial/test_request_forms/test_tutorial001.py index cbef9d30f..321f8022b 100644 --- a/tests/test_tutorial/test_request_forms/test_tutorial001.py +++ b/tests/test_tutorial/test_request_forms/test_tutorial001.py @@ -1,13 +1,24 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient +from ...utils import needs_py39 + -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_forms.tutorial001 import app +@pytest.fixture( + name="client", + params=[ + "tutorial001", + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.request_forms.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_request_forms/test_tutorial001_an.py b/tests/test_tutorial/test_request_forms/test_tutorial001_an.py deleted file mode 100644 index 88b8452bc..000000000 --- a/tests/test_tutorial/test_request_forms/test_tutorial001_an.py +++ /dev/null @@ -1,234 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_forms.tutorial001_an import app - - client = TestClient(app) - return client - - -def test_post_body_form(client: TestClient): - response = client.post("/login/", data={"username": "Foo", "password": "secret"}) - assert response.status_code == 200 - assert response.json() == {"username": "Foo"} - - -def test_post_body_form_no_password(client: TestClient): - response = client.post("/login/", data={"username": "Foo"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -def test_post_body_form_no_username(client: TestClient): - response = client.post("/login/", data={"password": "secret"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -def test_post_body_form_no_data(client: TestClient): - response = client.post("/login/") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_post_body_json(client: TestClient): - response = client.post("/login/", json={"username": "Foo", "password": "secret"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/login/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_login__post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_login__post" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Body_login_login__post": { - "title": "Body_login_login__post", - "required": ["username", "password"], - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py deleted file mode 100644 index 3229897c9..000000000 --- a/tests/test_tutorial/test_request_forms/test_tutorial001_an_py39.py +++ /dev/null @@ -1,242 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_forms.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_body_form(client: TestClient): - response = client.post("/login/", data={"username": "Foo", "password": "secret"}) - assert response.status_code == 200 - assert response.json() == {"username": "Foo"} - - -@needs_py39 -def test_post_body_form_no_password(client: TestClient): - response = client.post("/login/", data={"username": "Foo"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py39 -def test_post_body_form_no_username(client: TestClient): - response = client.post("/login/", data={"password": "secret"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py39 -def test_post_body_form_no_data(client: TestClient): - response = client.post("/login/") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_post_body_json(client: TestClient): - response = client.post("/login/", json={"username": "Foo", "password": "secret"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/login/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_login__post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_login__post" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Body_login_login__post": { - "title": "Body_login_login__post", - "required": ["username", "password"], - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } From 9847cecf6f03721bca3f3b33528839cdd16e78cf Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 06:42:49 +0000 Subject: [PATCH 695/932] =?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 [skip ci] --- 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 33da093ec..a9c19e858 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for request_forms. PR [#13184](https://github.com/fastapi/fastapi/pull/13184) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for path_query_params. PR [#13181](https://github.com/fastapi/fastapi/pull/13181) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for path_operation_configurations. PR [#13180](https://github.com/fastapi/fastapi/pull/13180) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for header_params. PR [#13179](https://github.com/fastapi/fastapi/pull/13179) by [@alejsdev](https://github.com/alejsdev). From d309c9e1403e645977afa7809d61d88e776140fa Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 06:43:21 +0000 Subject: [PATCH 696/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20re?= =?UTF-8?q?quest=5Fforms=5Fand=5Ffiles=20(#13185)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../test_tutorial001.py | 19 +- .../test_tutorial001_an.py | 309 ----------------- .../test_tutorial001_an_py39.py | 317 ------------------ 3 files changed, 15 insertions(+), 630 deletions(-) delete mode 100644 tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py delete mode 100644 tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py diff --git a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py index 1e1ad2a87..d12219245 100644 --- a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py +++ b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001.py @@ -1,14 +1,25 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi import FastAPI from fastapi.testclient import TestClient +from ...utils import needs_py39 + -@pytest.fixture(name="app") -def get_app(): - from docs_src.request_forms_and_files.tutorial001 import app +@pytest.fixture( + name="app", + params=[ + "tutorial001", + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + ], +) +def get_app(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.request_forms_and_files.{request.param}") - return app + return mod.app @pytest.fixture(name="client") diff --git a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py deleted file mode 100644 index 5daf4dbf4..000000000 --- a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an.py +++ /dev/null @@ -1,309 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi import FastAPI -from fastapi.testclient import TestClient - - -@pytest.fixture(name="app") -def get_app(): - from docs_src.request_forms_and_files.tutorial001_an import app - - return app - - -@pytest.fixture(name="client") -def get_client(app: FastAPI): - client = TestClient(app) - return client - - -def test_post_form_no_body(client: TestClient): - response = client.post("/files/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "file"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "fileb"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "token"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_post_form_no_file(client: TestClient): - response = client.post("/files/", data={"token": "foo"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "file"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "fileb"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_post_body_json(client: TestClient): - response = client.post("/files/", json={"file": "Foo", "token": "Bar"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "file"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "fileb"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "token"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_post_file_no_token(tmp_path, app: FastAPI): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "fileb"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "token"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_post_files_and_token(tmp_path, app: FastAPI): - patha = tmp_path / "test.txt" - pathb = tmp_path / "testb.txt" - patha.write_text("") - pathb.write_text("") - - client = TestClient(app) - with patha.open("rb") as filea, pathb.open("rb") as fileb: - response = client.post( - "/files/", - data={"token": "foo"}, - files={"file": filea, "fileb": ("testb.txt", fileb, "text/plain")}, - ) - assert response.status_code == 200, response.text - assert response.json() == { - "file_size": 14, - "token": "foo", - "fileb_content_type": "text/plain", - } - - -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "required": ["file", "fileb", "token"], - "type": "object", - "properties": { - "file": {"title": "File", "type": "string", "format": "binary"}, - "fileb": { - "title": "Fileb", - "type": "string", - "format": "binary", - }, - "token": {"title": "Token", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py deleted file mode 100644 index 3f1204efa..000000000 --- a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py +++ /dev/null @@ -1,317 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi import FastAPI -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="app") -def get_app(): - from docs_src.request_forms_and_files.tutorial001_an_py39 import app - - return app - - -@pytest.fixture(name="client") -def get_client(app: FastAPI): - client = TestClient(app) - return client - - -@needs_py39 -def test_post_form_no_body(client: TestClient): - response = client.post("/files/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "file"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "fileb"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "token"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_post_form_no_file(client: TestClient): - response = client.post("/files/", data={"token": "foo"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "file"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "fileb"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_post_body_json(client: TestClient): - response = client.post("/files/", json={"file": "Foo", "token": "Bar"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "file"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "fileb"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "token"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_post_file_no_token(tmp_path, app: FastAPI): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "fileb"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "token"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_post_files_and_token(tmp_path, app: FastAPI): - patha = tmp_path / "test.txt" - pathb = tmp_path / "testb.txt" - patha.write_text("") - pathb.write_text("") - - client = TestClient(app) - with patha.open("rb") as filea, pathb.open("rb") as fileb: - response = client.post( - "/files/", - data={"token": "foo"}, - files={"file": filea, "fileb": ("testb.txt", fileb, "text/plain")}, - ) - assert response.status_code == 200, response.text - assert response.json() == { - "file_size": 14, - "token": "foo", - "fileb_content_type": "text/plain", - } - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "required": ["file", "fileb", "token"], - "type": "object", - "properties": { - "file": {"title": "File", "type": "string", "format": "binary"}, - "fileb": { - "title": "Fileb", - "type": "string", - "format": "binary", - }, - "token": {"title": "Token", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } From 0069963bbae58f7dcac15590e31205ab87e3cf12 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 06:43:44 +0000 Subject: [PATCH 697/932] =?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 [skip ci] --- 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 a9c19e858..2fa245cdc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for request_forms_and_files. PR [#13185](https://github.com/fastapi/fastapi/pull/13185) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for request_forms. PR [#13184](https://github.com/fastapi/fastapi/pull/13184) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for path_query_params. PR [#13181](https://github.com/fastapi/fastapi/pull/13181) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for path_operation_configurations. PR [#13180](https://github.com/fastapi/fastapi/pull/13180) by [@alejsdev](https://github.com/alejsdev). From 081901cc9900d03118ca752ac61cfe77d750539e Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 06:57:50 +0000 Subject: [PATCH 698/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20re?= =?UTF-8?q?quest=5Fmodel=20(#13195)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_tutorial003_01.py | 23 ++- .../test_tutorial003_01_py310.py | 160 ----------------- .../test_tutorial003_05.py | 25 ++- .../test_tutorial003_05_py310.py | 103 ----------- .../test_response_model/test_tutorial004.py | 23 ++- .../test_tutorial004_py310.py | 147 ---------------- .../test_tutorial004_py39.py | 147 ---------------- .../test_response_model/test_tutorial005.py | 25 ++- .../test_tutorial005_py310.py | 166 ------------------ .../test_response_model/test_tutorial006.py | 25 ++- .../test_tutorial006_py310.py | 166 ------------------ 11 files changed, 98 insertions(+), 912 deletions(-) delete mode 100644 tests/test_tutorial/test_response_model/test_tutorial003_01_py310.py delete mode 100644 tests/test_tutorial/test_response_model/test_tutorial003_05_py310.py delete mode 100644 tests/test_tutorial/test_response_model/test_tutorial004_py310.py delete mode 100644 tests/test_tutorial/test_response_model/test_tutorial004_py39.py delete mode 100644 tests/test_tutorial/test_response_model/test_tutorial005_py310.py delete mode 100644 tests/test_tutorial/test_response_model/test_tutorial006_py310.py diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_01.py b/tests/test_tutorial/test_response_model/test_tutorial003_01.py index 3a6a0b20d..3975856b6 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial003_01.py +++ b/tests/test_tutorial/test_response_model/test_tutorial003_01.py @@ -1,12 +1,27 @@ +import importlib + +import pytest from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient -from docs_src.response_model.tutorial003_01 import app +from ...utils import needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial003_01", + pytest.param("tutorial003_01_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.response_model.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_post_user(): +def test_post_user(client: TestClient): response = client.post( "/user/", json={ @@ -24,7 +39,7 @@ def test_post_user(): } -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_01_py310.py b/tests/test_tutorial/test_response_model/test_tutorial003_01_py310.py deleted file mode 100644 index 6985b9de6..000000000 --- a/tests/test_tutorial/test_response_model/test_tutorial003_01_py310.py +++ /dev/null @@ -1,160 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.response_model.tutorial003_01_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_user(client: TestClient): - response = client.post( - "/user/", - json={ - "username": "foo", - "password": "fighter", - "email": "foo@example.com", - "full_name": "Grave Dohl", - }, - ) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "foo", - "email": "foo@example.com", - "full_name": "Grave Dohl", - } - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/user/": { - "post": { - "summary": "Create User", - "operationId": "create_user_user__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserIn"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/BaseUser"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "BaseUser": { - "title": "BaseUser", - "required": IsOneOf( - ["username", "email", "full_name"], - # TODO: remove when deprecating Pydantic v1 - ["username", "email"], - ), - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": { - "title": "Email", - "type": "string", - "format": "email", - }, - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "UserIn": { - "title": "UserIn", - "required": ["username", "email", "password"], - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": { - "title": "Email", - "type": "string", - "format": "email", - }, - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_05.py b/tests/test_tutorial/test_response_model/test_tutorial003_05.py index c7a39cc74..9500852e1 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial003_05.py +++ b/tests/test_tutorial/test_response_model/test_tutorial003_05.py @@ -1,23 +1,38 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.response_model.tutorial003_05 import app +from ...utils import needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial003_05", + pytest.param("tutorial003_05_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.response_model.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_get_portal(): +def test_get_portal(client: TestClient): response = client.get("/portal") assert response.status_code == 200, response.text assert response.json() == {"message": "Here's your interdimensional portal."} -def test_get_redirect(): +def test_get_redirect(client: TestClient): response = client.get("/portal", params={"teleport": True}, follow_redirects=False) assert response.status_code == 307, response.text assert response.headers["location"] == "https://www.youtube.com/watch?v=dQw4w9WgXcQ" -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_05_py310.py b/tests/test_tutorial/test_response_model/test_tutorial003_05_py310.py deleted file mode 100644 index f80d62572..000000000 --- a/tests/test_tutorial/test_response_model/test_tutorial003_05_py310.py +++ /dev/null @@ -1,103 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.response_model.tutorial003_05_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_get_portal(client: TestClient): - response = client.get("/portal") - assert response.status_code == 200, response.text - assert response.json() == {"message": "Here's your interdimensional portal."} - - -@needs_py310 -def test_get_redirect(client: TestClient): - response = client.get("/portal", params={"teleport": True}, follow_redirects=False) - assert response.status_code == 307, response.text - assert response.headers["location"] == "https://www.youtube.com/watch?v=dQw4w9WgXcQ" - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/portal": { - "get": { - "summary": "Get Portal", - "operationId": "get_portal_portal_get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Teleport", - "type": "boolean", - "default": False, - }, - "name": "teleport", - "in": "query", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_response_model/test_tutorial004.py b/tests/test_tutorial/test_response_model/test_tutorial004.py index e9bde18dd..449a52b81 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial004.py +++ b/tests/test_tutorial/test_response_model/test_tutorial004.py @@ -1,10 +1,25 @@ +import importlib + import pytest from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient -from docs_src.response_model.tutorial004 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial004", + pytest.param("tutorial004_py39", marks=needs_py39), + pytest.param("tutorial004_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.response_model.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client @pytest.mark.parametrize( @@ -27,13 +42,13 @@ client = TestClient(app) ), ], ) -def test_get(url, data): +def test_get(url, data, client: TestClient): response = client.get(url) assert response.status_code == 200, response.text assert response.json() == data -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_response_model/test_tutorial004_py310.py b/tests/test_tutorial/test_response_model/test_tutorial004_py310.py deleted file mode 100644 index 6f8a3cbea..000000000 --- a/tests/test_tutorial/test_response_model/test_tutorial004_py310.py +++ /dev/null @@ -1,147 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.response_model.tutorial004_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "url,data", - [ - ("/items/foo", {"name": "Foo", "price": 50.2}), - ( - "/items/bar", - {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2}, - ), - ( - "/items/baz", - { - "name": "Baz", - "description": None, - "price": 50.2, - "tax": 10.5, - "tags": [], - }, - ), - ], -) -def test_get(url, data, client: TestClient): - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == data - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item", - "operationId": "read_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": IsOneOf( - ["name", "description", "price", "tax", "tags"], - # TODO: remove when deprecating Pydantic v1 - ["name", "price"], - ), - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "price": {"title": "Price", "type": "number"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "tax": {"title": "Tax", "type": "number", "default": 10.5}, - "tags": { - "title": "Tags", - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_response_model/test_tutorial004_py39.py b/tests/test_tutorial/test_response_model/test_tutorial004_py39.py deleted file mode 100644 index cfaa1eba2..000000000 --- a/tests/test_tutorial/test_response_model/test_tutorial004_py39.py +++ /dev/null @@ -1,147 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.response_model.tutorial004_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -@pytest.mark.parametrize( - "url,data", - [ - ("/items/foo", {"name": "Foo", "price": 50.2}), - ( - "/items/bar", - {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2}, - ), - ( - "/items/baz", - { - "name": "Baz", - "description": None, - "price": 50.2, - "tax": 10.5, - "tags": [], - }, - ), - ], -) -def test_get(url, data, client: TestClient): - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == data - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item", - "operationId": "read_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": IsOneOf( - ["name", "description", "price", "tax", "tags"], - # TODO: remove when deprecating Pydantic v1 - ["name", "price"], - ), - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "price": {"title": "Price", "type": "number"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "tax": {"title": "Tax", "type": "number", "default": 10.5}, - "tags": { - "title": "Tags", - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_response_model/test_tutorial005.py b/tests/test_tutorial/test_response_model/test_tutorial005.py index b20864c07..a633a3fdd 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial005.py +++ b/tests/test_tutorial/test_response_model/test_tutorial005.py @@ -1,18 +1,33 @@ +import importlib + +import pytest from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient -from docs_src.response_model.tutorial005 import app +from ...utils import needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial005", + pytest.param("tutorial005_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.response_model.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_read_item_name(): +def test_read_item_name(client: TestClient): response = client.get("/items/bar/name") assert response.status_code == 200, response.text assert response.json() == {"name": "Bar", "description": "The Bar fighters"} -def test_read_item_public_data(): +def test_read_item_public_data(client: TestClient): response = client.get("/items/bar/public") assert response.status_code == 200, response.text assert response.json() == { @@ -22,7 +37,7 @@ def test_read_item_public_data(): } -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_response_model/test_tutorial005_py310.py b/tests/test_tutorial/test_response_model/test_tutorial005_py310.py deleted file mode 100644 index de552c8f2..000000000 --- a/tests/test_tutorial/test_response_model/test_tutorial005_py310.py +++ /dev/null @@ -1,166 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.response_model.tutorial005_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_read_item_name(client: TestClient): - response = client.get("/items/bar/name") - assert response.status_code == 200, response.text - assert response.json() == {"name": "Bar", "description": "The Bar fighters"} - - -@needs_py310 -def test_read_item_public_data(client: TestClient): - response = client.get("/items/bar/public") - assert response.status_code == 200, response.text - assert response.json() == { - "name": "Bar", - "description": "The Bar fighters", - "price": 62, - } - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}/name": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item Name", - "operationId": "read_item_name_items__item_id__name_get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - } - }, - "/items/{item_id}/public": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item Public Data", - "operationId": "read_item_public_data_items__item_id__public_get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - } - }, - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": IsOneOf( - ["name", "description", "price", "tax"], - # TODO: remove when deprecating Pydantic v1 - ["name", "price"], - ), - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "price": {"title": "Price", "type": "number"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "tax": {"title": "Tax", "type": "number", "default": 10.5}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_response_model/test_tutorial006.py b/tests/test_tutorial/test_response_model/test_tutorial006.py index 1e47e2ead..863522d1b 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial006.py +++ b/tests/test_tutorial/test_response_model/test_tutorial006.py @@ -1,18 +1,33 @@ +import importlib + +import pytest from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient -from docs_src.response_model.tutorial006 import app +from ...utils import needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial006", + pytest.param("tutorial006_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.response_model.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_read_item_name(): +def test_read_item_name(client: TestClient): response = client.get("/items/bar/name") assert response.status_code == 200, response.text assert response.json() == {"name": "Bar", "description": "The Bar fighters"} -def test_read_item_public_data(): +def test_read_item_public_data(client: TestClient): response = client.get("/items/bar/public") assert response.status_code == 200, response.text assert response.json() == { @@ -22,7 +37,7 @@ def test_read_item_public_data(): } -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_response_model/test_tutorial006_py310.py b/tests/test_tutorial/test_response_model/test_tutorial006_py310.py deleted file mode 100644 index 40058b12d..000000000 --- a/tests/test_tutorial/test_response_model/test_tutorial006_py310.py +++ /dev/null @@ -1,166 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.response_model.tutorial006_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_read_item_name(client: TestClient): - response = client.get("/items/bar/name") - assert response.status_code == 200, response.text - assert response.json() == {"name": "Bar", "description": "The Bar fighters"} - - -@needs_py310 -def test_read_item_public_data(client: TestClient): - response = client.get("/items/bar/public") - assert response.status_code == 200, response.text - assert response.json() == { - "name": "Bar", - "description": "The Bar fighters", - "price": 62, - } - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}/name": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item Name", - "operationId": "read_item_name_items__item_id__name_get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - } - }, - "/items/{item_id}/public": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item Public Data", - "operationId": "read_item_public_data_items__item_id__public_get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - } - }, - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": IsOneOf( - ["name", "description", "price", "tax"], - # TODO: remove when deprecating Pydantic v1 - ["name", "price"], - ), - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "price": {"title": "Price", "type": "number"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "tax": {"title": "Tax", "type": "number", "default": 10.5}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } From 2c83a11a7d6971c9efbb80129d6db7d70c9cadf4 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 06:58:12 +0000 Subject: [PATCH 699/932] =?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 [skip ci] --- 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 2fa245cdc..933b7271e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for request_model. PR [#13195](https://github.com/fastapi/fastapi/pull/13195) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for request_forms_and_files. PR [#13185](https://github.com/fastapi/fastapi/pull/13185) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for request_forms. PR [#13184](https://github.com/fastapi/fastapi/pull/13184) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for path_query_params. PR [#13181](https://github.com/fastapi/fastapi/pull/13181) by [@alejsdev](https://github.com/alejsdev). From 3e12918325fcde4cd749ac4c7957fa95ecbc584b Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 22:30:50 +0000 Subject: [PATCH 700/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20sc?= =?UTF-8?q?hema=5Fextra=5Fexample=20(#13197)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../test_tutorial001.py | 18 +- .../test_tutorial001_pv1.py | 18 +- .../test_tutorial001_pv1_py310.py | 129 ------------- .../test_tutorial001_py310.py | 135 ------------- .../test_tutorial004.py | 27 ++- .../test_tutorial004_an.py | 168 ----------------- .../test_tutorial004_an_py310.py | 177 ------------------ .../test_tutorial004_an_py39.py | 177 ------------------ .../test_tutorial004_py310.py | 177 ------------------ .../test_tutorial005.py | 21 ++- .../test_tutorial005_an.py | 166 ---------------- .../test_tutorial005_an_py310.py | 170 ----------------- .../test_tutorial005_an_py39.py | 170 ----------------- .../test_tutorial005_py310.py | 170 ----------------- 14 files changed, 65 insertions(+), 1658 deletions(-) delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1_py310.py delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310.py delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial004_an.py delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py310.py delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py39.py delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial004_py310.py delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial005_an.py delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py310.py delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py39.py delete mode 100644 tests/test_tutorial/test_schema_extra_example/test_tutorial005_py310.py diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py index 98b187355..c21cbb4bc 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py @@ -1,14 +1,22 @@ +import importlib + import pytest from fastapi.testclient import TestClient -from ...utils import needs_pydanticv2 +from ...utils import needs_py310, needs_pydanticv2 -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial001 import app +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1.py index 3520ef61d..b79f42e64 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1.py @@ -1,14 +1,22 @@ +import importlib + import pytest from fastapi.testclient import TestClient -from ...utils import needs_pydanticv1 +from ...utils import needs_py310, needs_pydanticv1 -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial001_pv1 import app +@pytest.fixture( + name="client", + params=[ + "tutorial001_pv1", + pytest.param("tutorial001_pv1_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1_py310.py deleted file mode 100644 index b2a4d15b1..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1_py310.py +++ /dev/null @@ -1,129 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv1 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial001_pv1_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@needs_pydanticv1 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py310 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - # insert_assert(response.json()) - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"type": "integer", "title": "Item Id"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "properties": { - "detail": { - "items": {"$ref": "#/components/schemas/ValidationError"}, - "type": "array", - "title": "Detail", - } - }, - "type": "object", - "title": "HTTPValidationError", - }, - "Item": { - "properties": { - "name": {"type": "string", "title": "Name"}, - "description": {"type": "string", "title": "Description"}, - "price": {"type": "number", "title": "Price"}, - "tax": {"type": "number", "title": "Tax"}, - }, - "type": "object", - "required": ["name", "price"], - "title": "Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - } - ], - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - "type": "array", - "title": "Location", - }, - "msg": {"type": "string", "title": "Message"}, - "type": {"type": "string", "title": "Error Type"}, - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError", - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310.py deleted file mode 100644 index e63e33cda..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310.py +++ /dev/null @@ -1,135 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@needs_pydanticv2 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py310 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - # insert_assert(response.json()) - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "name": "item_id", - "in": "path", - "required": True, - "schema": {"type": "integer", "title": "Item Id"}, - } - ], - "requestBody": { - "required": True, - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "properties": { - "detail": { - "items": {"$ref": "#/components/schemas/ValidationError"}, - "type": "array", - "title": "Detail", - } - }, - "type": "object", - "title": "HTTPValidationError", - }, - "Item": { - "properties": { - "name": {"type": "string", "title": "Name"}, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - "price": {"type": "number", "title": "Price"}, - "tax": { - "anyOf": [{"type": "number"}, {"type": "null"}], - "title": "Tax", - }, - }, - "type": "object", - "required": ["name", "price"], - "title": "Item", - "examples": [ - { - "description": "A very nice Item", - "name": "Foo", - "price": 35.4, - "tax": 3.2, - } - ], - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - "type": "array", - "title": "Location", - }, - "msg": {"type": "string", "title": "Message"}, - "type": {"type": "string", "title": "Error Type"}, - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError", - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py index eac0d1e29..61aefd12a 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py @@ -1,13 +1,30 @@ +import importlib + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.schema_extra_example.tutorial004 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial004", + pytest.param("tutorial004_py310", marks=needs_py310), + "tutorial004_an", + pytest.param("tutorial004_an_py39", marks=needs_py39), + pytest.param("tutorial004_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -# Test required and embedded body parameters with no bodies sent -def test_post_body_example(): +def test_post_body_example(client: TestClient): response = client.put( "/items/5", json={ @@ -20,7 +37,7 @@ def test_post_body_example(): assert response.status_code == 200 -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an.py deleted file mode 100644 index a9cecd098..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an.py +++ /dev/null @@ -1,168 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.schema_extra_example.tutorial004_an import app - -client = TestClient(app) - - -# Test required and embedded body parameters with no bodies sent -def test_post_body_example(): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "$ref": "#/components/schemas/Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py310.py deleted file mode 100644 index b6a735599..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py310.py +++ /dev/null @@ -1,177 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial004_an_py310 import app - - client = TestClient(app) - return client - - -# Test required and embedded body parameters with no bodies sent -@needs_py310 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "$ref": "#/components/schemas/Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py39.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py39.py deleted file mode 100644 index 2493194a0..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py39.py +++ /dev/null @@ -1,177 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial004_an_py39 import app - - client = TestClient(app) - return client - - -# Test required and embedded body parameters with no bodies sent -@needs_py39 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "$ref": "#/components/schemas/Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_py310.py deleted file mode 100644 index 15f54bd5a..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_py310.py +++ /dev/null @@ -1,177 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial004_py310 import app - - client = TestClient(app) - return client - - -# Test required and embedded body parameters with no bodies sent -@needs_py310 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "$ref": "#/components/schemas/Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py index 94a40ed5a..12859227b 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py @@ -1,13 +1,26 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient +from ...utils import needs_py39, needs_py310 + -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial005 import app +@pytest.fixture( + name="client", + params=[ + "tutorial005", + pytest.param("tutorial005_py310", marks=needs_py310), + "tutorial005_an", + pytest.param("tutorial005_an_py39", marks=needs_py39), + pytest.param("tutorial005_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an.py deleted file mode 100644 index da92f98f6..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an.py +++ /dev/null @@ -1,166 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial005_an import app - - client = TestClient(app) - return client - - -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict({"$ref": "#/components/schemas/Item"}) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - } - ), - "examples": { - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": {"name": "Bar", "price": "35.4"}, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py310.py deleted file mode 100644 index 9109cb14e..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py310.py +++ /dev/null @@ -1,170 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial005_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py310 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict({"$ref": "#/components/schemas/Item"}) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - } - ), - "examples": { - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": {"name": "Bar", "price": "35.4"}, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py39.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py39.py deleted file mode 100644 index fd4ec0575..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py39.py +++ /dev/null @@ -1,170 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial005_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py39 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict({"$ref": "#/components/schemas/Item"}) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - } - ), - "examples": { - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": {"name": "Bar", "price": "35.4"}, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_py310.py deleted file mode 100644 index 05df53422..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_py310.py +++ /dev/null @@ -1,170 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial005_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py310 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict({"$ref": "#/components/schemas/Item"}) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - } - ), - "examples": { - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": {"name": "Bar", "price": "35.4"}, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } From 818eb1f365dd6daad7746499120b10a0a1e0d42d Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 22:31:13 +0000 Subject: [PATCH 701/932] =?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 [skip ci] --- 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 933b7271e..f1538d6f4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for schema_extra_example. PR [#13197](https://github.com/fastapi/fastapi/pull/13197) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for request_model. PR [#13195](https://github.com/fastapi/fastapi/pull/13195) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for request_forms_and_files. PR [#13185](https://github.com/fastapi/fastapi/pull/13185) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for request_forms. PR [#13184](https://github.com/fastapi/fastapi/pull/13184) by [@alejsdev](https://github.com/alejsdev). From 20079934334945cf1e527a37582742e1f8d6dbb0 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 22:35:40 +0000 Subject: [PATCH 702/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20se?= =?UTF-8?q?curity=20(#13200)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_security/test_tutorial001.py | 28 +- .../test_security/test_tutorial001_an.py | 57 --- .../test_security/test_tutorial001_an_py39.py | 68 --- .../test_security/test_tutorial003.py | 40 +- .../test_security/test_tutorial003_an.py | 207 --------- .../test_tutorial003_an_py310.py | 223 --------- .../test_security/test_tutorial003_an_py39.py | 223 --------- .../test_security/test_tutorial003_py310.py | 223 --------- .../test_security/test_tutorial005.py | 108 +++-- .../test_security/test_tutorial005_an.py | 409 ---------------- .../test_tutorial005_an_py310.py | 437 ------------------ .../test_security/test_tutorial005_an_py39.py | 437 ------------------ .../test_security/test_tutorial005_py310.py | 437 ------------------ .../test_security/test_tutorial005_py39.py | 437 ------------------ .../test_security/test_tutorial006.py | 29 +- .../test_security/test_tutorial006_an.py | 65 --- .../test_security/test_tutorial006_an_py39.py | 77 --- 17 files changed, 146 insertions(+), 3359 deletions(-) delete mode 100644 tests/test_tutorial/test_security/test_tutorial001_an.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial001_an_py39.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial003_an.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial003_an_py310.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial003_an_py39.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial003_py310.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial005_an.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial005_an_py310.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial005_an_py39.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial005_py310.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial005_py39.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial006_an.py delete mode 100644 tests/test_tutorial/test_security/test_tutorial006_an_py39.py diff --git a/tests/test_tutorial/test_security/test_tutorial001.py b/tests/test_tutorial/test_security/test_tutorial001.py index 417bed8f7..f572d6e3e 100644 --- a/tests/test_tutorial/test_security/test_tutorial001.py +++ b/tests/test_tutorial/test_security/test_tutorial001.py @@ -1,31 +1,47 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.security.tutorial001 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.security.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_no_token(): +def test_no_token(client: TestClient): response = client.get("/items") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Bearer" -def test_token(): +def test_token(client: TestClient): response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) assert response.status_code == 200, response.text assert response.json() == {"token": "testtoken"} -def test_incorrect_token(): +def test_incorrect_token(client: TestClient): response = client.get("/items", headers={"Authorization": "Notexistent testtoken"}) assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Bearer" -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_security/test_tutorial001_an.py b/tests/test_tutorial/test_security/test_tutorial001_an.py deleted file mode 100644 index 59460da7f..000000000 --- a/tests/test_tutorial/test_security/test_tutorial001_an.py +++ /dev/null @@ -1,57 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.security.tutorial001_an import app - -client = TestClient(app) - - -def test_no_token(): - response = client.get("/items") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_token(): - response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) - assert response.status_code == 200, response.text - assert response.json() == {"token": "testtoken"} - - -def test_incorrect_token(): - response = client.get("/items", headers={"Authorization": "Notexistent testtoken"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "security": [{"OAuth2PasswordBearer": []}], - } - } - }, - "components": { - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, - } - } - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial001_an_py39.py b/tests/test_tutorial/test_security/test_tutorial001_an_py39.py deleted file mode 100644 index d8e712773..000000000 --- a/tests/test_tutorial/test_security/test_tutorial001_an_py39.py +++ /dev/null @@ -1,68 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_no_token(client: TestClient): - response = client.get("/items") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_token(client: TestClient): - response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) - assert response.status_code == 200, response.text - assert response.json() == {"token": "testtoken"} - - -@needs_py39 -def test_incorrect_token(client: TestClient): - response = client.get("/items", headers={"Authorization": "Notexistent testtoken"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "security": [{"OAuth2PasswordBearer": []}], - } - } - }, - "components": { - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, - } - } - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial003.py b/tests/test_tutorial/test_security/test_tutorial003.py index 18d4680f6..7a4c99401 100644 --- a/tests/test_tutorial/test_security/test_tutorial003.py +++ b/tests/test_tutorial/test_security/test_tutorial003.py @@ -1,18 +1,36 @@ +import importlib + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.security.tutorial003 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial003", + pytest.param("tutorial003_py310", marks=needs_py310), + "tutorial003_an", + pytest.param("tutorial003_an_py39", marks=needs_py39), + pytest.param("tutorial003_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.security.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_login(): +def test_login(client: TestClient): response = client.post("/token", data={"username": "johndoe", "password": "secret"}) assert response.status_code == 200, response.text assert response.json() == {"access_token": "johndoe", "token_type": "bearer"} -def test_login_incorrect_password(): +def test_login_incorrect_password(client: TestClient): response = client.post( "/token", data={"username": "johndoe", "password": "incorrect"} ) @@ -20,20 +38,20 @@ def test_login_incorrect_password(): assert response.json() == {"detail": "Incorrect username or password"} -def test_login_incorrect_username(): +def test_login_incorrect_username(client: TestClient): response = client.post("/token", data={"username": "foo", "password": "secret"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "Incorrect username or password"} -def test_no_token(): +def test_no_token(client: TestClient): response = client.get("/users/me") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Bearer" -def test_token(): +def test_token(client: TestClient): response = client.get("/users/me", headers={"Authorization": "Bearer johndoe"}) assert response.status_code == 200, response.text assert response.json() == { @@ -45,14 +63,14 @@ def test_token(): } -def test_incorrect_token(): +def test_incorrect_token(client: TestClient): response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) assert response.status_code == 401, response.text assert response.json() == {"detail": "Invalid authentication credentials"} assert response.headers["WWW-Authenticate"] == "Bearer" -def test_incorrect_token_type(): +def test_incorrect_token_type(client: TestClient): response = client.get( "/users/me", headers={"Authorization": "Notexistent testtoken"} ) @@ -61,13 +79,13 @@ def test_incorrect_token_type(): assert response.headers["WWW-Authenticate"] == "Bearer" -def test_inactive_user(): +def test_inactive_user(client: TestClient): response = client.get("/users/me", headers={"Authorization": "Bearer alice"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "Inactive user"} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_security/test_tutorial003_an.py b/tests/test_tutorial/test_security/test_tutorial003_an.py deleted file mode 100644 index a8f64d0c6..000000000 --- a/tests/test_tutorial/test_security/test_tutorial003_an.py +++ /dev/null @@ -1,207 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.security.tutorial003_an import app - -client = TestClient(app) - - -def test_login(): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - assert response.json() == {"access_token": "johndoe", "token_type": "bearer"} - - -def test_login_incorrect_password(): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -def test_login_incorrect_username(): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -def test_no_token(): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_token(): - response = client.get("/users/me", headers={"Authorization": "Bearer johndoe"}) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "fakehashedsecret", - "disabled": False, - } - - -def test_incorrect_token(): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Invalid authentication credentials"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_incorrect_token_type(): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_inactive_user(): - response = client.get("/users/me", headers={"Authorization": "Bearer alice"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me_get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "Body_login_token_post": { - "title": "Body_login_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Grant Type", - "pattern": "password", - "type": "string", - } - ), - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial003_an_py310.py b/tests/test_tutorial/test_security/test_tutorial003_an_py310.py deleted file mode 100644 index 7cbbcee2f..000000000 --- a/tests/test_tutorial/test_security/test_tutorial003_an_py310.py +++ /dev/null @@ -1,223 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial003_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - assert response.json() == {"access_token": "johndoe", "token_type": "bearer"} - - -@needs_py310 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer johndoe"}) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "fakehashedsecret", - "disabled": False, - } - - -@needs_py310 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Invalid authentication credentials"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_inactive_user(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer alice"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me_get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "Body_login_token_post": { - "title": "Body_login_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Grant Type", - "pattern": "password", - "type": "string", - } - ), - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial003_an_py39.py b/tests/test_tutorial/test_security/test_tutorial003_an_py39.py deleted file mode 100644 index 7b21fbcc9..000000000 --- a/tests/test_tutorial/test_security/test_tutorial003_an_py39.py +++ /dev/null @@ -1,223 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial003_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - assert response.json() == {"access_token": "johndoe", "token_type": "bearer"} - - -@needs_py39 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py39 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py39 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer johndoe"}) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "fakehashedsecret", - "disabled": False, - } - - -@needs_py39 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Invalid authentication credentials"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_inactive_user(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer alice"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me_get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "Body_login_token_post": { - "title": "Body_login_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Grant Type", - "pattern": "password", - "type": "string", - } - ), - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial003_py310.py b/tests/test_tutorial/test_security/test_tutorial003_py310.py deleted file mode 100644 index 512504534..000000000 --- a/tests/test_tutorial/test_security/test_tutorial003_py310.py +++ /dev/null @@ -1,223 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial003_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - assert response.json() == {"access_token": "johndoe", "token_type": "bearer"} - - -@needs_py310 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer johndoe"}) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "fakehashedsecret", - "disabled": False, - } - - -@needs_py310 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Invalid authentication credentials"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_inactive_user(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer alice"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me_get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "Body_login_token_post": { - "title": "Body_login_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Grant Type", - "pattern": "password", - "type": "string", - } - ), - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial005.py b/tests/test_tutorial/test_security/test_tutorial005.py index 2e580dbb3..c7f791b03 100644 --- a/tests/test_tutorial/test_security/test_tutorial005.py +++ b/tests/test_tutorial/test_security/test_tutorial005.py @@ -1,18 +1,33 @@ +import importlib +from types import ModuleType + +import pytest from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient -from docs_src.security.tutorial005 import ( - app, - create_access_token, - fake_users_db, - get_password_hash, - verify_password, +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="mod", + params=[ + "tutorial005", + pytest.param("tutorial005_py310", marks=needs_py310), + "tutorial005_an", + pytest.param("tutorial005_py39", marks=needs_py39), + pytest.param("tutorial005_an_py39", marks=needs_py39), + pytest.param("tutorial005_an_py310", marks=needs_py310), + ], ) +def get_mod(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.security.{request.param}") -client = TestClient(app) + return mod -def get_access_token(username="johndoe", password="secret", scope=None): +def get_access_token( + *, username="johndoe", password="secret", scope=None, client: TestClient +): data = {"username": username, "password": password} if scope: data["scope"] = scope @@ -22,7 +37,8 @@ def get_access_token(username="johndoe", password="secret", scope=None): return access_token -def test_login(): +def test_login(mod: ModuleType): + client = TestClient(mod.app) response = client.post("/token", data={"username": "johndoe", "password": "secret"}) assert response.status_code == 200, response.text content = response.json() @@ -30,7 +46,8 @@ def test_login(): assert content["token_type"] == "bearer" -def test_login_incorrect_password(): +def test_login_incorrect_password(mod: ModuleType): + client = TestClient(mod.app) response = client.post( "/token", data={"username": "johndoe", "password": "incorrect"} ) @@ -38,21 +55,24 @@ def test_login_incorrect_password(): assert response.json() == {"detail": "Incorrect username or password"} -def test_login_incorrect_username(): +def test_login_incorrect_username(mod: ModuleType): + client = TestClient(mod.app) response = client.post("/token", data={"username": "foo", "password": "secret"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "Incorrect username or password"} -def test_no_token(): +def test_no_token(mod: ModuleType): + client = TestClient(mod.app) response = client.get("/users/me") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Bearer" -def test_token(): - access_token = get_access_token(scope="me") +def test_token(mod: ModuleType): + client = TestClient(mod.app) + access_token = get_access_token(scope="me", client=client) response = client.get( "/users/me", headers={"Authorization": f"Bearer {access_token}"} ) @@ -65,14 +85,16 @@ def test_token(): } -def test_incorrect_token(): +def test_incorrect_token(mod: ModuleType): + client = TestClient(mod.app) response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) assert response.status_code == 401, response.text assert response.json() == {"detail": "Could not validate credentials"} assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_incorrect_token_type(): +def test_incorrect_token_type(mod: ModuleType): + client = TestClient(mod.app) response = client.get( "/users/me", headers={"Authorization": "Notexistent testtoken"} ) @@ -81,20 +103,24 @@ def test_incorrect_token_type(): assert response.headers["WWW-Authenticate"] == "Bearer" -def test_verify_password(): - assert verify_password("secret", fake_users_db["johndoe"]["hashed_password"]) +def test_verify_password(mod: ModuleType): + assert mod.verify_password( + "secret", mod.fake_users_db["johndoe"]["hashed_password"] + ) -def test_get_password_hash(): - assert get_password_hash("secretalice") +def test_get_password_hash(mod: ModuleType): + assert mod.get_password_hash("secretalice") -def test_create_access_token(): - access_token = create_access_token(data={"data": "foo"}) +def test_create_access_token(mod: ModuleType): + access_token = mod.create_access_token(data={"data": "foo"}) assert access_token -def test_token_no_sub(): +def test_token_no_sub(mod: ModuleType): + client = TestClient(mod.app) + response = client.get( "/users/me", headers={ @@ -106,7 +132,9 @@ def test_token_no_sub(): assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_token_no_username(): +def test_token_no_username(mod: ModuleType): + client = TestClient(mod.app) + response = client.get( "/users/me", headers={ @@ -118,8 +146,10 @@ def test_token_no_username(): assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_token_no_scope(): - access_token = get_access_token() +def test_token_no_scope(mod: ModuleType): + client = TestClient(mod.app) + + access_token = get_access_token(client=client) response = client.get( "/users/me", headers={"Authorization": f"Bearer {access_token}"} ) @@ -128,7 +158,9 @@ def test_token_no_scope(): assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_token_nonexistent_user(): +def test_token_nonexistent_user(mod: ModuleType): + client = TestClient(mod.app) + response = client.get( "/users/me", headers={ @@ -140,9 +172,11 @@ def test_token_nonexistent_user(): assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_token_inactive_user(): +def test_token_inactive_user(mod: ModuleType): + client = TestClient(mod.app) + access_token = get_access_token( - username="alice", password="secretalice", scope="me" + username="alice", password="secretalice", scope="me", client=client ) response = client.get( "/users/me", headers={"Authorization": f"Bearer {access_token}"} @@ -151,8 +185,9 @@ def test_token_inactive_user(): assert response.json() == {"detail": "Inactive user"} -def test_read_items(): - access_token = get_access_token(scope="me items") +def test_read_items(mod: ModuleType): + client = TestClient(mod.app) + access_token = get_access_token(scope="me items", client=client) response = client.get( "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"} ) @@ -160,8 +195,9 @@ def test_read_items(): assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}] -def test_read_system_status(): - access_token = get_access_token() +def test_read_system_status(mod: ModuleType): + client = TestClient(mod.app) + access_token = get_access_token(client=client) response = client.get( "/status/", headers={"Authorization": f"Bearer {access_token}"} ) @@ -169,14 +205,16 @@ def test_read_system_status(): assert response.json() == {"status": "ok"} -def test_read_system_status_no_token(): +def test_read_system_status_no_token(mod: ModuleType): + client = TestClient(mod.app) response = client.get("/status/") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Bearer" -def test_openapi_schema(): +def test_openapi_schema(mod: ModuleType): + client = TestClient(mod.app) response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_security/test_tutorial005_an.py b/tests/test_tutorial/test_security/test_tutorial005_an.py deleted file mode 100644 index 04c7d60bc..000000000 --- a/tests/test_tutorial/test_security/test_tutorial005_an.py +++ /dev/null @@ -1,409 +0,0 @@ -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from docs_src.security.tutorial005_an import ( - app, - create_access_token, - fake_users_db, - get_password_hash, - verify_password, -) - -client = TestClient(app) - - -def get_access_token(username="johndoe", password="secret", scope=None): - data = {"username": username, "password": password} - if scope: - data["scope"] = scope - response = client.post("/token", data=data) - content = response.json() - access_token = content.get("access_token") - return access_token - - -def test_login(): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - content = response.json() - assert "access_token" in content - assert content["token_type"] == "bearer" - - -def test_login_incorrect_password(): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -def test_login_incorrect_username(): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -def test_no_token(): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_token(): - access_token = get_access_token(scope="me") - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "disabled": False, - } - - -def test_incorrect_token(): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -def test_incorrect_token_type(): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_verify_password(): - assert verify_password("secret", fake_users_db["johndoe"]["hashed_password"]) - - -def test_get_password_hash(): - assert get_password_hash("secretalice") - - -def test_create_access_token(): - access_token = create_access_token(data={"data": "foo"}) - assert access_token - - -def test_token_no_sub(): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -def test_token_no_username(): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -def test_token_no_scope(): - access_token = get_access_token() - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not enough permissions"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -def test_token_nonexistent_user(): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -def test_token_inactive_user(): - access_token = get_access_token( - username="alice", password="secretalice", scope="me" - ) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -def test_read_items(): - access_token = get_access_token(scope="me items") - response = client.get( - "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}] - - -def test_read_system_status(): - access_token = get_access_token() - response = client.get( - "/status/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"status": "ok"} - - -def test_read_system_status_no_token(): - response = client.get("/status/") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Token"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login For Access Token", - "operationId": "login_for_access_token_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_for_access_token_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me__get", - "security": [{"OAuth2PasswordBearer": ["me"]}], - } - }, - "/users/me/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Own Items", - "operationId": "read_own_items_users_me_items__get", - "security": [{"OAuth2PasswordBearer": ["items", "me"]}], - } - }, - "/status/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read System Status", - "operationId": "read_system_status_status__get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "User": { - "title": "User", - "required": IsOneOf( - ["username", "email", "full_name", "disabled"], - # TODO: remove when deprecating Pydantic v1 - ["username"], - ), - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": IsDict( - { - "title": "Email", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Email", "type": "string"} - ), - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - "disabled": IsDict( - { - "title": "Disabled", - "anyOf": [{"type": "boolean"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Disabled", "type": "boolean"} - ), - }, - }, - "Token": { - "title": "Token", - "required": ["access_token", "token_type"], - "type": "object", - "properties": { - "access_token": {"title": "Access Token", "type": "string"}, - "token_type": {"title": "Token Type", "type": "string"}, - }, - }, - "Body_login_for_access_token_token_post": { - "title": "Body_login_for_access_token_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Grant Type", - "pattern": "password", - "type": "string", - } - ), - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": { - "password": { - "scopes": { - "me": "Read information about the current user.", - "items": "Read items.", - }, - "tokenUrl": "token", - } - }, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial005_an_py310.py b/tests/test_tutorial/test_security/test_tutorial005_an_py310.py deleted file mode 100644 index 9c7f83ed2..000000000 --- a/tests/test_tutorial/test_security/test_tutorial005_an_py310.py +++ /dev/null @@ -1,437 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial005_an_py310 import app - - client = TestClient(app) - return client - - -def get_access_token( - *, username="johndoe", password="secret", scope=None, client: TestClient -): - data = {"username": username, "password": password} - if scope: - data["scope"] = scope - response = client.post("/token", data=data) - content = response.json() - access_token = content.get("access_token") - return access_token - - -@needs_py310 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - content = response.json() - assert "access_token" in content - assert content["token_type"] == "bearer" - - -@needs_py310 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_token(client: TestClient): - access_token = get_access_token(scope="me", client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "disabled": False, - } - - -@needs_py310 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_verify_password(): - from docs_src.security.tutorial005_an_py310 import fake_users_db, verify_password - - assert verify_password("secret", fake_users_db["johndoe"]["hashed_password"]) - - -@needs_py310 -def test_get_password_hash(): - from docs_src.security.tutorial005_an_py310 import get_password_hash - - assert get_password_hash("secretalice") - - -@needs_py310 -def test_create_access_token(): - from docs_src.security.tutorial005_an_py310 import create_access_token - - access_token = create_access_token(data={"data": "foo"}) - assert access_token - - -@needs_py310 -def test_token_no_sub(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_no_username(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_no_scope(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not enough permissions"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_nonexistent_user(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_inactive_user(client: TestClient): - access_token = get_access_token( - username="alice", password="secretalice", scope="me", client=client - ) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py310 -def test_read_items(client: TestClient): - access_token = get_access_token(scope="me items", client=client) - response = client.get( - "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}] - - -@needs_py310 -def test_read_system_status(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/status/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"status": "ok"} - - -@needs_py310 -def test_read_system_status_no_token(client: TestClient): - response = client.get("/status/") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Token"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login For Access Token", - "operationId": "login_for_access_token_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_for_access_token_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me__get", - "security": [{"OAuth2PasswordBearer": ["me"]}], - } - }, - "/users/me/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Own Items", - "operationId": "read_own_items_users_me_items__get", - "security": [{"OAuth2PasswordBearer": ["items", "me"]}], - } - }, - "/status/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read System Status", - "operationId": "read_system_status_status__get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "User": { - "title": "User", - "required": IsOneOf( - ["username", "email", "full_name", "disabled"], - # TODO: remove when deprecating Pydantic v1 - ["username"], - ), - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": IsDict( - { - "title": "Email", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Email", "type": "string"} - ), - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - "disabled": IsDict( - { - "title": "Disabled", - "anyOf": [{"type": "boolean"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Disabled", "type": "boolean"} - ), - }, - }, - "Token": { - "title": "Token", - "required": ["access_token", "token_type"], - "type": "object", - "properties": { - "access_token": {"title": "Access Token", "type": "string"}, - "token_type": {"title": "Token Type", "type": "string"}, - }, - }, - "Body_login_for_access_token_token_post": { - "title": "Body_login_for_access_token_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Grant Type", - "pattern": "password", - "type": "string", - } - ), - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": { - "password": { - "scopes": { - "me": "Read information about the current user.", - "items": "Read items.", - }, - "tokenUrl": "token", - } - }, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial005_an_py39.py b/tests/test_tutorial/test_security/test_tutorial005_an_py39.py deleted file mode 100644 index 04cc1b014..000000000 --- a/tests/test_tutorial/test_security/test_tutorial005_an_py39.py +++ /dev/null @@ -1,437 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial005_an_py39 import app - - client = TestClient(app) - return client - - -def get_access_token( - *, username="johndoe", password="secret", scope=None, client: TestClient -): - data = {"username": username, "password": password} - if scope: - data["scope"] = scope - response = client.post("/token", data=data) - content = response.json() - access_token = content.get("access_token") - return access_token - - -@needs_py39 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - content = response.json() - assert "access_token" in content - assert content["token_type"] == "bearer" - - -@needs_py39 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py39 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py39 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_token(client: TestClient): - access_token = get_access_token(scope="me", client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "disabled": False, - } - - -@needs_py39 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_verify_password(): - from docs_src.security.tutorial005_an_py39 import fake_users_db, verify_password - - assert verify_password("secret", fake_users_db["johndoe"]["hashed_password"]) - - -@needs_py39 -def test_get_password_hash(): - from docs_src.security.tutorial005_an_py39 import get_password_hash - - assert get_password_hash("secretalice") - - -@needs_py39 -def test_create_access_token(): - from docs_src.security.tutorial005_an_py39 import create_access_token - - access_token = create_access_token(data={"data": "foo"}) - assert access_token - - -@needs_py39 -def test_token_no_sub(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_no_username(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_no_scope(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not enough permissions"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_nonexistent_user(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_inactive_user(client: TestClient): - access_token = get_access_token( - username="alice", password="secretalice", scope="me", client=client - ) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py39 -def test_read_items(client: TestClient): - access_token = get_access_token(scope="me items", client=client) - response = client.get( - "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}] - - -@needs_py39 -def test_read_system_status(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/status/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"status": "ok"} - - -@needs_py39 -def test_read_system_status_no_token(client: TestClient): - response = client.get("/status/") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Token"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login For Access Token", - "operationId": "login_for_access_token_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_for_access_token_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me__get", - "security": [{"OAuth2PasswordBearer": ["me"]}], - } - }, - "/users/me/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Own Items", - "operationId": "read_own_items_users_me_items__get", - "security": [{"OAuth2PasswordBearer": ["items", "me"]}], - } - }, - "/status/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read System Status", - "operationId": "read_system_status_status__get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "User": { - "title": "User", - "required": IsOneOf( - ["username", "email", "full_name", "disabled"], - # TODO: remove when deprecating Pydantic v1 - ["username"], - ), - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": IsDict( - { - "title": "Email", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Email", "type": "string"} - ), - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - "disabled": IsDict( - { - "title": "Disabled", - "anyOf": [{"type": "boolean"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Disabled", "type": "boolean"} - ), - }, - }, - "Token": { - "title": "Token", - "required": ["access_token", "token_type"], - "type": "object", - "properties": { - "access_token": {"title": "Access Token", "type": "string"}, - "token_type": {"title": "Token Type", "type": "string"}, - }, - }, - "Body_login_for_access_token_token_post": { - "title": "Body_login_for_access_token_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Grant Type", - "pattern": "password", - "type": "string", - } - ), - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": { - "password": { - "scopes": { - "me": "Read information about the current user.", - "items": "Read items.", - }, - "tokenUrl": "token", - } - }, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial005_py310.py b/tests/test_tutorial/test_security/test_tutorial005_py310.py deleted file mode 100644 index 98c60c1c2..000000000 --- a/tests/test_tutorial/test_security/test_tutorial005_py310.py +++ /dev/null @@ -1,437 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial005_py310 import app - - client = TestClient(app) - return client - - -def get_access_token( - *, username="johndoe", password="secret", scope=None, client: TestClient -): - data = {"username": username, "password": password} - if scope: - data["scope"] = scope - response = client.post("/token", data=data) - content = response.json() - access_token = content.get("access_token") - return access_token - - -@needs_py310 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - content = response.json() - assert "access_token" in content - assert content["token_type"] == "bearer" - - -@needs_py310 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_token(client: TestClient): - access_token = get_access_token(scope="me", client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "disabled": False, - } - - -@needs_py310 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_verify_password(): - from docs_src.security.tutorial005_py310 import fake_users_db, verify_password - - assert verify_password("secret", fake_users_db["johndoe"]["hashed_password"]) - - -@needs_py310 -def test_get_password_hash(): - from docs_src.security.tutorial005_py310 import get_password_hash - - assert get_password_hash("secretalice") - - -@needs_py310 -def test_create_access_token(): - from docs_src.security.tutorial005_py310 import create_access_token - - access_token = create_access_token(data={"data": "foo"}) - assert access_token - - -@needs_py310 -def test_token_no_sub(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_no_username(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_no_scope(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not enough permissions"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_nonexistent_user(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_inactive_user(client: TestClient): - access_token = get_access_token( - username="alice", password="secretalice", scope="me", client=client - ) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py310 -def test_read_items(client: TestClient): - access_token = get_access_token(scope="me items", client=client) - response = client.get( - "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}] - - -@needs_py310 -def test_read_system_status(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/status/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"status": "ok"} - - -@needs_py310 -def test_read_system_status_no_token(client: TestClient): - response = client.get("/status/") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Token"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login For Access Token", - "operationId": "login_for_access_token_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_for_access_token_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me__get", - "security": [{"OAuth2PasswordBearer": ["me"]}], - } - }, - "/users/me/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Own Items", - "operationId": "read_own_items_users_me_items__get", - "security": [{"OAuth2PasswordBearer": ["items", "me"]}], - } - }, - "/status/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read System Status", - "operationId": "read_system_status_status__get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "User": { - "title": "User", - "required": IsOneOf( - ["username", "email", "full_name", "disabled"], - # TODO: remove when deprecating Pydantic v1 - ["username"], - ), - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": IsDict( - { - "title": "Email", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Email", "type": "string"} - ), - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - "disabled": IsDict( - { - "title": "Disabled", - "anyOf": [{"type": "boolean"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Disabled", "type": "boolean"} - ), - }, - }, - "Token": { - "title": "Token", - "required": ["access_token", "token_type"], - "type": "object", - "properties": { - "access_token": {"title": "Access Token", "type": "string"}, - "token_type": {"title": "Token Type", "type": "string"}, - }, - }, - "Body_login_for_access_token_token_post": { - "title": "Body_login_for_access_token_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Grant Type", - "pattern": "password", - "type": "string", - } - ), - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": { - "password": { - "scopes": { - "me": "Read information about the current user.", - "items": "Read items.", - }, - "tokenUrl": "token", - } - }, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial005_py39.py b/tests/test_tutorial/test_security/test_tutorial005_py39.py deleted file mode 100644 index cd2157d54..000000000 --- a/tests/test_tutorial/test_security/test_tutorial005_py39.py +++ /dev/null @@ -1,437 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial005_py39 import app - - client = TestClient(app) - return client - - -def get_access_token( - *, username="johndoe", password="secret", scope=None, client: TestClient -): - data = {"username": username, "password": password} - if scope: - data["scope"] = scope - response = client.post("/token", data=data) - content = response.json() - access_token = content.get("access_token") - return access_token - - -@needs_py39 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - content = response.json() - assert "access_token" in content - assert content["token_type"] == "bearer" - - -@needs_py39 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py39 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py39 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_token(client: TestClient): - access_token = get_access_token(scope="me", client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "disabled": False, - } - - -@needs_py39 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_verify_password(): - from docs_src.security.tutorial005_py39 import fake_users_db, verify_password - - assert verify_password("secret", fake_users_db["johndoe"]["hashed_password"]) - - -@needs_py39 -def test_get_password_hash(): - from docs_src.security.tutorial005_py39 import get_password_hash - - assert get_password_hash("secretalice") - - -@needs_py39 -def test_create_access_token(): - from docs_src.security.tutorial005_py39 import create_access_token - - access_token = create_access_token(data={"data": "foo"}) - assert access_token - - -@needs_py39 -def test_token_no_sub(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_no_username(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_no_scope(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not enough permissions"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_nonexistent_user(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_inactive_user(client: TestClient): - access_token = get_access_token( - username="alice", password="secretalice", scope="me", client=client - ) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py39 -def test_read_items(client: TestClient): - access_token = get_access_token(scope="me items", client=client) - response = client.get( - "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}] - - -@needs_py39 -def test_read_system_status(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/status/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"status": "ok"} - - -@needs_py39 -def test_read_system_status_no_token(client: TestClient): - response = client.get("/status/") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Token"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login For Access Token", - "operationId": "login_for_access_token_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_for_access_token_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me__get", - "security": [{"OAuth2PasswordBearer": ["me"]}], - } - }, - "/users/me/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Own Items", - "operationId": "read_own_items_users_me_items__get", - "security": [{"OAuth2PasswordBearer": ["items", "me"]}], - } - }, - "/status/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read System Status", - "operationId": "read_system_status_status__get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "User": { - "title": "User", - "required": IsOneOf( - ["username", "email", "full_name", "disabled"], - # TODO: remove when deprecating Pydantic v1 - ["username"], - ), - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": IsDict( - { - "title": "Email", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Email", "type": "string"} - ), - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - "disabled": IsDict( - { - "title": "Disabled", - "anyOf": [{"type": "boolean"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Disabled", "type": "boolean"} - ), - }, - }, - "Token": { - "title": "Token", - "required": ["access_token", "token_type"], - "type": "object", - "properties": { - "access_token": {"title": "Access Token", "type": "string"}, - "token_type": {"title": "Token Type", "type": "string"}, - }, - }, - "Body_login_for_access_token_token_post": { - "title": "Body_login_for_access_token_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Grant Type", - "pattern": "password", - "type": "string", - } - ), - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": { - "password": { - "scopes": { - "me": "Read information about the current user.", - "items": "Read items.", - }, - "tokenUrl": "token", - } - }, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial006.py b/tests/test_tutorial/test_security/test_tutorial006.py index dc459b6fd..40b413806 100644 --- a/tests/test_tutorial/test_security/test_tutorial006.py +++ b/tests/test_tutorial/test_security/test_tutorial006.py @@ -1,26 +1,41 @@ +import importlib from base64 import b64encode +import pytest from fastapi.testclient import TestClient -from docs_src.security.tutorial006 import app +from ...utils import needs_py39 -client = TestClient(app) +@pytest.fixture( + name="client", + params=[ + "tutorial006", + "tutorial006_an", + pytest.param("tutorial006_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.security.{request.param}") -def test_security_http_basic(): + client = TestClient(mod.app) + return client + + +def test_security_http_basic(client: TestClient): response = client.get("/users/me", auth=("john", "secret")) assert response.status_code == 200, response.text assert response.json() == {"username": "john", "password": "secret"} -def test_security_http_basic_no_credentials(): +def test_security_http_basic_no_credentials(client: TestClient): response = client.get("/users/me") assert response.json() == {"detail": "Not authenticated"} assert response.status_code == 401, response.text assert response.headers["WWW-Authenticate"] == "Basic" -def test_security_http_basic_invalid_credentials(): +def test_security_http_basic_invalid_credentials(client: TestClient): response = client.get( "/users/me", headers={"Authorization": "Basic notabase64token"} ) @@ -29,7 +44,7 @@ def test_security_http_basic_invalid_credentials(): assert response.json() == {"detail": "Invalid authentication credentials"} -def test_security_http_basic_non_basic_credentials(): +def test_security_http_basic_non_basic_credentials(client: TestClient): payload = b64encode(b"johnsecret").decode("ascii") auth_header = f"Basic {payload}" response = client.get("/users/me", headers={"Authorization": auth_header}) @@ -38,7 +53,7 @@ def test_security_http_basic_non_basic_credentials(): assert response.json() == {"detail": "Invalid authentication credentials"} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_security/test_tutorial006_an.py b/tests/test_tutorial/test_security/test_tutorial006_an.py deleted file mode 100644 index 52ddd938f..000000000 --- a/tests/test_tutorial/test_security/test_tutorial006_an.py +++ /dev/null @@ -1,65 +0,0 @@ -from base64 import b64encode - -from fastapi.testclient import TestClient - -from docs_src.security.tutorial006_an import app - -client = TestClient(app) - - -def test_security_http_basic(): - response = client.get("/users/me", auth=("john", "secret")) - assert response.status_code == 200, response.text - assert response.json() == {"username": "john", "password": "secret"} - - -def test_security_http_basic_no_credentials(): - response = client.get("/users/me") - assert response.json() == {"detail": "Not authenticated"} - assert response.status_code == 401, response.text - assert response.headers["WWW-Authenticate"] == "Basic" - - -def test_security_http_basic_invalid_credentials(): - response = client.get( - "/users/me", headers={"Authorization": "Basic notabase64token"} - ) - assert response.status_code == 401, response.text - assert response.headers["WWW-Authenticate"] == "Basic" - assert response.json() == {"detail": "Invalid authentication credentials"} - - -def test_security_http_basic_non_basic_credentials(): - payload = b64encode(b"johnsecret").decode("ascii") - auth_header = f"Basic {payload}" - response = client.get("/users/me", headers={"Authorization": auth_header}) - assert response.status_code == 401, response.text - assert response.headers["WWW-Authenticate"] == "Basic" - assert response.json() == {"detail": "Invalid authentication credentials"} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/me": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Current User", - "operationId": "read_current_user_users_me_get", - "security": [{"HTTPBasic": []}], - } - } - }, - "components": { - "securitySchemes": {"HTTPBasic": {"type": "http", "scheme": "basic"}} - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial006_an_py39.py b/tests/test_tutorial/test_security/test_tutorial006_an_py39.py deleted file mode 100644 index 52b22e573..000000000 --- a/tests/test_tutorial/test_security/test_tutorial006_an_py39.py +++ /dev/null @@ -1,77 +0,0 @@ -from base64 import b64encode - -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial006_an import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_security_http_basic(client: TestClient): - response = client.get("/users/me", auth=("john", "secret")) - assert response.status_code == 200, response.text - assert response.json() == {"username": "john", "password": "secret"} - - -@needs_py39 -def test_security_http_basic_no_credentials(client: TestClient): - response = client.get("/users/me") - assert response.json() == {"detail": "Not authenticated"} - assert response.status_code == 401, response.text - assert response.headers["WWW-Authenticate"] == "Basic" - - -@needs_py39 -def test_security_http_basic_invalid_credentials(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Basic notabase64token"} - ) - assert response.status_code == 401, response.text - assert response.headers["WWW-Authenticate"] == "Basic" - assert response.json() == {"detail": "Invalid authentication credentials"} - - -@needs_py39 -def test_security_http_basic_non_basic_credentials(client: TestClient): - payload = b64encode(b"johnsecret").decode("ascii") - auth_header = f"Basic {payload}" - response = client.get("/users/me", headers={"Authorization": auth_header}) - assert response.status_code == 401, response.text - assert response.headers["WWW-Authenticate"] == "Basic" - assert response.json() == {"detail": "Invalid authentication credentials"} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/me": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Current User", - "operationId": "read_current_user_users_me_get", - "security": [{"HTTPBasic": []}], - } - } - }, - "components": { - "securitySchemes": {"HTTPBasic": {"type": "http", "scheme": "basic"}} - }, - } From 6d51389f75d0e5fff17edc0e71bba604a744e440 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 22:36:07 +0000 Subject: [PATCH 703/932] =?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 [skip ci] --- 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 f1538d6f4..a604e5169 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for security. PR [#13200](https://github.com/fastapi/fastapi/pull/13200) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for schema_extra_example. PR [#13197](https://github.com/fastapi/fastapi/pull/13197) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for request_model. PR [#13195](https://github.com/fastapi/fastapi/pull/13195) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for request_forms_and_files. PR [#13185](https://github.com/fastapi/fastapi/pull/13185) by [@alejsdev](https://github.com/alejsdev). From 39698df8069b8cd705dd4cb2194bbf447d3eec49 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 22:36:49 +0000 Subject: [PATCH 704/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20se?= =?UTF-8?q?parate=5Fopenapi=5Fschemas=20(#13201)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../test_tutorial001.py | 19 ++- .../test_tutorial001_py310.py | 136 ------------------ .../test_tutorial001_py39.py | 136 ------------------ .../test_tutorial002.py | 19 ++- .../test_tutorial002_py310.py | 136 ------------------ .../test_tutorial002_py39.py | 136 ------------------ 6 files changed, 28 insertions(+), 554 deletions(-) delete mode 100644 tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py310.py delete mode 100644 tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py39.py delete mode 100644 tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py310.py delete mode 100644 tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py39.py diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py index cdfae9f8c..059fb889b 100644 --- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py +++ b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py @@ -1,14 +1,23 @@ +import importlib + import pytest from fastapi.testclient import TestClient -from ...utils import needs_pydanticv2 +from ...utils import needs_py39, needs_py310, needs_pydanticv2 -@pytest.fixture(name="client") -def get_client() -> TestClient: - from docs_src.separate_openapi_schemas.tutorial001 import app +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + pytest.param("tutorial001_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest) -> TestClient: + mod = importlib.import_module(f"docs_src.separate_openapi_schemas.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py310.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py310.py deleted file mode 100644 index 3b22146f6..000000000 --- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py310.py +++ /dev/null @@ -1,136 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client() -> TestClient: - from docs_src.separate_openapi_schemas.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_create_item(client: TestClient) -> None: - response = client.post("/items/", json={"name": "Foo"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Foo", "description": None} - - -@needs_py310 -def test_read_items(client: TestClient) -> None: - response = client.get("/items/") - assert response.status_code == 200, response.text - assert response.json() == [ - { - "name": "Portal Gun", - "description": "Device to travel through the multi-rick-verse", - }, - {"name": "Plumbus", "description": None}, - ] - - -@needs_py310 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "items": {"$ref": "#/components/schemas/Item"}, - "type": "array", - "title": "Response Read Items Items Get", - } - } - }, - } - }, - }, - "post": { - "summary": "Create Item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "properties": { - "detail": { - "items": {"$ref": "#/components/schemas/ValidationError"}, - "type": "array", - "title": "Detail", - } - }, - "type": "object", - "title": "HTTPValidationError", - }, - "Item": { - "properties": { - "name": {"type": "string", "title": "Name"}, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - }, - "type": "object", - "required": ["name"], - "title": "Item", - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - "type": "array", - "title": "Location", - }, - "msg": {"type": "string", "title": "Message"}, - "type": {"type": "string", "title": "Error Type"}, - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError", - }, - } - }, - } diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py39.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py39.py deleted file mode 100644 index 991abe811..000000000 --- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py39.py +++ /dev/null @@ -1,136 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client() -> TestClient: - from docs_src.separate_openapi_schemas.tutorial001_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_create_item(client: TestClient) -> None: - response = client.post("/items/", json={"name": "Foo"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Foo", "description": None} - - -@needs_py39 -def test_read_items(client: TestClient) -> None: - response = client.get("/items/") - assert response.status_code == 200, response.text - assert response.json() == [ - { - "name": "Portal Gun", - "description": "Device to travel through the multi-rick-verse", - }, - {"name": "Plumbus", "description": None}, - ] - - -@needs_py39 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "items": {"$ref": "#/components/schemas/Item"}, - "type": "array", - "title": "Response Read Items Items Get", - } - } - }, - } - }, - }, - "post": { - "summary": "Create Item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "properties": { - "detail": { - "items": {"$ref": "#/components/schemas/ValidationError"}, - "type": "array", - "title": "Detail", - } - }, - "type": "object", - "title": "HTTPValidationError", - }, - "Item": { - "properties": { - "name": {"type": "string", "title": "Name"}, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - }, - "type": "object", - "required": ["name"], - "title": "Item", - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - "type": "array", - "title": "Location", - }, - "msg": {"type": "string", "title": "Message"}, - "type": {"type": "string", "title": "Error Type"}, - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError", - }, - } - }, - } diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py index d2cf7945b..cc9afeab7 100644 --- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py +++ b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py @@ -1,14 +1,23 @@ +import importlib + import pytest from fastapi.testclient import TestClient -from ...utils import needs_pydanticv2 +from ...utils import needs_py39, needs_py310, needs_pydanticv2 -@pytest.fixture(name="client") -def get_client() -> TestClient: - from docs_src.separate_openapi_schemas.tutorial002 import app +@pytest.fixture( + name="client", + params=[ + "tutorial002", + pytest.param("tutorial002_py310", marks=needs_py310), + pytest.param("tutorial002_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest) -> TestClient: + mod = importlib.import_module(f"docs_src.separate_openapi_schemas.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py310.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py310.py deleted file mode 100644 index 89c9ce977..000000000 --- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py310.py +++ /dev/null @@ -1,136 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client() -> TestClient: - from docs_src.separate_openapi_schemas.tutorial002_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_create_item(client: TestClient) -> None: - response = client.post("/items/", json={"name": "Foo"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Foo", "description": None} - - -@needs_py310 -def test_read_items(client: TestClient) -> None: - response = client.get("/items/") - assert response.status_code == 200, response.text - assert response.json() == [ - { - "name": "Portal Gun", - "description": "Device to travel through the multi-rick-verse", - }, - {"name": "Plumbus", "description": None}, - ] - - -@needs_py310 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "items": {"$ref": "#/components/schemas/Item"}, - "type": "array", - "title": "Response Read Items Items Get", - } - } - }, - } - }, - }, - "post": { - "summary": "Create Item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "properties": { - "detail": { - "items": {"$ref": "#/components/schemas/ValidationError"}, - "type": "array", - "title": "Detail", - } - }, - "type": "object", - "title": "HTTPValidationError", - }, - "Item": { - "properties": { - "name": {"type": "string", "title": "Name"}, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - }, - "type": "object", - "required": ["name"], - "title": "Item", - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - "type": "array", - "title": "Location", - }, - "msg": {"type": "string", "title": "Message"}, - "type": {"type": "string", "title": "Error Type"}, - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError", - }, - } - }, - } diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py39.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py39.py deleted file mode 100644 index 6ac3d8f79..000000000 --- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py39.py +++ /dev/null @@ -1,136 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client() -> TestClient: - from docs_src.separate_openapi_schemas.tutorial002_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_create_item(client: TestClient) -> None: - response = client.post("/items/", json={"name": "Foo"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Foo", "description": None} - - -@needs_py39 -def test_read_items(client: TestClient) -> None: - response = client.get("/items/") - assert response.status_code == 200, response.text - assert response.json() == [ - { - "name": "Portal Gun", - "description": "Device to travel through the multi-rick-verse", - }, - {"name": "Plumbus", "description": None}, - ] - - -@needs_py39 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "items": {"$ref": "#/components/schemas/Item"}, - "type": "array", - "title": "Response Read Items Items Get", - } - } - }, - } - }, - }, - "post": { - "summary": "Create Item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "properties": { - "detail": { - "items": {"$ref": "#/components/schemas/ValidationError"}, - "type": "array", - "title": "Detail", - } - }, - "type": "object", - "title": "HTTPValidationError", - }, - "Item": { - "properties": { - "name": {"type": "string", "title": "Name"}, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - }, - "type": "object", - "required": ["name"], - "title": "Item", - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - "type": "array", - "title": "Location", - }, - "msg": {"type": "string", "title": "Message"}, - "type": {"type": "string", "title": "Error Type"}, - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError", - }, - } - }, - } From b5e40a6233d93e8805ba4c843bc82893d074d31a Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 22:37:13 +0000 Subject: [PATCH 705/932] =?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 [skip ci] --- 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 a604e5169..169345509 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for separate_openapi_schemas. PR [#13201](https://github.com/fastapi/fastapi/pull/13201) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for security. PR [#13200](https://github.com/fastapi/fastapi/pull/13200) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for schema_extra_example. PR [#13197](https://github.com/fastapi/fastapi/pull/13197) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for request_model. PR [#13195](https://github.com/fastapi/fastapi/pull/13195) by [@alejsdev](https://github.com/alejsdev). From 182c28e57acace06f9c3e9f11fd5096be5bac781 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 22:39:18 +0000 Subject: [PATCH 706/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20re?= =?UTF-8?q?quest=5Fform=5Fmodels=20=20(#13183)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sofie Van Landeghem --- .../test_tutorial001.py | 19 +- .../test_tutorial001_an.py | 232 ----------------- .../test_tutorial001_an_py39.py | 240 ------------------ .../test_tutorial002.py | 19 +- .../test_tutorial002_an.py | 196 -------------- .../test_tutorial002_an_py39.py | 203 --------------- .../test_tutorial002_pv1.py | 26 +- .../test_tutorial002_pv1_an.py | 196 -------------- .../test_tutorial002_pv1_an_p39.py | 203 --------------- 9 files changed, 50 insertions(+), 1284 deletions(-) delete mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial001_an.py delete mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py delete mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial002_an.py delete mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py delete mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py delete mode 100644 tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001.py b/tests/test_tutorial/test_request_form_models/test_tutorial001.py index 46c130ee8..1ca3c96d3 100644 --- a/tests/test_tutorial/test_request_form_models/test_tutorial001.py +++ b/tests/test_tutorial/test_request_form_models/test_tutorial001.py @@ -1,13 +1,24 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient +from ...utils import needs_py39 + -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial001 import app +@pytest.fixture( + name="client", + params=[ + "tutorial001", + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.request_form_models.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py b/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py deleted file mode 100644 index 4e14d89c8..000000000 --- a/tests/test_tutorial/test_request_form_models/test_tutorial001_an.py +++ /dev/null @@ -1,232 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial001_an import app - - client = TestClient(app) - return client - - -def test_post_body_form(client: TestClient): - response = client.post("/login/", data={"username": "Foo", "password": "secret"}) - assert response.status_code == 200 - assert response.json() == {"username": "Foo", "password": "secret"} - - -def test_post_body_form_no_password(client: TestClient): - response = client.post("/login/", data={"username": "Foo"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {"username": "Foo"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -def test_post_body_form_no_username(client: TestClient): - response = client.post("/login/", data={"password": "secret"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {"password": "secret"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -def test_post_body_form_no_data(client: TestClient): - response = client.post("/login/") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_post_body_json(client: TestClient): - response = client.post("/login/", json={"username": "Foo", "password": "secret"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/login/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_login__post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": {"$ref": "#/components/schemas/FormData"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "FormData": { - "properties": { - "username": {"type": "string", "title": "Username"}, - "password": {"type": "string", "title": "Password"}, - }, - "type": "object", - "required": ["username", "password"], - "title": "FormData", - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py deleted file mode 100644 index 2e6426aa7..000000000 --- a/tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py +++ /dev/null @@ -1,240 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from tests.utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_body_form(client: TestClient): - response = client.post("/login/", data={"username": "Foo", "password": "secret"}) - assert response.status_code == 200 - assert response.json() == {"username": "Foo", "password": "secret"} - - -@needs_py39 -def test_post_body_form_no_password(client: TestClient): - response = client.post("/login/", data={"username": "Foo"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {"username": "Foo"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py39 -def test_post_body_form_no_username(client: TestClient): - response = client.post("/login/", data={"password": "secret"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {"password": "secret"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py39 -def test_post_body_form_no_data(client: TestClient): - response = client.post("/login/") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_post_body_json(client: TestClient): - response = client.post("/login/", json={"username": "Foo", "password": "secret"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "username"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "password"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/login/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_login__post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": {"$ref": "#/components/schemas/FormData"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "FormData": { - "properties": { - "username": {"type": "string", "title": "Username"}, - "password": {"type": "string", "title": "Password"}, - }, - "type": "object", - "required": ["username", "password"], - "title": "FormData", - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002.py b/tests/test_tutorial/test_request_form_models/test_tutorial002.py index 76f480001..b3f6be63a 100644 --- a/tests/test_tutorial/test_request_form_models/test_tutorial002.py +++ b/tests/test_tutorial/test_request_form_models/test_tutorial002.py @@ -1,14 +1,23 @@ +import importlib + import pytest from fastapi.testclient import TestClient -from tests.utils import needs_pydanticv2 +from ...utils import needs_py39, needs_pydanticv2 -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial002 import app +@pytest.fixture( + name="client", + params=[ + "tutorial002", + "tutorial002_an", + pytest.param("tutorial002_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.request_form_models.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_an.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_an.py deleted file mode 100644 index 179b2977d..000000000 --- a/tests/test_tutorial/test_request_form_models/test_tutorial002_an.py +++ /dev/null @@ -1,196 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from tests.utils import needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial002_an import app - - client = TestClient(app) - return client - - -@needs_pydanticv2 -def test_post_body_form(client: TestClient): - response = client.post("/login/", data={"username": "Foo", "password": "secret"}) - assert response.status_code == 200 - assert response.json() == {"username": "Foo", "password": "secret"} - - -@needs_pydanticv2 -def test_post_body_extra_form(client: TestClient): - response = client.post( - "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} - ) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "extra_forbidden", - "loc": ["body", "extra"], - "msg": "Extra inputs are not permitted", - "input": "extra", - } - ] - } - - -@needs_pydanticv2 -def test_post_body_form_no_password(client: TestClient): - response = client.post("/login/", data={"username": "Foo"}) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {"username": "Foo"}, - } - ] - } - - -@needs_pydanticv2 -def test_post_body_form_no_username(client: TestClient): - response = client.post("/login/", data={"password": "secret"}) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {"password": "secret"}, - } - ] - } - - -@needs_pydanticv2 -def test_post_body_form_no_data(client: TestClient): - response = client.post("/login/") - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - - -@needs_pydanticv2 -def test_post_body_json(client: TestClient): - response = client.post("/login/", json={"username": "Foo", "password": "secret"}) - assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - - -@needs_pydanticv2 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/login/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_login__post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": {"$ref": "#/components/schemas/FormData"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "FormData": { - "properties": { - "username": {"type": "string", "title": "Username"}, - "password": {"type": "string", "title": "Password"}, - }, - "additionalProperties": False, - "type": "object", - "required": ["username", "password"], - "title": "FormData", - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py deleted file mode 100644 index 510ad9d7c..000000000 --- a/tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py +++ /dev/null @@ -1,203 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from tests.utils import needs_py39, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial002_an_py39 import app - - client = TestClient(app) - return client - - -@needs_pydanticv2 -@needs_py39 -def test_post_body_form(client: TestClient): - response = client.post("/login/", data={"username": "Foo", "password": "secret"}) - assert response.status_code == 200 - assert response.json() == {"username": "Foo", "password": "secret"} - - -@needs_pydanticv2 -@needs_py39 -def test_post_body_extra_form(client: TestClient): - response = client.post( - "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} - ) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "extra_forbidden", - "loc": ["body", "extra"], - "msg": "Extra inputs are not permitted", - "input": "extra", - } - ] - } - - -@needs_pydanticv2 -@needs_py39 -def test_post_body_form_no_password(client: TestClient): - response = client.post("/login/", data={"username": "Foo"}) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {"username": "Foo"}, - } - ] - } - - -@needs_pydanticv2 -@needs_py39 -def test_post_body_form_no_username(client: TestClient): - response = client.post("/login/", data={"password": "secret"}) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {"password": "secret"}, - } - ] - } - - -@needs_pydanticv2 -@needs_py39 -def test_post_body_form_no_data(client: TestClient): - response = client.post("/login/") - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - - -@needs_pydanticv2 -@needs_py39 -def test_post_body_json(client: TestClient): - response = client.post("/login/", json={"username": "Foo", "password": "secret"}) - assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "type": "missing", - "loc": ["body", "username"], - "msg": "Field required", - "input": {}, - }, - { - "type": "missing", - "loc": ["body", "password"], - "msg": "Field required", - "input": {}, - }, - ] - } - - -@needs_pydanticv2 -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/login/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_login__post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": {"$ref": "#/components/schemas/FormData"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "FormData": { - "properties": { - "username": {"type": "string", "title": "Username"}, - "password": {"type": "string", "title": "Password"}, - }, - "additionalProperties": False, - "type": "object", - "required": ["username", "password"], - "title": "FormData", - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py index 249b9379d..b503f23a5 100644 --- a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py +++ b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py @@ -1,17 +1,27 @@ +import importlib + import pytest from fastapi.testclient import TestClient -from tests.utils import needs_pydanticv1 +from ...utils import needs_py39, needs_pydanticv1 -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial002_pv1 import app +@pytest.fixture( + name="client", + params=[ + "tutorial002_pv1", + "tutorial002_pv1_an", + pytest.param("tutorial002_pv1_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.request_form_models.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client +# TODO: remove when deprecating Pydantic v1 @needs_pydanticv1 def test_post_body_form(client: TestClient): response = client.post("/login/", data={"username": "Foo", "password": "secret"}) @@ -19,6 +29,7 @@ def test_post_body_form(client: TestClient): assert response.json() == {"username": "Foo", "password": "secret"} +# TODO: remove when deprecating Pydantic v1 @needs_pydanticv1 def test_post_body_extra_form(client: TestClient): response = client.post( @@ -36,6 +47,7 @@ def test_post_body_extra_form(client: TestClient): } +# TODO: remove when deprecating Pydantic v1 @needs_pydanticv1 def test_post_body_form_no_password(client: TestClient): response = client.post("/login/", data={"username": "Foo"}) @@ -51,6 +63,7 @@ def test_post_body_form_no_password(client: TestClient): } +# TODO: remove when deprecating Pydantic v1 @needs_pydanticv1 def test_post_body_form_no_username(client: TestClient): response = client.post("/login/", data={"password": "secret"}) @@ -66,6 +79,7 @@ def test_post_body_form_no_username(client: TestClient): } +# TODO: remove when deprecating Pydantic v1 @needs_pydanticv1 def test_post_body_form_no_data(client: TestClient): response = client.post("/login/") @@ -86,6 +100,7 @@ def test_post_body_form_no_data(client: TestClient): } +# TODO: remove when deprecating Pydantic v1 @needs_pydanticv1 def test_post_body_json(client: TestClient): response = client.post("/login/", json={"username": "Foo", "password": "secret"}) @@ -106,6 +121,7 @@ def test_post_body_json(client: TestClient): } +# TODO: remove when deprecating Pydantic v1 @needs_pydanticv1 def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py deleted file mode 100644 index 44cb3c32b..000000000 --- a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py +++ /dev/null @@ -1,196 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from tests.utils import needs_pydanticv1 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial002_pv1_an import app - - client = TestClient(app) - return client - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -def test_post_body_form(client: TestClient): - response = client.post("/login/", data={"username": "Foo", "password": "secret"}) - assert response.status_code == 200 - assert response.json() == {"username": "Foo", "password": "secret"} - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -def test_post_body_extra_form(client: TestClient): - response = client.post( - "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} - ) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "value_error.extra", - "loc": ["body", "extra"], - "msg": "extra fields not permitted", - } - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -def test_post_body_form_no_password(client: TestClient): - response = client.post("/login/", data={"username": "Foo"}) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "value_error.missing", - "loc": ["body", "password"], - "msg": "field required", - } - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -def test_post_body_form_no_username(client: TestClient): - response = client.post("/login/", data={"password": "secret"}) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "value_error.missing", - "loc": ["body", "username"], - "msg": "field required", - } - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -def test_post_body_form_no_data(client: TestClient): - response = client.post("/login/") - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "value_error.missing", - "loc": ["body", "username"], - "msg": "field required", - }, - { - "type": "value_error.missing", - "loc": ["body", "password"], - "msg": "field required", - }, - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -def test_post_body_json(client: TestClient): - response = client.post("/login/", json={"username": "Foo", "password": "secret"}) - assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "type": "value_error.missing", - "loc": ["body", "username"], - "msg": "field required", - }, - { - "type": "value_error.missing", - "loc": ["body", "password"], - "msg": "field required", - }, - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/login/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_login__post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": {"$ref": "#/components/schemas/FormData"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "FormData": { - "properties": { - "username": {"type": "string", "title": "Username"}, - "password": {"type": "string", "title": "Password"}, - }, - "additionalProperties": False, - "type": "object", - "required": ["username", "password"], - "title": "FormData", - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py b/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py deleted file mode 100644 index 899549e40..000000000 --- a/tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py +++ /dev/null @@ -1,203 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from tests.utils import needs_py39, needs_pydanticv1 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_form_models.tutorial002_pv1_an_py39 import app - - client = TestClient(app) - return client - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -@needs_py39 -def test_post_body_form(client: TestClient): - response = client.post("/login/", data={"username": "Foo", "password": "secret"}) - assert response.status_code == 200 - assert response.json() == {"username": "Foo", "password": "secret"} - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -@needs_py39 -def test_post_body_extra_form(client: TestClient): - response = client.post( - "/login/", data={"username": "Foo", "password": "secret", "extra": "extra"} - ) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "value_error.extra", - "loc": ["body", "extra"], - "msg": "extra fields not permitted", - } - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -@needs_py39 -def test_post_body_form_no_password(client: TestClient): - response = client.post("/login/", data={"username": "Foo"}) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "value_error.missing", - "loc": ["body", "password"], - "msg": "field required", - } - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -@needs_py39 -def test_post_body_form_no_username(client: TestClient): - response = client.post("/login/", data={"password": "secret"}) - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "value_error.missing", - "loc": ["body", "username"], - "msg": "field required", - } - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -@needs_py39 -def test_post_body_form_no_data(client: TestClient): - response = client.post("/login/") - assert response.status_code == 422 - assert response.json() == { - "detail": [ - { - "type": "value_error.missing", - "loc": ["body", "username"], - "msg": "field required", - }, - { - "type": "value_error.missing", - "loc": ["body", "password"], - "msg": "field required", - }, - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -@needs_py39 -def test_post_body_json(client: TestClient): - response = client.post("/login/", json={"username": "Foo", "password": "secret"}) - assert response.status_code == 422, response.text - assert response.json() == { - "detail": [ - { - "type": "value_error.missing", - "loc": ["body", "username"], - "msg": "field required", - }, - { - "type": "value_error.missing", - "loc": ["body", "password"], - "msg": "field required", - }, - ] - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_pydanticv1 -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/login/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_login__post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": {"$ref": "#/components/schemas/FormData"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "FormData": { - "properties": { - "username": {"type": "string", "title": "Username"}, - "password": {"type": "string", "title": "Password"}, - }, - "additionalProperties": False, - "type": "object", - "required": ["username", "password"], - "title": "FormData", - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } From 9f3edbf537deb28ed56dd983b09156b365cfec87 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 22:39:42 +0000 Subject: [PATCH 707/932] =?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 [skip ci] --- 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 169345509..162d8c752 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for request_form_models . PR [#13183](https://github.com/fastapi/fastapi/pull/13183) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for separate_openapi_schemas. PR [#13201](https://github.com/fastapi/fastapi/pull/13201) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for security. PR [#13200](https://github.com/fastapi/fastapi/pull/13200) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for schema_extra_example. PR [#13197](https://github.com/fastapi/fastapi/pull/13197) by [@alejsdev](https://github.com/alejsdev). From 280fe73c0398c912a38ffbf96e3897fc9cb78a5f Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Sun, 19 Jan 2025 22:40:39 +0000 Subject: [PATCH 708/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20we?= =?UTF-8?q?bsockets=20(#13202)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_websockets/test_tutorial002.py | 33 ++++-- .../test_websockets/test_tutorial002_an.py | 88 --------------- .../test_tutorial002_an_py310.py | 102 ------------------ .../test_tutorial002_an_py39.py | 102 ------------------ .../test_websockets/test_tutorial002_py310.py | 102 ------------------ 5 files changed, 26 insertions(+), 401 deletions(-) delete mode 100644 tests/test_tutorial/test_websockets/test_tutorial002_an.py delete mode 100644 tests/test_tutorial/test_websockets/test_tutorial002_an_py310.py delete mode 100644 tests/test_tutorial/test_websockets/test_tutorial002_an_py39.py delete mode 100644 tests/test_tutorial/test_websockets/test_tutorial002_py310.py diff --git a/tests/test_tutorial/test_websockets/test_tutorial002.py b/tests/test_tutorial/test_websockets/test_tutorial002.py index bb5ccbf8e..51aa5752a 100644 --- a/tests/test_tutorial/test_websockets/test_tutorial002.py +++ b/tests/test_tutorial/test_websockets/test_tutorial002.py @@ -1,18 +1,37 @@ +import importlib + import pytest +from fastapi import FastAPI from fastapi.testclient import TestClient from fastapi.websockets import WebSocketDisconnect -from docs_src.websockets.tutorial002 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="app", + params=[ + "tutorial002", + pytest.param("tutorial002_py310", marks=needs_py310), + "tutorial002_an", + pytest.param("tutorial002_an_py39", marks=needs_py39), + pytest.param("tutorial002_an_py310", marks=needs_py310), + ], +) +def get_app(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.websockets.{request.param}") + + return mod.app -def test_main(): +def test_main(app: FastAPI): client = TestClient(app) response = client.get("/") assert response.status_code == 200, response.text assert b"" in response.content -def test_websocket_with_cookie(): +def test_websocket_with_cookie(app: FastAPI): client = TestClient(app, cookies={"session": "fakesession"}) with pytest.raises(WebSocketDisconnect): with client.websocket_connect("/items/foo/ws") as websocket: @@ -30,7 +49,7 @@ def test_websocket_with_cookie(): assert data == f"Message text was: {message}, for item ID: foo" -def test_websocket_with_header(): +def test_websocket_with_header(app: FastAPI): client = TestClient(app) with pytest.raises(WebSocketDisconnect): with client.websocket_connect("/items/bar/ws?token=some-token") as websocket: @@ -48,7 +67,7 @@ def test_websocket_with_header(): assert data == f"Message text was: {message}, for item ID: bar" -def test_websocket_with_header_and_query(): +def test_websocket_with_header_and_query(app: FastAPI): client = TestClient(app) with pytest.raises(WebSocketDisconnect): with client.websocket_connect("/items/2/ws?q=3&token=some-token") as websocket: @@ -70,7 +89,7 @@ def test_websocket_with_header_and_query(): assert data == f"Message text was: {message}, for item ID: 2" -def test_websocket_no_credentials(): +def test_websocket_no_credentials(app: FastAPI): client = TestClient(app) with pytest.raises(WebSocketDisconnect): with client.websocket_connect("/items/foo/ws"): @@ -79,7 +98,7 @@ def test_websocket_no_credentials(): ) # pragma: no cover -def test_websocket_invalid_data(): +def test_websocket_invalid_data(app: FastAPI): client = TestClient(app) with pytest.raises(WebSocketDisconnect): with client.websocket_connect("/items/foo/ws?q=bar&token=some-token"): diff --git a/tests/test_tutorial/test_websockets/test_tutorial002_an.py b/tests/test_tutorial/test_websockets/test_tutorial002_an.py deleted file mode 100644 index ec78d70d3..000000000 --- a/tests/test_tutorial/test_websockets/test_tutorial002_an.py +++ /dev/null @@ -1,88 +0,0 @@ -import pytest -from fastapi.testclient import TestClient -from fastapi.websockets import WebSocketDisconnect - -from docs_src.websockets.tutorial002_an import app - - -def test_main(): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"" in response.content - - -def test_websocket_with_cookie(): - client = TestClient(app, cookies={"session": "fakesession"}) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - - -def test_websocket_with_header(): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/bar/ws?token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - - -def test_websocket_with_header_and_query(): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/2/ws?q=3&token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - - -def test_websocket_no_credentials(): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover - - -def test_websocket_invalid_data(): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws?q=bar&token=some-token"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover diff --git a/tests/test_tutorial/test_websockets/test_tutorial002_an_py310.py b/tests/test_tutorial/test_websockets/test_tutorial002_an_py310.py deleted file mode 100644 index 23b4bcb78..000000000 --- a/tests/test_tutorial/test_websockets/test_tutorial002_an_py310.py +++ /dev/null @@ -1,102 +0,0 @@ -import pytest -from fastapi import FastAPI -from fastapi.testclient import TestClient -from fastapi.websockets import WebSocketDisconnect - -from ...utils import needs_py310 - - -@pytest.fixture(name="app") -def get_app(): - from docs_src.websockets.tutorial002_an_py310 import app - - return app - - -@needs_py310 -def test_main(app: FastAPI): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"" in response.content - - -@needs_py310 -def test_websocket_with_cookie(app: FastAPI): - client = TestClient(app, cookies={"session": "fakesession"}) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - - -@needs_py310 -def test_websocket_with_header(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/bar/ws?token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - - -@needs_py310 -def test_websocket_with_header_and_query(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/2/ws?q=3&token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - - -@needs_py310 -def test_websocket_no_credentials(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover - - -@needs_py310 -def test_websocket_invalid_data(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws?q=bar&token=some-token"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover diff --git a/tests/test_tutorial/test_websockets/test_tutorial002_an_py39.py b/tests/test_tutorial/test_websockets/test_tutorial002_an_py39.py deleted file mode 100644 index 2d77f05b3..000000000 --- a/tests/test_tutorial/test_websockets/test_tutorial002_an_py39.py +++ /dev/null @@ -1,102 +0,0 @@ -import pytest -from fastapi import FastAPI -from fastapi.testclient import TestClient -from fastapi.websockets import WebSocketDisconnect - -from ...utils import needs_py39 - - -@pytest.fixture(name="app") -def get_app(): - from docs_src.websockets.tutorial002_an_py39 import app - - return app - - -@needs_py39 -def test_main(app: FastAPI): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"" in response.content - - -@needs_py39 -def test_websocket_with_cookie(app: FastAPI): - client = TestClient(app, cookies={"session": "fakesession"}) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - - -@needs_py39 -def test_websocket_with_header(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/bar/ws?token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - - -@needs_py39 -def test_websocket_with_header_and_query(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/2/ws?q=3&token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - - -@needs_py39 -def test_websocket_no_credentials(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover - - -@needs_py39 -def test_websocket_invalid_data(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws?q=bar&token=some-token"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover diff --git a/tests/test_tutorial/test_websockets/test_tutorial002_py310.py b/tests/test_tutorial/test_websockets/test_tutorial002_py310.py deleted file mode 100644 index 03bc27bdf..000000000 --- a/tests/test_tutorial/test_websockets/test_tutorial002_py310.py +++ /dev/null @@ -1,102 +0,0 @@ -import pytest -from fastapi import FastAPI -from fastapi.testclient import TestClient -from fastapi.websockets import WebSocketDisconnect - -from ...utils import needs_py310 - - -@pytest.fixture(name="app") -def get_app(): - from docs_src.websockets.tutorial002_py310 import app - - return app - - -@needs_py310 -def test_main(app: FastAPI): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"" in response.content - - -@needs_py310 -def test_websocket_with_cookie(app: FastAPI): - client = TestClient(app, cookies={"session": "fakesession"}) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - - -@needs_py310 -def test_websocket_with_header(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/bar/ws?token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - - -@needs_py310 -def test_websocket_with_header_and_query(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/2/ws?q=3&token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - - -@needs_py310 -def test_websocket_no_credentials(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover - - -@needs_py310 -def test_websocket_invalid_data(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws?q=bar&token=some-token"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover From 6ba09082a0b8455a890a4877c8ab1e3f143be8d1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 19 Jan 2025 22:41:00 +0000 Subject: [PATCH 709/932] =?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 [skip ci] --- 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 162d8c752..a242407ea 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for websockets. PR [#13202](https://github.com/fastapi/fastapi/pull/13202) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for request_form_models . PR [#13183](https://github.com/fastapi/fastapi/pull/13183) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for separate_openapi_schemas. PR [#13201](https://github.com/fastapi/fastapi/pull/13201) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for security. PR [#13200](https://github.com/fastapi/fastapi/pull/13200) by [@alejsdev](https://github.com/alejsdev). From 8fa18e5e6ff5ae6bb620bf4a7bd0d1964f10f2de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Pedro?= Date: Wed, 22 Jan 2025 10:41:56 -0300 Subject: [PATCH 710/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Portuguese=20Tr?= =?UTF-8?q?anslation=20for=20`docs/pt/docs/tutorial/request-forms.md`=20(#?= =?UTF-8?q?13216)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/request-forms.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/pt/docs/tutorial/request-forms.md b/docs/pt/docs/tutorial/request-forms.md index 756ceb581..572ddf003 100644 --- a/docs/pt/docs/tutorial/request-forms.md +++ b/docs/pt/docs/tutorial/request-forms.md @@ -6,7 +6,11 @@ Quando você precisar receber campos de formulário ao invés de JSON, você pod Para usar formulários, primeiro instale `python-multipart`. -Ex: `pip install python-multipart`. +Lembre-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo e então instalar a dependência, por exemplo: + +```console +$ pip install python-multipart +``` /// From a215687c987ea882ef6c4f0788b6c5a8b71f75ff Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 22 Jan 2025 13:42:19 +0000 Subject: [PATCH 711/932] =?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 [skip ci] --- 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 a242407ea..5f527d37b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -49,6 +49,7 @@ hide: ### Translations +* 🌐 Update Portuguese Translation for `docs/pt/docs/tutorial/request-forms.md`. PR [#13216](https://github.com/fastapi/fastapi/pull/13216) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Update Portuguese translation for `docs/pt/docs/advanced/settings.md`. PR [#13209](https://github.com/fastapi/fastapi/pull/13209) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/oauth2-jwt.md`. PR [#13205](https://github.com/fastapi/fastapi/pull/13205) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Indonesian translation for `docs/id/docs/index.md`. PR [#13191](https://github.com/fastapi/fastapi/pull/13191) by [@gerry-sabar](https://github.com/gerry-sabar). From 548f67d465afff233fa1856b2d337d13595e3308 Mon Sep 17 00:00:00 2001 From: Daniel Kusy <36250676+DanielKusyDev@users.noreply.github.com> Date: Wed, 22 Jan 2025 19:02:36 +0100 Subject: [PATCH 712/932] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20`jinja2`?= =?UTF-8?q?=20to=20>=3D3.1.5=20(#13194)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index edfa81522..ae56ebb7e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -60,7 +60,7 @@ standard = [ # For the test client "httpx >=0.23.0", # For templates - "jinja2 >=2.11.2", + "jinja2 >=3.1.5", # For forms and file uploads "python-multipart >=0.0.7", # To validate email fields @@ -79,7 +79,7 @@ all = [ # # For the test client "httpx >=0.23.0", # For templates - "jinja2 >=2.11.2", + "jinja2 >=3.1.5", # For forms and file uploads "python-multipart >=0.0.7", # For Starlette's SessionMiddleware, not commonly used with FastAPI From 1a38cc506e5732a8a0e2d4cfec3059f670a5ef90 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 22 Jan 2025 18:03:00 +0000 Subject: [PATCH 713/932] =?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 [skip ci] --- 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 5f527d37b..d982a15f2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -33,6 +33,10 @@ hide: * ✅ Simplify tests for background_tasks. PR [#13166](https://github.com/fastapi/fastapi/pull/13166) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for additional_status_codes. PR [#13149](https://github.com/fastapi/fastapi/pull/13149) by [@tiangolo](https://github.com/tiangolo). +### Upgrades + +* ⬆️ Upgrade `jinja2` to >=3.1.5. PR [#13194](https://github.com/fastapi/fastapi/pull/13194) by [@DanielKusyDev](https://github.com/DanielKusyDev). + ### Docs * ✏️ Update Strawberry integration docs. PR [#13155](https://github.com/fastapi/fastapi/pull/13155) by [@kinuax](https://github.com/kinuax). From 82c74789e8c2ba68f4c88b6e8c80928881578272 Mon Sep 17 00:00:00 2001 From: Marcelo Trylesinski Date: Wed, 22 Jan 2025 19:21:40 +0100 Subject: [PATCH 714/932] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Bump=20Starlette?= =?UTF-8?q?=20to=20allow=20up=20to=200.45.0:=20`>=3D0.40.0,<0.46.0`=20(#13?= =?UTF-8?q?117)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index ae56ebb7e..9510d36c3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,7 +41,7 @@ classifiers = [ "Topic :: Internet :: WWW/HTTP", ] dependencies = [ - "starlette>=0.40.0,<0.42.0", + "starlette>=0.40.0,<0.46.0", "pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0", "typing-extensions>=4.8.0", ] From 91c05b9245269502ea3d28569b3cbe2fa556e465 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 22 Jan 2025 18:22:02 +0000 Subject: [PATCH 715/932] =?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 [skip ci] --- 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 d982a15f2..1951d6559 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Upgrades +* ⬆️ Bump Starlette to allow up to 0.45.0: `>=0.40.0,<0.46.0`. PR [#13117](https://github.com/fastapi/fastapi/pull/13117) by [@Kludex](https://github.com/Kludex). * ⬆️ Upgrade `jinja2` to >=3.1.5. PR [#13194](https://github.com/fastapi/fastapi/pull/13194) by [@DanielKusyDev](https://github.com/DanielKusyDev). ### Docs From 49e82ed2ac63c2aad957d01c857ee1fe597dc4ca Mon Sep 17 00:00:00 2001 From: Daniel Kusy <36250676+DanielKusyDev@users.noreply.github.com> Date: Wed, 22 Jan 2025 19:23:13 +0100 Subject: [PATCH 716/932] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20`python-?= =?UTF-8?q?multipart`=20to=20>=3D0.0.18=20(#13219)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 9510d36c3..6fa0f080f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -62,7 +62,7 @@ standard = [ # For templates "jinja2 >=3.1.5", # For forms and file uploads - "python-multipart >=0.0.7", + "python-multipart >=0.0.18", # To validate email fields "email-validator >=2.0.0", # Uvicorn with uvloop @@ -81,7 +81,7 @@ all = [ # For templates "jinja2 >=3.1.5", # For forms and file uploads - "python-multipart >=0.0.7", + "python-multipart >=0.0.18", # For Starlette's SessionMiddleware, not commonly used with FastAPI "itsdangerous >=1.1.0", # For Starlette's schema generation, would not be used with FastAPI From e39143d56de41f8d72a3be8847030346cb1d8adc Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 22 Jan 2025 18:24:12 +0000 Subject: [PATCH 717/932] =?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 [skip ci] --- 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 1951d6559..a806930f5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Upgrades +* ⬆️ Upgrade `python-multipart` to >=0.0.18. PR [#13219](https://github.com/fastapi/fastapi/pull/13219) by [@DanielKusyDev](https://github.com/DanielKusyDev). * ⬆️ Bump Starlette to allow up to 0.45.0: `>=0.40.0,<0.46.0`. PR [#13117](https://github.com/fastapi/fastapi/pull/13117) by [@Kludex](https://github.com/Kludex). * ⬆️ Upgrade `jinja2` to >=3.1.5. PR [#13194](https://github.com/fastapi/fastapi/pull/13194) by [@DanielKusyDev](https://github.com/DanielKusyDev). From abd05a6d30e6e4c9b1496e0b94d362a9979c9f37 Mon Sep 17 00:00:00 2001 From: johnthagen Date: Wed, 22 Jan 2025 13:24:58 -0500 Subject: [PATCH 718/932] =?UTF-8?q?=F0=9F=94=A7=20Add=20Pydantic=202=20tro?= =?UTF-8?q?ve=20classifier=20(#13199)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/pyproject.toml b/pyproject.toml index 6fa0f080f..381eb50bf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,6 +29,7 @@ classifiers = [ "Framework :: FastAPI", "Framework :: Pydantic", "Framework :: Pydantic :: 1", + "Framework :: Pydantic :: 2", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3 :: Only", From 2b6f63df712f0ab98f071f64b3f8ac215ddf43be Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 22 Jan 2025 18:25:24 +0000 Subject: [PATCH 719/932] =?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 [skip ci] --- 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 a806930f5..13976b788 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -110,6 +110,7 @@ hide: ### Internal +* 🔧 Add Pydantic 2 trove classifier. PR [#13199](https://github.com/fastapi/fastapi/pull/13199) by [@johnthagen](https://github.com/johnthagen). * 👥 Update FastAPI People - Sponsors. PR [#13231](https://github.com/fastapi/fastapi/pull/13231) by [@tiangolo](https://github.com/tiangolo). * 👷 Refactor FastAPI People Sponsors to use 2 tokens. PR [#13228](https://github.com/fastapi/fastapi/pull/13228) by [@tiangolo](https://github.com/tiangolo). * 👷 Update token for FastAPI People - Sponsors. PR [#13225](https://github.com/fastapi/fastapi/pull/13225) by [@tiangolo](https://github.com/tiangolo). From 7183f0d683558390b973af8ad708e82567d4dc7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 22 Jan 2025 22:48:57 +0000 Subject: [PATCH 720/932] =?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 | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 13976b788..c7f01b82f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,12 @@ hide: ## Latest Changes +### Upgrades + +* ⬆️ Upgrade `python-multipart` to >=0.0.18. PR [#13219](https://github.com/fastapi/fastapi/pull/13219) by [@DanielKusyDev](https://github.com/DanielKusyDev). +* ⬆️ Bump Starlette to allow up to 0.45.0: `>=0.40.0,<0.46.0`. PR [#13117](https://github.com/fastapi/fastapi/pull/13117) by [@Kludex](https://github.com/Kludex). +* ⬆️ Upgrade `jinja2` to >=3.1.5. PR [#13194](https://github.com/fastapi/fastapi/pull/13194) by [@DanielKusyDev](https://github.com/DanielKusyDev). + ### Refactors * ✅ Simplify tests for websockets. PR [#13202](https://github.com/fastapi/fastapi/pull/13202) by [@alejsdev](https://github.com/alejsdev). @@ -33,12 +39,6 @@ hide: * ✅ Simplify tests for background_tasks. PR [#13166](https://github.com/fastapi/fastapi/pull/13166) by [@alejsdev](https://github.com/alejsdev). * ✅ Simplify tests for additional_status_codes. PR [#13149](https://github.com/fastapi/fastapi/pull/13149) by [@tiangolo](https://github.com/tiangolo). -### Upgrades - -* ⬆️ Upgrade `python-multipart` to >=0.0.18. PR [#13219](https://github.com/fastapi/fastapi/pull/13219) by [@DanielKusyDev](https://github.com/DanielKusyDev). -* ⬆️ Bump Starlette to allow up to 0.45.0: `>=0.40.0,<0.46.0`. PR [#13117](https://github.com/fastapi/fastapi/pull/13117) by [@Kludex](https://github.com/Kludex). -* ⬆️ Upgrade `jinja2` to >=3.1.5. PR [#13194](https://github.com/fastapi/fastapi/pull/13194) by [@DanielKusyDev](https://github.com/DanielKusyDev). - ### Docs * ✏️ Update Strawberry integration docs. PR [#13155](https://github.com/fastapi/fastapi/pull/13155) by [@kinuax](https://github.com/kinuax). From fe513719ea98abade167d8a89e92f600d9d8f0e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 22 Jan 2025 22:50:29 +0000 Subject: [PATCH 721/932] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?5.7?= 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 c7f01b82f..c8a75756b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.115.7 + ### Upgrades * ⬆️ Upgrade `python-multipart` to >=0.0.18. PR [#13219](https://github.com/fastapi/fastapi/pull/13219) by [@DanielKusyDev](https://github.com/DanielKusyDev). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 823957822..c92279cfd 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.6" +__version__ = "0.115.7" from starlette import status as status From 4d60022c88e6ba92a89df4860ba2df3af7e8c926 Mon Sep 17 00:00:00 2001 From: alv2017 Date: Thu, 23 Jan 2025 11:46:41 +0200 Subject: [PATCH 722/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/tutorial/bigger-applications.md`=20(#?= =?UTF-8?q?13154)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/tutorial/bigger-applications.md | 556 +++++++++++++++++++ 1 file changed, 556 insertions(+) create mode 100644 docs/ru/docs/tutorial/bigger-applications.md diff --git a/docs/ru/docs/tutorial/bigger-applications.md b/docs/ru/docs/tutorial/bigger-applications.md new file mode 100644 index 000000000..7c3dc288f --- /dev/null +++ b/docs/ru/docs/tutorial/bigger-applications.md @@ -0,0 +1,556 @@ +# Большие приложения, в которых много файлов + +При построении приложения или веб-API нам редко удается поместить всё в один файл. + +**FastAPI** предоставляет удобный инструментарий, который позволяет нам структурировать приложение, сохраняя при этом всю необходимую гибкость. + +/// info | Примечание + +Если вы раньше использовали Flask, то это аналог шаблонов Flask (Flask's Blueprints). + +/// + +## Пример структуры приложения + +Давайте предположим, что наше приложение имеет следующую структуру: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   ├── dependencies.py +│   └── routers +│   │ ├── __init__.py +│   │ ├── items.py +│   │ └── users.py +│   └── internal +│   ├── __init__.py +│   └── admin.py +``` + +/// tip | Подсказка + +Обратите внимание, что в каждом каталоге и подкаталоге имеется файл `__init__.py` + +Это как раз то, что позволяет импортировать код из одного файла в другой. + +Например, в файле `app/main.py` может быть следующая строка: + +``` +from app.routers import items +``` + +/// + +* Всё помещается в каталоге `app`. В нём также находится пустой файл `app/__init__.py`. Таким образом, `app` является "Python-пакетом" (коллекцией модулей Python). +* Он содержит файл `app/main.py`. Данный файл является частью пакета (т.е. находится внутри каталога, содержащего файл `__init__.py`), и, соответственно, он является модулем пакета: `app.main`. +* Он также содержит файл `app/dependencies.py`, который также, как и `app/main.py`, является модулем: `app.dependencies`. +* Здесь также находится подкаталог `app/routers/`, содержащий `__init__.py`. Он является суб-пакетом: `app.routers`. +* Файл `app/routers/items.py` находится внутри пакета `app/routers/`. Таким образом, он является суб-модулем: `app.routers.items`. +* Точно также `app/routers/users.py` является ещё одним суб-модулем: `app.routers.users`. +* Подкаталог `app/internal/`, содержащий файл `__init__.py`, является ещё одним суб-пакетом: `app.internal`. +* А файл `app/internal/admin.py` является ещё одним суб-модулем: `app.internal.admin`. + + + +Та же самая файловая структура приложения, но с комментариями: + +``` +. +├── app # "app" пакет +│   ├── __init__.py # этот файл превращает "app" в "Python-пакет" +│   ├── main.py # модуль "main", напр.: import app.main +│   ├── dependencies.py # модуль "dependencies", напр.: import app.dependencies +│   └── routers # суб-пакет "routers" +│   │ ├── __init__.py # превращает "routers" в суб-пакет +│   │ ├── items.py # суб-модуль "items", напр.: import app.routers.items +│   │ └── users.py # суб-модуль "users", напр.: import app.routers.users +│   └── internal # суб-пакет "internal" +│   ├── __init__.py # превращает "internal" в суб-пакет +│   └── admin.py # суб-модуль "admin", напр.: import app.internal.admin +``` + +## `APIRouter` + +Давайте предположим, что для работы с пользователями используется отдельный файл (суб-модуль) `/app/routers/users.py`. + +Для лучшей организации приложения, вы хотите отделить операции пути, связанные с пользователями, от остального кода. + +Но так, чтобы эти операции по-прежнему оставались частью **FastAPI** приложения/веб-API (частью одного пакета) + +С помощью `APIRouter` вы можете создать *операции пути* (*эндпоинты*) для данного модуля. + + +### Импорт `APIRouter` + +Точно также, как и в случае с классом `FastAPI`, вам нужно импортировать и создать объект класса `APIRouter`. + +```Python hl_lines="1 3" title="app/routers/users.py" +{!../../docs_src/bigger_applications/app/routers/users.py!} +``` + +### Создание *эндпоинтов* с помощью `APIRouter` + +В дальнейшем используйте `APIRouter` для объявления *эндпоинтов*, точно также, как вы используете класс `FastAPI`: + +```Python hl_lines="6 11 16" title="app/routers/users.py" +{!../../docs_src/bigger_applications/app/routers/users.py!} +``` + +Вы можете думать об `APIRouter` как об "уменьшенной версии" класса FastAPI`. + +`APIRouter` поддерживает все те же самые опции. + +`APIRouter` поддерживает все те же самые параметры, такие как `parameters`, `responses`, `dependencies`, `tags`, и т. д. + +/// tip | Подсказка + +В данном примере, в качестве названия переменной используется `router`, но вы можете использовать любое другое имя. + +/// + +Мы собираемся подключить данный `APIRouter` к нашему основному приложению на `FastAPI`, но сначала давайте проверим зависимости и создадим ещё один модуль с `APIRouter`. + +## Зависимости + +Нам понадобятся некоторые зависимости, которые мы будем использовать в разных местах нашего приложения. + +Мы поместим их в отдельный модуль `dependencies` (`app/dependencies.py`). + +Теперь мы воспользуемся простой зависимостью, чтобы прочитать кастомизированный `X-Token` из заголовка: + +//// tab | Python 3.9+ + +```Python hl_lines="3 6-8" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 5-7" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app_an/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Подсказка + +Мы рекомендуем использовать версию `Annotated`, когда это возможно. + +/// + +```Python hl_lines="1 4-6" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app/dependencies.py!} +``` + +//// + +/// tip | Подсказка + +Для простоты мы воспользовались неким воображаемым заголовоком. + +В реальных случаях для получения наилучших результатов используйте интегрированные утилиты обеспечения безопасности [Security utilities](security/index.md){.internal-link target=_blank}. + +/// + +## Ещё один модуль с `APIRouter` + +Давайте также предположим, что у вас есть *эндпоинты*, отвечающие за обработку "items", и они находятся в модуле `app/routers/items.py`. + +У вас определены следующие *операции пути* (*эндпоинты*): + +* `/items/` +* `/items/{item_id}` + +Тут всё точно также, как и в ситуации с `app/routers/users.py`. + +Но теперь мы хотим поступить немного умнее и слегка упростить код. + +Мы знаем, что все *эндпоинты* данного модуля имеют некоторые общие свойства: + +* Префикс пути: `/items`. +* Теги: (один единственный тег: `items`). +* Дополнительные ответы (responses) +* Зависимости: использование созданной нами зависимости `X-token` + +Таким образом, вместо того чтобы добавлять все эти свойства в функцию каждого отдельного *эндпоинта*, +мы добавим их в `APIRouter`. + +```Python hl_lines="5-10 16 21" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +Так как каждый *эндпоинт* начинается с символа `/`: + +```Python hl_lines="1" +@router.get("/{item_id}") +async def read_item(item_id: str): + ... +``` + +...то префикс не должен заканчиваться символом `/`. + +В нашем случае префиксом является `/items`. + +Мы также можем добавить в наш маршрутизатор (router) список `тегов` (`tags`) и дополнительных `ответов` (`responses`), которые являются общими для каждого *эндпоинта*. + +И ещё мы можем добавить в наш маршрутизатор список `зависимостей`, которые должны вызываться при каждом обращении к *эндпоинтам*. + +/// tip | Подсказка + +Обратите внимание, что также, как и в случае с зависимостями в декораторах *эндпоинтов* ([dependencies in *path operation decorators*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), никакого значения в *функцию эндпоинта* передано не будет. + +/// + +В результате мы получим следующие эндпоинты: + +* `/items/` +* `/items/{item_id}` + +...как мы и планировали. + +* Они будут помечены тегами из заданного списка, в нашем случае это `"items"`. + * Эти теги особенно полезны для системы автоматической интерактивной документации (с использованием OpenAPI). +* Каждый из них будет включать предопределенные ответы `responses`. +* Каждый *эндпоинт* будет иметь список зависимостей (`dependencies`), исполняемых перед вызовом *эндпоинта*. + * Если вы определили зависимости в самой операции пути, **то она также будет выполнена**. + * Сначала выполняются зависимости маршрутизатора, затем вызываются зависимости, определенные в декораторе *эндпоинта* ([`dependencies` in the decorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), и, наконец, обычные параметрические зависимости. + * Вы также можете добавить зависимости безопасности с областями видимости (`scopes`) [`Security` dependencies with `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}. + +/// tip | Подсказка + +Например, с помощью зависимостей в `APIRouter` мы можем потребовать аутентификации для доступа ко всей группе *эндпоинтов*, не указывая зависимости для каждой отдельной функции *эндпоинта*. + +/// + +/// check | Заметка + +Параметры `prefix`, `tags`, `responses` и `dependencies` относятся к функционалу **FastAPI**, помогающему избежать дублирования кода. + +/// + +### Импорт зависимостей + +Наш код находится в модуле `app.routers.items` (файл `app/routers/items.py`). + +И нам нужно вызвать функцию зависимости из модуля `app.dependencies` (файл `app/dependencies.py`). + +Мы используем операцию относительного импорта `..` для импорта зависимости: + +```Python hl_lines="3" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +#### Как работает относительный импорт? + +/// tip | Подсказка + +Если вы прекрасно знаете, как работает импорт в Python, то переходите к следующему разделу. + +/// + +Одна точка `.`, как в данном примере: + +```Python +from .dependencies import get_token_header +``` +означает: + +* Начните с пакета, в котором находится данный модуль (файл `app/routers/items.py` расположен в каталоге `app/routers/`)... +* ... найдите модуль `dependencies` (файл `app/routers/dependencies.py`)... +* ... и импортируйте из него функцию `get_token_header`. + +К сожалению, такого файла не существует, и наши зависимости находятся в файле `app/dependencies.py`. + +Вспомните, как выглядит файловая структура нашего приложения: + + + +--- + +Две точки `..`, как в данном примере: + +```Python +from ..dependencies import get_token_header +``` + +означают: + +* Начните с пакета, в котором находится данный модуль (файл `app/routers/items.py` находится в каталоге `app/routers/`)... +* ... перейдите в родительский пакет (каталог `app/`)... +* ... найдите в нём модуль `dependencies` (файл `app/dependencies.py`)... +* ... и импортируйте из него функцию `get_token_header`. + +Это работает верно! 🎉 + +--- + +Аналогично, если бы мы использовали три точки `...`, как здесь: + +```Python +from ...dependencies import get_token_header +``` + +то это бы означало: + +* Начните с пакета, в котором находится данный модуль (файл `app/routers/items.py` находится в каталоге `app/routers/`)... +* ... перейдите в родительский пакет (каталог `app/`)... +* ... затем перейдите в родительский пакет текущего пакета (такого пакета не существует, `app` находится на самом верхнем уровне 😱)... +* ... найдите в нём модуль `dependencies` (файл `app/dependencies.py`)... +* ... и импортируйте из него функцию `get_token_header`. + +Это будет относиться к некоторому пакету, находящемуся на один уровень выше чем `app/` и содержащему свой собственный файл `__init__.py`. Но ничего такого у нас нет. Поэтому это приведет к ошибке в нашем примере. 🚨 + +Теперь вы знаете, как работает импорт в Python, и сможете использовать относительное импортирование в своих собственных приложениях любого уровня сложности. 🤓 + +### Добавление пользовательских тегов (`tags`), ответов (`responses`) и зависимостей (`dependencies`) + +Мы не будем добавлять префикс `/items` и список тегов `tags=["items"]` для каждого *эндпоинта*, т.к. мы уже их добавили с помощью `APIRouter`. + +Но помимо этого мы можем добавить новые теги для каждого отдельного *эндпоинта*, а также некоторые дополнительные ответы (`responses`), характерные для данного *эндпоинта*: + +```Python hl_lines="30-31" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +/// tip | Подсказка + +Последний *эндпоинт* будет иметь следующую комбинацию тегов: `["items", "custom"]`. + +А также в его документации будут содержаться оба ответа: один для `404` и другой для `403`. + +/// + +## Модуль main в `FastAPI` + +Теперь давайте посмотрим на модуль `app/main.py`. + +Именно сюда вы импортируете и именно здесь вы используете класс `FastAPI`. + +Это основной файл вашего приложения, который объединяет всё в одно целое. + +И теперь, когда большая часть логики приложения разделена на отдельные модули, основной файл `app/main.py` будет достаточно простым. + +### Импорт `FastAPI` + +Вы импортируете и создаете класс `FastAPI` как обычно. + +Мы даже можем объявить глобальные зависимости [global dependencies](dependencies/global-dependencies.md){.internal-link target=_blank}, которые будут объединены с зависимостями для каждого отдельного маршрутизатора: + +```Python hl_lines="1 3 7" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +### Импорт `APIRouter` + +Теперь мы импортируем другие суб-модули, содержащие `APIRouter`: + +```Python hl_lines="4-5" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +Так как файлы `app/routers/users.py` и `app/routers/items.py` являются суб-модулями одного и того же Python-пакета `app`, то мы сможем их импортировать, воспользовавшись операцией относительного импорта `.`. + +### Как работает импорт? + +Данная строка кода: + +```Python +from .routers import items, users +``` + +означает: + +* Начните с пакета, в котором содержится данный модуль (файл `app/main.py` содержится в каталоге `app/`)... +* ... найдите суб-пакет `routers` (каталог `app/routers/`)... +* ... и из него импортируйте суб-модули `items` (файл `app/routers/items.py`) и `users` (файл `app/routers/users.py`)... + +В модуле `items` содержится переменная `router` (`items.router`), та самая, которую мы создали в файле `app/routers/items.py`, она является объектом класса `APIRouter`. + +И затем мы сделаем то же самое для модуля `users`. + +Мы также могли бы импортировать и другим методом: + +```Python +from app.routers import items, users +``` + +/// info | Примечание + +Первая версия является примером относительного импорта: + +```Python +from .routers import items, users +``` + +Вторая версия является примером абсолютного импорта: + +```Python +from app.routers import items, users +``` + +Узнать больше о пакетах и модулях в Python вы можете из официальной документации Python о модулях + +/// + +### Избегайте конфликтов имен + +Вместо того чтобы импортировать только переменную `router`, мы импортируем непосредственно суб-модуль `items`. + +Мы делаем это потому, что у нас есть ещё одна переменная `router` в суб-модуле `users`. + +Если бы мы импортировали их одну за другой, как показано в примере: + +```Python +from .routers.items import router +from .routers.users import router +``` + +то переменная `router` из `users` переписал бы переменную `router` из `items`, и у нас не было бы возможности использовать их одновременно. + +Поэтому, для того чтобы использовать обе эти переменные в одном файле, мы импортировали соответствующие суб-модули: + +```Python hl_lines="5" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +### Подключение маршрутизаторов (`APIRouter`) для `users` и для `items` + +Давайте подключим маршрутизаторы (`router`) из суб-модулей `users` и `items`: + +```Python hl_lines="10-11" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +/// info | Примечание + +`users.router` содержит `APIRouter` из файла `app/routers/users.py`. + +А `items.router` содержит `APIRouter` из файла `app/routers/items.py`. + +/// + +С помощью `app.include_router()` мы можем добавить каждый из маршрутизаторов (`APIRouter`) в основное приложение `FastAPI`. + +Он подключит все маршруты заданного маршрутизатора к нашему приложению. + +/// note | Технические детали + +Фактически, внутри он создаст все *операции пути* для каждой операции пути объявленной в `APIRouter`. + +И под капотом всё будет работать так, как будто бы мы имеем дело с одним файлом приложения. + +/// + +/// check | Заметка + +При подключении маршрутизаторов не стоит беспокоиться о производительности. + +Операция подключения займёт микросекунды и понадобится только при запуске приложения. + +Таким образом, это не повлияет на производительность. ⚡ + +/// + +### Подключение `APIRouter` с пользовательскими префиксом (`prefix`), тегами (`tags`), ответами (`responses`), и зависимостями (`dependencies`) + +Теперь давайте представим, что ваша организация передала вам файл `app/internal/admin.py`. + +Он содержит `APIRouter` с некоторыми *эндпоитами* администрирования, которые ваша организация использует для нескольких проектов. + +В данном примере это сделать очень просто. Но давайте предположим, что поскольку файл используется для нескольких проектов, +то мы не можем модифицировать его, добавляя префиксы (`prefix`), зависимости (`dependencies`), теги (`tags`), и т.д. непосредственно в `APIRouter`: + +```Python hl_lines="3" title="app/internal/admin.py" +{!../../docs_src/bigger_applications/app/internal/admin.py!} +``` + +Но, несмотря на это, мы хотим использовать кастомный префикс (`prefix`) для подключенного маршрутизатора (`APIRouter`), в результате чего, каждая *операция пути* будет начинаться с `/admin`. Также мы хотим защитить наш маршрутизатор с помощью зависимостей, созданных для нашего проекта. И ещё мы хотим включить теги (`tags`) и ответы (`responses`). + +Мы можем применить все вышеперечисленные настройки, не изменяя начальный `APIRouter`. Нам всего лишь нужно передать нужные параметры в `app.include_router()`. + +```Python hl_lines="14-17" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +Таким образом, оригинальный `APIRouter` не будет модифицирован, и мы сможем использовать файл `app/internal/admin.py` сразу в нескольких проектах организации. + +В результате, в нашем приложении каждый *эндпоинт* модуля `admin` будет иметь: + +* Префикс `/admin`. +* Тег `admin`. +* Зависимость `get_token_header`. +* Ответ `418`. 🍵 + +Это будет иметь место исключительно для `APIRouter` в нашем приложении, и не затронет любой другой код, использующий его. + +Например, другие проекты, могут использовать тот же самый `APIRouter` с другими методами аутентификации. + +### Подключение отдельного *эндпоинта* + +Мы также можем добавить *эндпоинт* непосредственно в основное приложение `FastAPI`. + +Здесь мы это делаем ... просто, чтобы показать, что это возможно 🤷: + +```Python hl_lines="21-23" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +и это будет работать корректно вместе с другими *эндпоинтами*, добавленными с помощью `app.include_router()`. + +/// info | Сложные технические детали + +**Примечание**: это сложная техническая деталь, которую, скорее всего, **вы можете пропустить**. + +--- + +Маршрутизаторы (`APIRouter`) не "монтируются" по-отдельности и не изолируются от остального приложения. + +Это происходит потому, что нужно включить их *эндпоинты* в OpenAPI схему и в интерфейс пользователя. + +В силу того, что мы не можем их изолировать и "примонтировать" независимо от остальных, *эндпоинты* клонируются (пересоздаются) и не подключаются напрямую. + +/// + +## Проверка автоматической документации API + +Теперь запустите приложение: + +
    + +```console +$ fastapi dev app/main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
    + +Откройте документацию по адресу http://127.0.0.1:8000/docs. + +Вы увидите автоматическую API документацию. Она включает в себя маршруты из суб-модулей, используя верные маршруты, префиксы и теги: + + + +## Подключение существующего маршрута через новый префикс (`prefix`) + +Вы можете использовать `.include_router()` несколько раз с одним и тем же маршрутом, применив различные префиксы. + +Это может быть полезным, если нужно предоставить доступ к одному и тому же API через различные префиксы, например, `/api/v1` и `/api/latest`. + +Это продвинутый способ, который вам может и не пригодится. Мы приводим его на случай, если вдруг вам это понадобится. + +## Включение одного маршрутизатора (`APIRouter`) в другой + +Точно так же, как вы включаете `APIRouter` в приложение `FastAPI`, вы можете включить `APIRouter` в другой `APIRouter`: + +```Python +router.include_router(other_router) +``` + +Удостоверьтесь, что вы сделали это до того, как подключить маршрутизатор (`router`) к вашему `FastAPI` приложению, и *эндпоинты* маршрутизатора `other_router` были также подключены. From b6f6818d76f312fe30d798e52fff16927649db0a Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 23 Jan 2025 09:47:05 +0000 Subject: [PATCH 723/932] =?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 [skip ci] --- 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 c8a75756b..bc725fafe 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Translations + +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/bigger-applications.md`. PR [#13154](https://github.com/fastapi/fastapi/pull/13154) by [@alv2017](https://github.com/alv2017). + ## 0.115.7 ### Upgrades From 0e2d8d64a427905d673ecee9cfeaf9e74ed979e4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 24 Jan 2025 17:05:11 +0000 Subject: [PATCH 724/932] =?UTF-8?q?=E2=AC=86=20Bump=20pypa/gh-action-pypi-?= =?UTF-8?q?publish=20from=201.12.3=20to=201.12.4=20(#13251)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.12.3 to 1.12.4. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.12.3...v1.12.4) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 38df75928..bf88d59b1 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -35,7 +35,7 @@ jobs: TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.12.3 + uses: pypa/gh-action-pypi-publish@v1.12.4 - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} From 6bbd315f3e7c08893591729cfb61a19eadb73eae Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 24 Jan 2025 17:05:37 +0000 Subject: [PATCH 725/932] =?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 [skip ci] --- 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 bc725fafe..b1020d6e4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,10 @@ hide: * 🌐 Add Russian translation for `docs/ru/docs/tutorial/bigger-applications.md`. PR [#13154](https://github.com/fastapi/fastapi/pull/13154) by [@alv2017](https://github.com/alv2017). +### Internal + +* ⬆ Bump pypa/gh-action-pypi-publish from 1.12.3 to 1.12.4. PR [#13251](https://github.com/fastapi/fastapi/pull/13251) by [@dependabot[bot]](https://github.com/apps/dependabot). + ## 0.115.7 ### Upgrades From 998a9139d3e34100874712f5a9261cdc67f8d4ed Mon Sep 17 00:00:00 2001 From: Rishat-F <66554797+Rishat-F@users.noreply.github.com> Date: Fri, 24 Jan 2025 22:44:31 +0300 Subject: [PATCH 726/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Russian=20trans?= =?UTF-8?q?lation=20for=20`docs/ru/docs/tutorial/dependencies/dependencies?= =?UTF-8?q?-in-path-operation-decorators.md`=20(#13252)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependencies/dependencies-in-path-operation-decorators.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index f9b9dec25..0e4eb95be 100644 --- a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -18,7 +18,7 @@ Зависимости из dependencies выполнятся так же, как и обычные зависимости. Но их значения (если они были) не будут переданы в *функцию операции пути*. -/// подсказка +/// tip | Подсказка Некоторые редакторы кода определяют неиспользуемые параметры функций и подсвечивают их как ошибку. @@ -28,7 +28,7 @@ /// -/// дополнительная | информация +/// info | Примечание В этом примере мы используем выдуманные пользовательские заголовки `X-Key` и `X-Token`. From 1e44825ef2143e37e51edb86ae44d408d9dbb756 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 24 Jan 2025 19:44:54 +0000 Subject: [PATCH 727/932] =?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 [skip ci] --- 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 b1020d6e4..f25648b9a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Update Russian translation for `docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#13252](https://github.com/fastapi/fastapi/pull/13252) by [@Rishat-F](https://github.com/Rishat-F). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/bigger-applications.md`. PR [#13154](https://github.com/fastapi/fastapi/pull/13154) by [@alv2017](https://github.com/alv2017). ### Internal From 24eb8eeeba23d93288ef40596d621f149e648e10 Mon Sep 17 00:00:00 2001 From: Rishat-F <66554797+Rishat-F@users.noreply.github.com> Date: Mon, 27 Jan 2025 18:36:13 +0300 Subject: [PATCH 728/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/advanced/async-tests.md`=20(#13227)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/advanced/async-tests.md | 99 ++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 docs/ru/docs/advanced/async-tests.md diff --git a/docs/ru/docs/advanced/async-tests.md b/docs/ru/docs/advanced/async-tests.md new file mode 100644 index 000000000..7849ad109 --- /dev/null +++ b/docs/ru/docs/advanced/async-tests.md @@ -0,0 +1,99 @@ +# Асинхронное тестирование + +Вы уже видели как тестировать **FastAPI** приложение, используя имеющийся класс `TestClient`. К этому моменту вы видели только как писать тесты в синхронном стиле без использования `async` функций. + +Возможность использования асинхронных функций в ваших тестах может быть полезнa, когда, например, вы асинхронно обращаетесь к вашей базе данных. Представьте, что вы хотите отправить запросы в ваше FastAPI приложение, а затем при помощи асинхронной библиотеки для работы с базой данных удостовериться, что ваш бекэнд корректно записал данные в базу данных. + +Давайте рассмотрим, как мы можем это реализовать. + +## pytest.mark.anyio + +Если мы хотим вызывать асинхронные функции в наших тестах, то наши тестовые функции должны быть асинхронными. AnyIO предоставляет для этого отличный плагин, который позволяет нам указывать, какие тестовые функции должны вызываться асинхронно. + +## HTTPX + +Даже если **FastAPI** приложение использует обычные функции `def` вместо `async def`, это все равно `async` приложение 'под капотом'. + +Чтобы работать с асинхронным FastAPI приложением в ваших обычных тестовых функциях `def`, используя стандартный pytest, `TestClient` внутри себя делает некоторую магию. Но эта магия перестает работать, когда мы используем его внутри асинхронных функций. Запуская наши тесты асинхронно, мы больше не можем использовать `TestClient` внутри наших тестовых функций. + +`TestClient` основан на HTTPX, и, к счастью, мы можем использовать его (`HTTPX`) напрямую для тестирования API. + +## Пример + +В качестве простого примера, давайте рассмотрим файловую структуру, схожую с описанной в [Большие приложения](../tutorial/bigger-applications.md){.internal-link target=_blank} и [Тестирование](../tutorial/testing.md){.internal-link target=_blank}: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Файл `main.py`: + +{* ../../docs_src/async_tests/main.py *} + +Файл `test_main.py` содержит тесты для `main.py`, теперь он может выглядеть так: + +{* ../../docs_src/async_tests/test_main.py *} + +## Запуск тестов + +Вы можете запустить свои тесты как обычно: + +
    + +```console +$ pytest + +---> 100% +``` + +
    + +## Подробнее + +Маркер `@pytest.mark.anyio` говорит pytest, что тестовая функция должна быть вызвана асинхронно: + +{* ../../docs_src/async_tests/test_main.py hl[7] *} + +/// tip | Подсказка + +Обратите внимание, что тестовая функция теперь `async def` вместо простого `def`, как это было при использовании `TestClient`. + +/// + +Затем мы можем создать `AsyncClient` со ссылкой на приложение и посылать асинхронные запросы, используя `await`. + +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} + +Это эквивалентно следующему: + +```Python +response = client.get('/') +``` + +...которое мы использовали для отправки наших запросов с `TestClient`. + +/// tip | Подсказка + +Обратите внимание, что мы используем async/await с `AsyncClient` - запрос асинхронный. + +/// + +/// warning | Внимание + +Если ваше приложение полагается на lifespan события, то `AsyncClient` не запустит эти события. Чтобы обеспечить их срабатывание используйте `LifespanManager` из florimondmanca/asgi-lifespan. + +/// + +## Вызов других асинхронных функций + +Теперь тестовая функция стала асинхронной, поэтому внутри нее вы можете вызывать также и другие `async` функции, не связанные с отправлением запросов в ваше FastAPI приложение. Как если бы вы вызывали их в любом другом месте вашего кода. + +/// tip | Подсказка + +Если вы столкнулись с `RuntimeError: Task attached to a different loop` при вызове асинхронных функций в ваших тестах (например, при использовании MongoDB's MotorClient), то не забывайте инициализировать объекты, которым нужен цикл событий (event loop), только внутри асинхронных функций, например, в `'@app.on_event("startup")` callback. + +/// From 18127b790725a3a6ca378dd99eb2cfd9f2423ccd Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 27 Jan 2025 15:36:36 +0000 Subject: [PATCH 729/932] =?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 [skip ci] --- 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 f25648b9a..0dc660412 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Russian translation for `docs/ru/docs/advanced/async-tests.md`. PR [#13227](https://github.com/fastapi/fastapi/pull/13227) by [@Rishat-F](https://github.com/Rishat-F). * 🌐 Update Russian translation for `docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#13252](https://github.com/fastapi/fastapi/pull/13252) by [@Rishat-F](https://github.com/Rishat-F). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/bigger-applications.md`. PR [#13154](https://github.com/fastapi/fastapi/pull/13154) by [@alv2017](https://github.com/alv2017). From 8f359273b5663aecdc989c762fad3804c3a6df80 Mon Sep 17 00:00:00 2001 From: k94-ishi <32672580+k94-ishi@users.noreply.github.com> Date: Tue, 28 Jan 2025 00:39:04 +0900 Subject: [PATCH 730/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/environment-variables.md`=20(#13226)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ja/docs/environment-variables.md | 301 ++++++++++++++++++++++++++ 1 file changed, 301 insertions(+) create mode 100644 docs/ja/docs/environment-variables.md diff --git a/docs/ja/docs/environment-variables.md b/docs/ja/docs/environment-variables.md new file mode 100644 index 000000000..507af3a0c --- /dev/null +++ b/docs/ja/docs/environment-variables.md @@ -0,0 +1,301 @@ +# 環境変数 + +/// tip + +もし、「環境変数」とは何か、それをどう使うかを既に知っている場合は、このセクションをスキップして構いません。 + +/// + +環境変数(**env var**とも呼ばれる)はPythonコードの**外側**、つまり**OS**に存在する変数で、Pythonから読み取ることができます。(他のプログラムでも同様に読み取れます。) + +環境変数は、アプリケーションの**設定**の管理や、Pythonの**インストール**などに役立ちます。 + +## 環境変数の作成と使用 + +環境変数は**シェル(ターミナル)**内で**作成**して使用でき、それらにPythonは不要です。 + +//// tab | Linux, macOS, Windows Bash + +
    + +```console +// You could create an env var MY_NAME with +$ export MY_NAME="Wade Wilson" + +// Then you could use it with other programs, like +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
    + +//// + +//// tab | Windows PowerShell + +
    + + +```console +// Create an env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Use it with other programs, like +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
    + +//// + +## Pythonで環境変数を読み取る + +環境変数をPythonの**外側**、ターミナル(や他の方法)で作成し、**Python内で読み取る**こともできます。 + +例えば、以下のような`main.py`ファイルを用意します: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +`os.getenv()` の第2引数は、デフォルトで返される値を指定します。 + +この引数を省略するとデフォルト値として`None`が返されますが、ここではデフォルト値として`"World"`を指定しています。 + +/// + +次に、このPythonプログラムを呼び出します。 + +//// tab | Linux, macOS, Windows Bash + +
    + +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ export MY_NAME="Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
    + +//// + +//// tab | Windows PowerShell + +
    + +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ $Env:MY_NAME = "Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
    + +//// + +環境変数はコードの外側で設定し、内側から読み取ることができるので、他のファイルと一緒に(`git`に)保存する必要がありません。そのため、環境変数をコンフィグレーションや**設定**に使用することが一般的です。 + +また、**特定のプログラムの呼び出し**のための環境変数を、そのプログラムのみ、その実行中に限定して利用できるよう作成できます。 + +そのためには、プログラム起動コマンドと同じコマンドライン上の、起動コマンド直前で環境変数を作成してください。 + +
    + +```console +// Create an env var MY_NAME in line for this program call +$ MY_NAME="Wade Wilson" python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python + +// The env var no longer exists afterwards +$ python main.py + +Hello World from Python +``` + +
    + +/// tip + +詳しくは The Twelve-Factor App: Config を参照してください。 + +/// + +## 型とバリデーション + +環境変数は**テキスト文字列**のみを扱うことができます。これは、環境変数がPython外部に存在し、他のプログラムやシステム全体(Linux、Windows、macOS間の互換性を含む)と連携する必要があるためです。 + +つまり、Pythonが環境変数から読み取る**あらゆる値**は **`str`型となり**、他の型への変換やバリデーションはコード内で行う必要があります。 + +環境変数を使用して**アプリケーション設定**を管理する方法については、[高度なユーザーガイド - Settings and Environment Variables](./advanced/settings.md){.internal-link target=_blank}で詳しく学べます。 + +## `PATH`環境変数 + +**`PATH`**という**特別な**環境変数があります。この環境変数は、OS(Linux、macOS、Windows)が実行するプログラムを発見するために使用されます。 + +`PATH`変数は、複数のディレクトリのパスから成る長い文字列です。このパスはLinuxやMacOSの場合は`:`で、Windowsの場合は`;`で区切られています。 + +例えば、`PATH`環境変数は次のような文字列かもしれません: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +これは、OSはプログラムを見つけるために以下のディレクトリを探す、ということを意味します: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +これは、OSはプログラムを見つけるために以下のディレクトリを探す、ということを意味します: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +ターミナル上で**コマンド**を入力すると、 OSはそのプログラムを見つけるために、`PATH`環境変数のリストに記載された**それぞれのディレクトリを探し**ます。 + +例えば、ターミナル上で`python`を入力すると、OSは`python`によって呼ばれるプログラムを見つけるために、そのリストの**先頭のディレクトリ**を最初に探します。 + +OSは、もしそのプログラムをそこで発見すれば**実行し**ますが、そうでなければリストの**他のディレクトリ**を探していきます。 + +### PythonのインストールとPATH環境変数の更新 + +Pythonのインストール時に`PATH`環境変数を更新したいか聞かれるかもしれません。 + +/// tab | Linux, macOS + +Pythonをインストールして、そのプログラムが`/opt/custompython/bin`というディレクトリに配置されたとします。 + +もし、`PATH`環境変数を更新するように答えると、`PATH`環境変数に`/opt/custompython/bin`が追加されます。 + +`PATH`環境変数は以下のように更新されるでしょう: + +``` plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +このようにして、ターミナルで`python`と入力したときに、OSは`/opt/custompython/bin`(リストの末尾のディレクトリ)にあるPythonプログラムを見つけ、使用します。 + +/// + +/// tab | Windows + +Pythonをインストールして、そのプログラムが`C:\opt\custompython\bin`というディレクトリに配置されたとします。 + +もし、`PATH`環境変数を更新するように答えると、`PATH`環境変数に`C:\opt\custompython\bin`が追加されます。 + +`PATH`環境変数は以下のように更新されるでしょう: + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +このようにして、ターミナルで`python`と入力したときに、OSは`C:\opt\custompython\bin\python`(リストの末尾のディレクトリ)にあるPythonプログラムを見つけ、使用します。 + +/// + +つまり、ターミナルで以下のコマンドを入力すると: + +
    + +``` console +$ python +``` + +
    + +/// tab | Linux, macOS + +OSは`/opt/custompython/bin`にある`python`プログラムを**見つけ**て実行します。 + +これは、次のコマンドを入力した場合とほとんど同等です: + +
    + +```console +$ /opt/custompython/bin/python +``` + +
    + +/// + +/// tab | Windows + +OSは`C:\opt\custompython\bin\python`にある`python`プログラムを**見つけ**て実行します。 + +これは、次のコマンドを入力した場合とほとんど同等です: + +
    + +```console +$ C:\opt\custompython\bin\python +``` + +
    + +/// + +この情報は、[Virtual Environments](virtual-environments.md) について学ぶ際にも役立ちます。 + +## まとめ + +これで、**環境変数**とは何か、Pythonでどのように使用するかについて、基本的な理解が得られたはずです。 + +環境変数についての詳細は、Wikipedia: Environment Variable を参照してください。 + +環境変数の用途や適用方法が最初は直感的ではないかもしれませんが、開発中のさまざまなシナリオで繰り返し登場します。そのため、基本を知っておくことが重要です。 + +たとえば、この情報は次のセクションで扱う[Virtual Environments](virtual-environments.md)にも関連します。 From d2f5097dedcfb1eb695d21dbb19a5593cf1bd756 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 27 Jan 2025 15:39:30 +0000 Subject: [PATCH 731/932] =?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 [skip ci] --- 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 0dc660412..76333d313 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/environment-variables.md`. PR [#13226](https://github.com/fastapi/fastapi/pull/13226) by [@k94-ishi](https://github.com/k94-ishi). * 🌐 Add Russian translation for `docs/ru/docs/advanced/async-tests.md`. PR [#13227](https://github.com/fastapi/fastapi/pull/13227) by [@Rishat-F](https://github.com/Rishat-F). * 🌐 Update Russian translation for `docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md`. PR [#13252](https://github.com/fastapi/fastapi/pull/13252) by [@Rishat-F](https://github.com/Rishat-F). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/bigger-applications.md`. PR [#13154](https://github.com/fastapi/fastapi/pull/13154) by [@alv2017](https://github.com/alv2017). From ff68d0894a7191f7dd107bd449e6bd40b3af1735 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 28 Jan 2025 20:34:56 +0000 Subject: [PATCH 732/932] =?UTF-8?q?=F0=9F=94=A8=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e=20Experts=20script,=20refactor=20and=20optimize=20data=20fetc?= =?UTF-8?q?hing=20to=20handle=20rate=20limits=20(#13267)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/actions/people/Dockerfile | 7 - .github/actions/people/action.yml | 10 - .github/actions/people/app/main.py | 682 ----------------------------- .github/workflows/people.yml | 37 +- docs/en/docs/fastapi-people.md | 33 ++ scripts/people.py | 401 +++++++++++++++++ 6 files changed, 462 insertions(+), 708 deletions(-) delete mode 100644 .github/actions/people/Dockerfile delete mode 100644 .github/actions/people/action.yml delete mode 100644 .github/actions/people/app/main.py create mode 100644 scripts/people.py diff --git a/.github/actions/people/Dockerfile b/.github/actions/people/Dockerfile deleted file mode 100644 index 1455106bd..000000000 --- a/.github/actions/people/Dockerfile +++ /dev/null @@ -1,7 +0,0 @@ -FROM python:3.9 - -RUN pip install httpx PyGithub "pydantic==2.0.2" pydantic-settings "pyyaml>=5.3.1,<6.0.0" - -COPY ./app /app - -CMD ["python", "/app/main.py"] diff --git a/.github/actions/people/action.yml b/.github/actions/people/action.yml deleted file mode 100644 index 71745b874..000000000 --- a/.github/actions/people/action.yml +++ /dev/null @@ -1,10 +0,0 @@ -name: "Generate FastAPI People" -description: "Generate the data for the FastAPI People page" -author: "Sebastián Ramírez " -inputs: - token: - description: 'User token, to read the GitHub API. Can be passed in using {{ secrets.FASTAPI_PEOPLE }}' - required: true -runs: - using: 'docker' - image: 'Dockerfile' diff --git a/.github/actions/people/app/main.py b/.github/actions/people/app/main.py deleted file mode 100644 index b752d9d2b..000000000 --- a/.github/actions/people/app/main.py +++ /dev/null @@ -1,682 +0,0 @@ -import logging -import subprocess -import sys -from collections import Counter, defaultdict -from datetime import datetime, timedelta, timezone -from pathlib import Path -from typing import Any, Container, DefaultDict, Dict, List, Set, Union - -import httpx -import yaml -from github import Github -from pydantic import BaseModel, SecretStr -from pydantic_settings import BaseSettings - -github_graphql_url = "https://api.github.com/graphql" -questions_category_id = "MDE4OkRpc2N1c3Npb25DYXRlZ29yeTMyMDAxNDM0" - -discussions_query = """ -query Q($after: String, $category_id: ID) { - repository(name: "fastapi", owner: "fastapi") { - discussions(first: 100, after: $after, categoryId: $category_id) { - edges { - cursor - node { - number - author { - login - avatarUrl - url - } - title - createdAt - comments(first: 100) { - nodes { - createdAt - author { - login - avatarUrl - url - } - isAnswer - replies(first: 10) { - nodes { - createdAt - author { - login - avatarUrl - url - } - } - } - } - } - } - } - } - } -} -""" - - -prs_query = """ -query Q($after: String) { - repository(name: "fastapi", owner: "fastapi") { - pullRequests(first: 100, after: $after) { - edges { - cursor - node { - number - labels(first: 100) { - nodes { - name - } - } - author { - login - avatarUrl - url - } - title - createdAt - state - comments(first: 100) { - nodes { - createdAt - author { - login - avatarUrl - url - } - } - } - reviews(first:100) { - nodes { - author { - login - avatarUrl - url - } - state - } - } - } - } - } - } -} -""" - -sponsors_query = """ -query Q($after: String) { - user(login: "fastapi") { - sponsorshipsAsMaintainer(first: 100, after: $after) { - edges { - cursor - node { - sponsorEntity { - ... on Organization { - login - avatarUrl - url - } - ... on User { - login - avatarUrl - url - } - } - tier { - name - monthlyPriceInDollars - } - } - } - } - } -} -""" - - -class Author(BaseModel): - login: str - avatarUrl: str - url: str - - -# Discussions - - -class CommentsNode(BaseModel): - createdAt: datetime - author: Union[Author, None] = None - - -class Replies(BaseModel): - nodes: List[CommentsNode] - - -class DiscussionsCommentsNode(CommentsNode): - replies: Replies - - -class Comments(BaseModel): - nodes: List[CommentsNode] - - -class DiscussionsComments(BaseModel): - nodes: List[DiscussionsCommentsNode] - - -class DiscussionsNode(BaseModel): - number: int - author: Union[Author, None] = None - title: str - createdAt: datetime - comments: DiscussionsComments - - -class DiscussionsEdge(BaseModel): - cursor: str - node: DiscussionsNode - - -class Discussions(BaseModel): - edges: List[DiscussionsEdge] - - -class DiscussionsRepository(BaseModel): - discussions: Discussions - - -class DiscussionsResponseData(BaseModel): - repository: DiscussionsRepository - - -class DiscussionsResponse(BaseModel): - data: DiscussionsResponseData - - -# PRs - - -class LabelNode(BaseModel): - name: str - - -class Labels(BaseModel): - nodes: List[LabelNode] - - -class ReviewNode(BaseModel): - author: Union[Author, None] = None - state: str - - -class Reviews(BaseModel): - nodes: List[ReviewNode] - - -class PullRequestNode(BaseModel): - number: int - labels: Labels - author: Union[Author, None] = None - title: str - createdAt: datetime - state: str - comments: Comments - reviews: Reviews - - -class PullRequestEdge(BaseModel): - cursor: str - node: PullRequestNode - - -class PullRequests(BaseModel): - edges: List[PullRequestEdge] - - -class PRsRepository(BaseModel): - pullRequests: PullRequests - - -class PRsResponseData(BaseModel): - repository: PRsRepository - - -class PRsResponse(BaseModel): - data: PRsResponseData - - -# Sponsors - - -class SponsorEntity(BaseModel): - login: str - avatarUrl: str - url: str - - -class Tier(BaseModel): - name: str - monthlyPriceInDollars: float - - -class SponsorshipAsMaintainerNode(BaseModel): - sponsorEntity: SponsorEntity - tier: Tier - - -class SponsorshipAsMaintainerEdge(BaseModel): - cursor: str - node: SponsorshipAsMaintainerNode - - -class SponsorshipAsMaintainer(BaseModel): - edges: List[SponsorshipAsMaintainerEdge] - - -class SponsorsUser(BaseModel): - sponsorshipsAsMaintainer: SponsorshipAsMaintainer - - -class SponsorsResponseData(BaseModel): - user: SponsorsUser - - -class SponsorsResponse(BaseModel): - data: SponsorsResponseData - - -class Settings(BaseSettings): - input_token: SecretStr - github_repository: str - httpx_timeout: int = 30 - - -def get_graphql_response( - *, - settings: Settings, - query: str, - after: Union[str, None] = None, - category_id: Union[str, None] = None, -) -> Dict[str, Any]: - headers = {"Authorization": f"token {settings.input_token.get_secret_value()}"} - # category_id is only used by one query, but GraphQL allows unused variables, so - # keep it here for simplicity - variables = {"after": after, "category_id": category_id} - response = httpx.post( - github_graphql_url, - headers=headers, - timeout=settings.httpx_timeout, - json={"query": query, "variables": variables, "operationName": "Q"}, - ) - if response.status_code != 200: - logging.error( - f"Response was not 200, after: {after}, category_id: {category_id}" - ) - logging.error(response.text) - raise RuntimeError(response.text) - data = response.json() - if "errors" in data: - logging.error(f"Errors in response, after: {after}, category_id: {category_id}") - logging.error(data["errors"]) - logging.error(response.text) - raise RuntimeError(response.text) - return data - - -def get_graphql_question_discussion_edges( - *, - settings: Settings, - after: Union[str, None] = None, -): - data = get_graphql_response( - settings=settings, - query=discussions_query, - after=after, - category_id=questions_category_id, - ) - graphql_response = DiscussionsResponse.model_validate(data) - return graphql_response.data.repository.discussions.edges - - -def get_graphql_pr_edges(*, settings: Settings, after: Union[str, None] = None): - data = get_graphql_response(settings=settings, query=prs_query, after=after) - graphql_response = PRsResponse.model_validate(data) - return graphql_response.data.repository.pullRequests.edges - - -def get_graphql_sponsor_edges(*, settings: Settings, after: Union[str, None] = None): - data = get_graphql_response(settings=settings, query=sponsors_query, after=after) - graphql_response = SponsorsResponse.model_validate(data) - return graphql_response.data.user.sponsorshipsAsMaintainer.edges - - -class DiscussionExpertsResults(BaseModel): - commenters: Counter - last_month_commenters: Counter - three_months_commenters: Counter - six_months_commenters: Counter - one_year_commenters: Counter - authors: Dict[str, Author] - - -def get_discussion_nodes(settings: Settings) -> List[DiscussionsNode]: - discussion_nodes: List[DiscussionsNode] = [] - discussion_edges = get_graphql_question_discussion_edges(settings=settings) - - while discussion_edges: - for discussion_edge in discussion_edges: - discussion_nodes.append(discussion_edge.node) - last_edge = discussion_edges[-1] - discussion_edges = get_graphql_question_discussion_edges( - settings=settings, after=last_edge.cursor - ) - return discussion_nodes - - -def get_discussions_experts( - discussion_nodes: List[DiscussionsNode], -) -> DiscussionExpertsResults: - commenters = Counter() - last_month_commenters = Counter() - three_months_commenters = Counter() - six_months_commenters = Counter() - one_year_commenters = Counter() - authors: Dict[str, Author] = {} - - now = datetime.now(tz=timezone.utc) - one_month_ago = now - timedelta(days=30) - three_months_ago = now - timedelta(days=90) - six_months_ago = now - timedelta(days=180) - one_year_ago = now - timedelta(days=365) - - for discussion in discussion_nodes: - discussion_author_name = None - if discussion.author: - authors[discussion.author.login] = discussion.author - discussion_author_name = discussion.author.login - discussion_commentors: dict[str, datetime] = {} - for comment in discussion.comments.nodes: - if comment.author: - authors[comment.author.login] = comment.author - if comment.author.login != discussion_author_name: - author_time = discussion_commentors.get( - comment.author.login, comment.createdAt - ) - discussion_commentors[comment.author.login] = max( - author_time, comment.createdAt - ) - for reply in comment.replies.nodes: - if reply.author: - authors[reply.author.login] = reply.author - if reply.author.login != discussion_author_name: - author_time = discussion_commentors.get( - reply.author.login, reply.createdAt - ) - discussion_commentors[reply.author.login] = max( - author_time, reply.createdAt - ) - for author_name, author_time in discussion_commentors.items(): - commenters[author_name] += 1 - if author_time > one_month_ago: - last_month_commenters[author_name] += 1 - if author_time > three_months_ago: - three_months_commenters[author_name] += 1 - if author_time > six_months_ago: - six_months_commenters[author_name] += 1 - if author_time > one_year_ago: - one_year_commenters[author_name] += 1 - discussion_experts_results = DiscussionExpertsResults( - authors=authors, - commenters=commenters, - last_month_commenters=last_month_commenters, - three_months_commenters=three_months_commenters, - six_months_commenters=six_months_commenters, - one_year_commenters=one_year_commenters, - ) - return discussion_experts_results - - -def get_pr_nodes(settings: Settings) -> List[PullRequestNode]: - pr_nodes: List[PullRequestNode] = [] - pr_edges = get_graphql_pr_edges(settings=settings) - - while pr_edges: - for edge in pr_edges: - pr_nodes.append(edge.node) - last_edge = pr_edges[-1] - pr_edges = get_graphql_pr_edges(settings=settings, after=last_edge.cursor) - return pr_nodes - - -class ContributorsResults(BaseModel): - contributors: Counter - commenters: Counter - reviewers: Counter - translation_reviewers: Counter - authors: Dict[str, Author] - - -def get_contributors(pr_nodes: List[PullRequestNode]) -> ContributorsResults: - contributors = Counter() - commenters = Counter() - reviewers = Counter() - translation_reviewers = Counter() - authors: Dict[str, Author] = {} - - for pr in pr_nodes: - author_name = None - if pr.author: - authors[pr.author.login] = pr.author - author_name = pr.author.login - pr_commentors: Set[str] = set() - pr_reviewers: Set[str] = set() - for comment in pr.comments.nodes: - if comment.author: - authors[comment.author.login] = comment.author - if comment.author.login == author_name: - continue - pr_commentors.add(comment.author.login) - for author_name in pr_commentors: - commenters[author_name] += 1 - for review in pr.reviews.nodes: - if review.author: - authors[review.author.login] = review.author - pr_reviewers.add(review.author.login) - for label in pr.labels.nodes: - if label.name == "lang-all": - translation_reviewers[review.author.login] += 1 - break - for reviewer in pr_reviewers: - reviewers[reviewer] += 1 - if pr.state == "MERGED" and pr.author: - contributors[pr.author.login] += 1 - return ContributorsResults( - contributors=contributors, - commenters=commenters, - reviewers=reviewers, - translation_reviewers=translation_reviewers, - authors=authors, - ) - - -def get_individual_sponsors(settings: Settings): - nodes: List[SponsorshipAsMaintainerNode] = [] - edges = get_graphql_sponsor_edges(settings=settings) - - while edges: - for edge in edges: - nodes.append(edge.node) - last_edge = edges[-1] - edges = get_graphql_sponsor_edges(settings=settings, after=last_edge.cursor) - - tiers: DefaultDict[float, Dict[str, SponsorEntity]] = defaultdict(dict) - for node in nodes: - tiers[node.tier.monthlyPriceInDollars][node.sponsorEntity.login] = ( - node.sponsorEntity - ) - return tiers - - -def get_top_users( - *, - counter: Counter, - authors: Dict[str, Author], - skip_users: Container[str], - min_count: int = 2, -): - users = [] - for commenter, count in counter.most_common(50): - if commenter in skip_users: - continue - if count >= min_count: - author = authors[commenter] - users.append( - { - "login": commenter, - "count": count, - "avatarUrl": author.avatarUrl, - "url": author.url, - } - ) - return users - - -if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) - settings = Settings() - logging.info(f"Using config: {settings.model_dump_json()}") - g = Github(settings.input_token.get_secret_value()) - repo = g.get_repo(settings.github_repository) - discussion_nodes = get_discussion_nodes(settings=settings) - experts_results = get_discussions_experts(discussion_nodes=discussion_nodes) - pr_nodes = get_pr_nodes(settings=settings) - contributors_results = get_contributors(pr_nodes=pr_nodes) - authors = {**experts_results.authors, **contributors_results.authors} - maintainers_logins = {"tiangolo"} - bot_names = {"codecov", "github-actions", "pre-commit-ci", "dependabot"} - maintainers = [] - for login in maintainers_logins: - user = authors[login] - maintainers.append( - { - "login": login, - "answers": experts_results.commenters[login], - "prs": contributors_results.contributors[login], - "avatarUrl": user.avatarUrl, - "url": user.url, - } - ) - - skip_users = maintainers_logins | bot_names - experts = get_top_users( - counter=experts_results.commenters, - authors=authors, - skip_users=skip_users, - ) - last_month_experts = get_top_users( - counter=experts_results.last_month_commenters, - authors=authors, - skip_users=skip_users, - ) - three_months_experts = get_top_users( - counter=experts_results.three_months_commenters, - authors=authors, - skip_users=skip_users, - ) - six_months_experts = get_top_users( - counter=experts_results.six_months_commenters, - authors=authors, - skip_users=skip_users, - ) - one_year_experts = get_top_users( - counter=experts_results.one_year_commenters, - authors=authors, - skip_users=skip_users, - ) - top_contributors = get_top_users( - counter=contributors_results.contributors, - authors=authors, - skip_users=skip_users, - ) - top_reviewers = get_top_users( - counter=contributors_results.reviewers, - authors=authors, - skip_users=skip_users, - ) - top_translations_reviewers = get_top_users( - counter=contributors_results.translation_reviewers, - authors=authors, - skip_users=skip_users, - ) - - tiers = get_individual_sponsors(settings=settings) - keys = list(tiers.keys()) - keys.sort(reverse=True) - sponsors = [] - for key in keys: - sponsor_group = [] - for login, sponsor in tiers[key].items(): - sponsor_group.append( - {"login": login, "avatarUrl": sponsor.avatarUrl, "url": sponsor.url} - ) - sponsors.append(sponsor_group) - - people = { - "maintainers": maintainers, - "experts": experts, - "last_month_experts": last_month_experts, - "three_months_experts": three_months_experts, - "six_months_experts": six_months_experts, - "one_year_experts": one_year_experts, - "top_contributors": top_contributors, - "top_reviewers": top_reviewers, - "top_translations_reviewers": top_translations_reviewers, - } - github_sponsors = { - "sponsors": sponsors, - } - # For local development - # people_path = Path("../../../../docs/en/data/people.yml") - people_path = Path("./docs/en/data/people.yml") - github_sponsors_path = Path("./docs/en/data/github_sponsors.yml") - people_old_content = people_path.read_text(encoding="utf-8") - github_sponsors_old_content = github_sponsors_path.read_text(encoding="utf-8") - new_people_content = yaml.dump( - people, sort_keys=False, width=200, allow_unicode=True - ) - new_github_sponsors_content = yaml.dump( - github_sponsors, sort_keys=False, width=200, allow_unicode=True - ) - if ( - people_old_content == new_people_content - and github_sponsors_old_content == new_github_sponsors_content - ): - logging.info("The FastAPI People data hasn't changed, finishing.") - sys.exit(0) - people_path.write_text(new_people_content, encoding="utf-8") - github_sponsors_path.write_text(new_github_sponsors_content, encoding="utf-8") - logging.info("Setting up GitHub Actions git user") - subprocess.run(["git", "config", "user.name", "github-actions"], check=True) - subprocess.run( - ["git", "config", "user.email", "github-actions@github.com"], check=True - ) - branch_name = "fastapi-people" - logging.info(f"Creating a new branch {branch_name}") - subprocess.run(["git", "checkout", "-b", branch_name], check=True) - logging.info("Adding updated file") - subprocess.run( - ["git", "add", str(people_path), str(github_sponsors_path)], check=True - ) - logging.info("Committing updated file") - message = "👥 Update FastAPI People" - result = subprocess.run(["git", "commit", "-m", message], check=True) - logging.info("Pushing branch") - subprocess.run(["git", "push", "origin", branch_name], check=True) - logging.info("Creating PR") - pr = repo.create_pull(title=message, body=message, base="master", head=branch_name) - logging.info(f"Created PR: {pr.number}") - logging.info("Finished") diff --git a/.github/workflows/people.yml b/.github/workflows/people.yml index c60c63d1b..6ec3c1ad2 100644 --- a/.github/workflows/people.yml +++ b/.github/workflows/people.yml @@ -6,29 +6,48 @@ on: workflow_dispatch: inputs: debug_enabled: - description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)' + description: Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate) required: false - default: 'false' + default: "false" + +env: + UV_SYSTEM_PYTHON: 1 jobs: - fastapi-people: + job: if: github.repository_owner == 'fastapi' runs-on: ubuntu-latest + permissions: + contents: write steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 - # Ref: https://github.com/actions/runner/issues/2033 - - name: Fix git safe.directory in container - run: mkdir -p /home/runner/work/_temp/_github_home && printf "[safe]\n\tdirectory = /github/workspace" > /home/runner/work/_temp/_github_home/.gitconfig + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Setup uv + uses: astral-sh/setup-uv@v5 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - name: Install Dependencies + run: uv pip install -r requirements-github-actions.txt # Allow debugging with tmate - name: Setup tmate session uses: mxschmitt/action-tmate@v3 if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - - uses: ./.github/actions/people - with: - token: ${{ secrets.FASTAPI_PEOPLE }} + env: + GITHUB_TOKEN: ${{ secrets.FASTAPI_PEOPLE }} + - name: FastAPI People Experts + run: python ./scripts/people.py + env: + GITHUB_TOKEN: ${{ secrets.FASTAPI_PEOPLE }} diff --git a/docs/en/docs/fastapi-people.md b/docs/en/docs/fastapi-people.md index ffc579b10..f2ca26013 100644 --- a/docs/en/docs/fastapi-people.md +++ b/docs/en/docs/fastapi-people.md @@ -47,9 +47,11 @@ This is the current list of team members. 😎 They have different levels of involvement and permissions, they can perform [repository management tasks](./management-tasks.md){.internal-link target=_blank} and together we [manage the FastAPI repository](./management.md){.internal-link target=_blank}.
    + {% for user in members["members"] %} + {% endfor %}
    @@ -83,9 +85,15 @@ You can see the **FastAPI Experts** for: These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last month. 🤓
    + {% for user in people.last_month_experts[:10] %} +{% if user.login not in skip_users %} +
    @{{ user.login }}
    Questions replied: {{ user.count }}
    + +{% endif %} + {% endfor %}
    @@ -95,9 +103,15 @@ These are the users that have been [helping others the most with questions in Gi These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last 3 months. 😎
    + {% for user in people.three_months_experts[:10] %} +{% if user.login not in skip_users %} +
    @{{ user.login }}
    Questions replied: {{ user.count }}
    + +{% endif %} + {% endfor %}
    @@ -107,9 +121,15 @@ These are the users that have been [helping others the most with questions in Gi These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last 6 months. 🧐
    + {% for user in people.six_months_experts[:10] %} +{% if user.login not in skip_users %} +
    @{{ user.login }}
    Questions replied: {{ user.count }}
    + +{% endif %} + {% endfor %}
    @@ -119,9 +139,15 @@ These are the users that have been [helping others the most with questions in Gi These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last year. 🧑‍🔬
    + {% for user in people.one_year_experts[:20] %} +{% if user.login not in skip_users %} +
    @{{ user.login }}
    Questions replied: {{ user.count }}
    + +{% endif %} + {% endfor %}
    @@ -133,9 +159,15 @@ Here are the all time **FastAPI Experts**. 🤓🤯 These are the users that have [helped others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} through *all time*. 🧙
    + {% for user in people.experts[:50] %} +{% if user.login not in skip_users %} +
    @{{ user.login }}
    Questions replied: {{ user.count }}
    + +{% endif %} + {% endfor %}
    @@ -149,6 +181,7 @@ These users have [created the most Pull Requests](help-fastapi.md#create-a-pull- They have contributed source code, documentation, etc. 📦
    + {% for user in (contributors.values() | list)[:50] %} {% if user.login not in skip_users %} diff --git a/scripts/people.py b/scripts/people.py new file mode 100644 index 000000000..f61fd31c9 --- /dev/null +++ b/scripts/people.py @@ -0,0 +1,401 @@ +import logging +import secrets +import subprocess +import time +from collections import Counter +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import Any, Container, Union + +import httpx +import yaml +from github import Github +from pydantic import BaseModel, SecretStr +from pydantic_settings import BaseSettings + +github_graphql_url = "https://api.github.com/graphql" +questions_category_id = "MDE4OkRpc2N1c3Npb25DYXRlZ29yeTMyMDAxNDM0" + +discussions_query = """ +query Q($after: String, $category_id: ID) { + repository(name: "fastapi", owner: "fastapi") { + discussions(first: 100, after: $after, categoryId: $category_id) { + edges { + cursor + node { + number + author { + login + avatarUrl + url + } + createdAt + comments(first: 50) { + totalCount + nodes { + createdAt + author { + login + avatarUrl + url + } + isAnswer + replies(first: 10) { + totalCount + nodes { + createdAt + author { + login + avatarUrl + url + } + } + } + } + } + } + } + } + } +} +""" + + +class Author(BaseModel): + login: str + avatarUrl: str | None = None + url: str | None = None + + +class CommentsNode(BaseModel): + createdAt: datetime + author: Union[Author, None] = None + + +class Replies(BaseModel): + totalCount: int + nodes: list[CommentsNode] + + +class DiscussionsCommentsNode(CommentsNode): + replies: Replies + + +class DiscussionsComments(BaseModel): + totalCount: int + nodes: list[DiscussionsCommentsNode] + + +class DiscussionsNode(BaseModel): + number: int + author: Union[Author, None] = None + title: str | None = None + createdAt: datetime + comments: DiscussionsComments + + +class DiscussionsEdge(BaseModel): + cursor: str + node: DiscussionsNode + + +class Discussions(BaseModel): + edges: list[DiscussionsEdge] + + +class DiscussionsRepository(BaseModel): + discussions: Discussions + + +class DiscussionsResponseData(BaseModel): + repository: DiscussionsRepository + + +class DiscussionsResponse(BaseModel): + data: DiscussionsResponseData + + +class Settings(BaseSettings): + github_token: SecretStr + github_repository: str + httpx_timeout: int = 30 + + +def get_graphql_response( + *, + settings: Settings, + query: str, + after: Union[str, None] = None, + category_id: Union[str, None] = None, +) -> dict[str, Any]: + headers = {"Authorization": f"token {settings.github_token.get_secret_value()}"} + variables = {"after": after, "category_id": category_id} + response = httpx.post( + github_graphql_url, + headers=headers, + timeout=settings.httpx_timeout, + json={"query": query, "variables": variables, "operationName": "Q"}, + ) + if response.status_code != 200: + logging.error( + f"Response was not 200, after: {after}, category_id: {category_id}" + ) + logging.error(response.text) + raise RuntimeError(response.text) + data = response.json() + if "errors" in data: + logging.error(f"Errors in response, after: {after}, category_id: {category_id}") + logging.error(data["errors"]) + logging.error(response.text) + raise RuntimeError(response.text) + return data + + +def get_graphql_question_discussion_edges( + *, + settings: Settings, + after: Union[str, None] = None, +) -> list[DiscussionsEdge]: + data = get_graphql_response( + settings=settings, + query=discussions_query, + after=after, + category_id=questions_category_id, + ) + graphql_response = DiscussionsResponse.model_validate(data) + return graphql_response.data.repository.discussions.edges + + +class DiscussionExpertsResults(BaseModel): + commenters: Counter[str] + last_month_commenters: Counter[str] + three_months_commenters: Counter[str] + six_months_commenters: Counter[str] + one_year_commenters: Counter[str] + authors: dict[str, Author] + + +def get_discussion_nodes(settings: Settings) -> list[DiscussionsNode]: + discussion_nodes: list[DiscussionsNode] = [] + discussion_edges = get_graphql_question_discussion_edges(settings=settings) + + while discussion_edges: + for discussion_edge in discussion_edges: + discussion_nodes.append(discussion_edge.node) + last_edge = discussion_edges[-1] + # Handle GitHub secondary rate limits, requests per minute + time.sleep(5) + discussion_edges = get_graphql_question_discussion_edges( + settings=settings, after=last_edge.cursor + ) + return discussion_nodes + + +def get_discussions_experts( + discussion_nodes: list[DiscussionsNode], +) -> DiscussionExpertsResults: + commenters = Counter[str]() + last_month_commenters = Counter[str]() + three_months_commenters = Counter[str]() + six_months_commenters = Counter[str]() + one_year_commenters = Counter[str]() + authors: dict[str, Author] = {} + + now = datetime.now(tz=timezone.utc) + one_month_ago = now - timedelta(days=30) + three_months_ago = now - timedelta(days=90) + six_months_ago = now - timedelta(days=180) + one_year_ago = now - timedelta(days=365) + + for discussion in discussion_nodes: + discussion_author_name = None + if discussion.author: + authors[discussion.author.login] = discussion.author + discussion_author_name = discussion.author.login + discussion_commentors: dict[str, datetime] = {} + for comment in discussion.comments.nodes: + if comment.author: + authors[comment.author.login] = comment.author + if comment.author.login != discussion_author_name: + author_time = discussion_commentors.get( + comment.author.login, comment.createdAt + ) + discussion_commentors[comment.author.login] = max( + author_time, comment.createdAt + ) + for reply in comment.replies.nodes: + if reply.author: + authors[reply.author.login] = reply.author + if reply.author.login != discussion_author_name: + author_time = discussion_commentors.get( + reply.author.login, reply.createdAt + ) + discussion_commentors[reply.author.login] = max( + author_time, reply.createdAt + ) + for author_name, author_time in discussion_commentors.items(): + commenters[author_name] += 1 + if author_time > one_month_ago: + last_month_commenters[author_name] += 1 + if author_time > three_months_ago: + three_months_commenters[author_name] += 1 + if author_time > six_months_ago: + six_months_commenters[author_name] += 1 + if author_time > one_year_ago: + one_year_commenters[author_name] += 1 + discussion_experts_results = DiscussionExpertsResults( + authors=authors, + commenters=commenters, + last_month_commenters=last_month_commenters, + three_months_commenters=three_months_commenters, + six_months_commenters=six_months_commenters, + one_year_commenters=one_year_commenters, + ) + return discussion_experts_results + + +def get_top_users( + *, + counter: Counter[str], + authors: dict[str, Author], + skip_users: Container[str], + min_count: int = 2, +) -> list[dict[str, Any]]: + users: list[dict[str, Any]] = [] + for commenter, count in counter.most_common(50): + if commenter in skip_users: + continue + if count >= min_count: + author = authors[commenter] + users.append( + { + "login": commenter, + "count": count, + "avatarUrl": author.avatarUrl, + "url": author.url, + } + ) + return users + + +def get_users_to_write( + *, + counter: Counter[str], + authors: dict[str, Author], + min_count: int = 2, +) -> list[dict[str, Any]]: + users: dict[str, Any] = {} + users_list: list[dict[str, Any]] = [] + for user, count in counter.most_common(60): + if count >= min_count: + author = authors[user] + user_data = { + "login": user, + "count": count, + "avatarUrl": author.avatarUrl, + "url": author.url, + } + users[user] = user_data + users_list.append(user_data) + return users_list + + +def update_content(*, content_path: Path, new_content: Any) -> bool: + old_content = content_path.read_text(encoding="utf-8") + + new_content = yaml.dump(new_content, sort_keys=False, width=200, allow_unicode=True) + if old_content == new_content: + logging.info(f"The content hasn't changed for {content_path}") + return False + content_path.write_text(new_content, encoding="utf-8") + logging.info(f"Updated {content_path}") + return True + + +def main() -> None: + logging.basicConfig(level=logging.INFO) + settings = Settings() + logging.info(f"Using config: {settings.model_dump_json()}") + g = Github(settings.github_token.get_secret_value()) + repo = g.get_repo(settings.github_repository) + + discussion_nodes = get_discussion_nodes(settings=settings) + experts_results = get_discussions_experts(discussion_nodes=discussion_nodes) + + authors = experts_results.authors + maintainers_logins = {"tiangolo"} + maintainers = [] + for login in maintainers_logins: + user = authors[login] + maintainers.append( + { + "login": login, + "answers": experts_results.commenters[login], + "avatarUrl": user.avatarUrl, + "url": user.url, + } + ) + + experts = get_users_to_write( + counter=experts_results.commenters, + authors=authors, + ) + last_month_experts = get_users_to_write( + counter=experts_results.last_month_commenters, + authors=authors, + ) + three_months_experts = get_users_to_write( + counter=experts_results.three_months_commenters, + authors=authors, + ) + six_months_experts = get_users_to_write( + counter=experts_results.six_months_commenters, + authors=authors, + ) + one_year_experts = get_users_to_write( + counter=experts_results.one_year_commenters, + authors=authors, + ) + + people = { + "maintainers": maintainers, + "experts": experts, + "last_month_experts": last_month_experts, + "three_months_experts": three_months_experts, + "six_months_experts": six_months_experts, + "one_year_experts": one_year_experts, + } + + # For local development + # people_path = Path("../docs/en/data/people.yml") + people_path = Path("./docs/en/data/people.yml") + + updated = update_content(content_path=people_path, new_content=people) + + if not updated: + logging.info("The data hasn't changed, finishing.") + return + + logging.info("Setting up GitHub Actions git user") + subprocess.run(["git", "config", "user.name", "github-actions"], check=True) + subprocess.run( + ["git", "config", "user.email", "github-actions@github.com"], check=True + ) + branch_name = f"fastapi-people-experts-{secrets.token_hex(4)}" + logging.info(f"Creating a new branch {branch_name}") + subprocess.run(["git", "checkout", "-b", branch_name], check=True) + logging.info("Adding updated file") + subprocess.run(["git", "add", str(people_path)], check=True) + logging.info("Committing updated file") + message = "👥 Update FastAPI People - Experts" + subprocess.run(["git", "commit", "-m", message], check=True) + logging.info("Pushing branch") + subprocess.run(["git", "push", "origin", branch_name], check=True) + logging.info("Creating PR") + pr = repo.create_pull(title=message, body=message, base="master", head=branch_name) + logging.info(f"Created PR: {pr.number}") + logging.info("Finished") + + +if __name__ == "__main__": + main() From e925c0ec8e4dd5ad0d2d7082de280678cead8d43 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 28 Jan 2025 20:35:19 +0000 Subject: [PATCH 733/932] =?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 [skip ci] --- 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 76333d313..3db7042fb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -16,6 +16,7 @@ hide: ### Internal +* 🔨 Update FastAPI People Experts script, refactor and optimize data fetching to handle rate limits. PR [#13267](https://github.com/fastapi/fastapi/pull/13267) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump pypa/gh-action-pypi-publish from 1.12.3 to 1.12.4. PR [#13251](https://github.com/fastapi/fastapi/pull/13251) by [@dependabot[bot]](https://github.com/apps/dependabot). ## 0.115.7 From 3da797aeb894d82be24d4a137046b65c2c1029c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 28 Jan 2025 20:41:08 +0000 Subject: [PATCH 734/932] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e=20-=20Experts=20(#13269)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions --- docs/en/data/people.yml | 1676 ++++++++++++++------------------------- 1 file changed, 592 insertions(+), 1084 deletions(-) diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml index 02d1779e0..112567778 100644 --- a/docs/en/data/people.yml +++ b/docs/en/data/people.yml @@ -1,24 +1,35 @@ maintainers: - login: tiangolo - answers: 1885 - prs: 577 - avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=740f11212a731f56798f558ceddb0bd07642afa7&v=4 + answers: 1894 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 url: https://github.com/tiangolo experts: +- login: tiangolo + count: 1894 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo +- login: github-actions + count: 770 + avatarUrl: https://avatars.githubusercontent.com/in/15368?v=4 + url: https://github.com/apps/github-actions - login: Kludex - count: 608 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + count: 644 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex -- login: dmontagu - count: 241 - avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 - url: https://github.com/dmontagu - login: jgould22 - count: 241 + count: 250 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 +- login: dmontagu + count: 240 + avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 + url: https://github.com/dmontagu +- login: YuriiMotov + count: 223 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: Mause - count: 220 + count: 219 avatarUrl: https://avatars.githubusercontent.com/u/1405026?v=4 url: https://github.com/Mause - login: ycd @@ -26,7 +37,7 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 url: https://github.com/ycd - login: JarroVGIT - count: 193 + count: 192 avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4 url: https://github.com/JarroVGIT - login: euri10 @@ -41,78 +52,82 @@ experts: count: 126 avatarUrl: https://avatars.githubusercontent.com/u/331403?v=4 url: https://github.com/phy25 -- login: YuriiMotov - count: 104 - avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 - url: https://github.com/YuriiMotov +- login: JavierSanchezCastro + count: 85 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: raphaelauv count: 83 avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 url: https://github.com/raphaelauv -- login: ArcLightSlavik - count: 71 - avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4 - url: https://github.com/ArcLightSlavik - login: ghandic count: 71 avatarUrl: https://avatars.githubusercontent.com/u/23500353?u=e2e1d736f924d9be81e8bfc565b6d8836ba99773&v=4 url: https://github.com/ghandic -- login: JavierSanchezCastro - count: 64 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro +- login: ArcLightSlavik + count: 71 + avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4 + url: https://github.com/ArcLightSlavik +- login: n8sty + count: 66 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty - login: falkben count: 59 avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 url: https://github.com/falkben -- login: n8sty - count: 56 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty - login: acidjunk count: 50 avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 url: https://github.com/acidjunk -- login: yinziyan1206 - count: 49 - avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 - url: https://github.com/yinziyan1206 - login: sm-Fifteen count: 49 avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 url: https://github.com/sm-Fifteen -- login: insomnes - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 - url: https://github.com/insomnes +- login: yinziyan1206 + count: 49 + avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 + url: https://github.com/yinziyan1206 +- login: adriangb + count: 46 + avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 + url: https://github.com/adriangb - login: Dustyposa count: 45 avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 url: https://github.com/Dustyposa -- login: adriangb +- login: insomnes count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 - url: https://github.com/adriangb -- login: frankie567 - count: 43 - avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=c159fe047727aedecbbeeaa96a1b03ceb9d39add&v=4 - url: https://github.com/frankie567 + avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 + url: https://github.com/insomnes - login: odiseo0 count: 43 avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 url: https://github.com/odiseo0 +- login: frankie567 + count: 43 + avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=c159fe047727aedecbbeeaa96a1b03ceb9d39add&v=4 + url: https://github.com/frankie567 - login: includeamin count: 40 avatarUrl: https://avatars.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4 url: https://github.com/includeamin +- login: sinisaos + count: 39 + avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 + url: https://github.com/sinisaos - login: chbndrhnns - count: 38 + count: 37 avatarUrl: https://avatars.githubusercontent.com/u/7534547?v=4 url: https://github.com/chbndrhnns - login: STeveShary count: 37 avatarUrl: https://avatars.githubusercontent.com/u/5167622?u=de8f597c81d6336fcebc37b32dfd61a3f877160c&v=4 url: https://github.com/STeveShary +- login: luzzodev + count: 36 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 + url: https://github.com/luzzodev - login: krishnardt count: 35 avatarUrl: https://avatars.githubusercontent.com/u/31960541?u=47f4829c77f4962ab437ffb7995951e41eeebe9b&v=4 @@ -123,7 +138,7 @@ experts: url: https://github.com/panla - login: prostomarkeloff count: 28 - avatarUrl: https://avatars.githubusercontent.com/u/28061158?u=72309cc1f2e04e40fa38b29969cb4e9d3f722e7b&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/28061158?u=6918e39a1224194ba636e897461a02a20126d7ad&v=4 url: https://github.com/prostomarkeloff - login: hasansezertasan count: 27 @@ -137,10 +152,6 @@ experts: count: 25 avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 url: https://github.com/wshayes -- login: acnebs - count: 23 - avatarUrl: https://avatars.githubusercontent.com/u/9054108?v=4 - url: https://github.com/acnebs - login: SirTelemak count: 23 avatarUrl: https://avatars.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4 @@ -149,6 +160,10 @@ experts: count: 22 avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 url: https://github.com/nymous +- login: acnebs + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/9054108?v=4 + url: https://github.com/acnebs - login: chrisK824 count: 22 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 @@ -157,30 +172,38 @@ experts: count: 21 avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=5fe59a56e1f2f9ccd8005d71752a8276f133ae1a&v=4 url: https://github.com/rafsaf +- login: ebottos94 + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=8b91053b3abe4a9209375e3651e1c1ef192d884b&v=4 + url: https://github.com/ebottos94 - login: nsidnev count: 20 avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4 url: https://github.com/nsidnev -- login: ebottos94 - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 - url: https://github.com/ebottos94 - login: chris-allnutt count: 20 avatarUrl: https://avatars.githubusercontent.com/u/565544?v=4 url: https://github.com/chris-allnutt -- login: retnikt - count: 18 - avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4 - url: https://github.com/retnikt +- login: estebanx64 + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 - login: zoliknemet count: 18 avatarUrl: https://avatars.githubusercontent.com/u/22326718?u=31ba446ac290e23e56eea8e4f0c558aaf0b40779&v=4 url: https://github.com/zoliknemet -- login: nkhitrov +- login: retnikt + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4 + url: https://github.com/retnikt +- login: sehraramiz count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/28262306?u=66ee21316275ef356081c2efc4ed7a4572e690dc&v=4 - url: https://github.com/nkhitrov + avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 + url: https://github.com/sehraramiz +- login: caeser1996 + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/16540232?u=05d2beb8e034d584d0a374b99d8826327bd7f614&v=4 + url: https://github.com/caeser1996 - login: Hultner count: 17 avatarUrl: https://avatars.githubusercontent.com/u/2669034?u=115e53df959309898ad8dc9443fbb35fee71df07&v=4 @@ -189,1170 +212,655 @@ experts: count: 17 avatarUrl: https://avatars.githubusercontent.com/u/1765494?u=5b1ab7c582db4b4016fa31affe977d10af108ad4&v=4 url: https://github.com/harunyasar -- login: caeser1996 +- login: nkhitrov count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/16540232?u=05d2beb8e034d584d0a374b99d8826327bd7f614&v=4 - url: https://github.com/caeser1996 + avatarUrl: https://avatars.githubusercontent.com/u/28262306?u=e19427d8dc296d6950e9c424adacc92d37496fe9&v=4 + url: https://github.com/nkhitrov +- login: jonatasoli + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4 + url: https://github.com/jonatasoli - login: dstlny count: 16 avatarUrl: https://avatars.githubusercontent.com/u/41964673?u=9f2174f9d61c15c6e3a4c9e3aeee66f711ce311f&v=4 url: https://github.com/dstlny +- login: jorgerpo + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/12537771?u=7444d20019198e34911082780cc7ad73f2b97cb3&v=4 + url: https://github.com/jorgerpo +- login: simondale00 + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/33907262?u=2721fb37014d50daf473267c808aa678ecaefe09&v=4 + url: https://github.com/simondale00 +- login: ghost + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/10137?u=b1951d34a583cf12ec0d3b0781ba19be97726318&v=4 + url: https://github.com/ghost +- login: abhint + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 + url: https://github.com/abhint +- login: pythonweb2 + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 last_month_experts: +- login: Kludex + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 + url: https://github.com/Kludex - login: YuriiMotov - count: 29 + count: 10 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov -- login: killjoy1221 +- login: sehraramiz count: 8 - avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 - url: https://github.com/killjoy1221 -- login: Kludex - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 - url: https://github.com/Kludex -- login: JavierSanchezCastro - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro -- login: hasansezertasan - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan -- login: PhysicallyActive + avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 + url: https://github.com/sehraramiz +- login: luzzodev + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 + url: https://github.com/luzzodev +- login: yokwejuste + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/71908316?u=592c1e42aa0ee5cb94890e0b863e2acc78cc3bbc&v=4 + url: https://github.com/yokwejuste +- login: alv2017 count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 - url: https://github.com/PhysicallyActive -- login: n8sty - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty -- login: pedroconceicao - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/32837064?u=5a0e6559bc391442629a28b6923790b54deb4464&v=4 - url: https://github.com/pedroconceicao + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 - login: PREPONDERANCE count: 2 avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 url: https://github.com/PREPONDERANCE -- login: aanchlia +- login: nbx3 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 - url: https://github.com/aanchlia -- login: 0sahil + avatarUrl: https://avatars.githubusercontent.com/u/34649527?u=943812f69e0d40adbd3fa1c9b8ef50dd971a2a45&v=4 + url: https://github.com/nbx3 +- login: XiaoXinYo count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/58521386?u=ac00b731c07c712d0baa57b8b70ac8422acf183c&v=4 - url: https://github.com/0sahil -- login: jgould22 + avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=b3b7cb758997f283c271a581833e407229dab82c&v=4 + url: https://github.com/XiaoXinYo +- login: iloveitaly count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 + avatarUrl: https://avatars.githubusercontent.com/u/150855?v=4 + url: https://github.com/iloveitaly three_months_experts: +- login: luzzodev + count: 34 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 + url: https://github.com/luzzodev - login: YuriiMotov - count: 101 + count: 33 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov -- login: JavierSanchezCastro - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro - login: Kludex - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex -- login: jgould22 - count: 14 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 -- login: killjoy1221 - count: 8 - avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 - url: https://github.com/killjoy1221 -- login: hasansezertasan - count: 8 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan -- login: PhysicallyActive - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 - url: https://github.com/PhysicallyActive -- login: n8sty - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty - login: sehraramiz - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/14166324?v=4 + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 url: https://github.com/sehraramiz -- login: acidjunk - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk - login: estebanx64 - count: 3 + count: 7 avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 url: https://github.com/estebanx64 -- login: PREPONDERANCE - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 - url: https://github.com/PREPONDERANCE -- login: chrisK824 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 -- login: ryanisn - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 - url: https://github.com/ryanisn -- login: pythonweb2 +- login: yvallois + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/36999744?v=4 + url: https://github.com/yvallois +- login: yokwejuste + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/71908316?u=592c1e42aa0ee5cb94890e0b863e2acc78cc3bbc&v=4 + url: https://github.com/yokwejuste +- login: jgould22 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 +- login: alv2017 count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 - url: https://github.com/pythonweb2 -- login: omarcruzpantoja + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 +- login: viniciusCalcantara count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 - url: https://github.com/omarcruzpantoja -- login: mskrip - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/17459600?u=10019d5c38ae3374dd4a6743b0223e56a78d4855&v=4 - url: https://github.com/mskrip -- login: pedroconceicao - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/32837064?u=5a0e6559bc391442629a28b6923790b54deb4464&v=4 - url: https://github.com/pedroconceicao -- login: Jackiexiao - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/18050469?u=a2003e21a7780477ba00bf87a9abef8af58e91d1&v=4 - url: https://github.com/Jackiexiao -- login: aanchlia - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 - url: https://github.com/aanchlia -- login: moreno-p + avatarUrl: https://avatars.githubusercontent.com/u/108818737?u=3d7ffe5808843ee4372f9cc5a559ff1674cf1792&v=4 + url: https://github.com/viniciusCalcantara +- login: PREPONDERANCE count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/164261630?v=4 - url: https://github.com/moreno-p -- login: 0sahil + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE +- login: nbx3 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/58521386?u=ac00b731c07c712d0baa57b8b70ac8422acf183c&v=4 - url: https://github.com/0sahil -- login: patrick91 + avatarUrl: https://avatars.githubusercontent.com/u/34649527?u=943812f69e0d40adbd3fa1c9b8ef50dd971a2a45&v=4 + url: https://github.com/nbx3 +- login: XiaoXinYo count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/667029?u=e35958a75ac1f99c81b4bc99e22db8cd665ae7f0&v=4 - url: https://github.com/patrick91 -- login: pprunty + avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=b3b7cb758997f283c271a581833e407229dab82c&v=4 + url: https://github.com/XiaoXinYo +- login: JavierSanchezCastro count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/58374462?u=5736576e586429abc97a803b8bcd4a6d828b8a2f&v=4 - url: https://github.com/pprunty -- login: angely-dev + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +- login: iloveitaly count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 - url: https://github.com/angely-dev -- login: mastizada + avatarUrl: https://avatars.githubusercontent.com/u/150855?v=4 + url: https://github.com/iloveitaly +- login: LincolnPuzey count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1975818?u=0751a06d7271c8bf17cb73b1b845644ab4d2c6dc&v=4 - url: https://github.com/mastizada -- login: sm-Fifteen + avatarUrl: https://avatars.githubusercontent.com/u/18750802?v=4 + url: https://github.com/LincolnPuzey +- login: Knighthawk-Leo count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 - url: https://github.com/sm-Fifteen -- login: methane + avatarUrl: https://avatars.githubusercontent.com/u/72437494?u=27c68db94a3107b605e603cc136f4ba83f0106d5&v=4 + url: https://github.com/Knighthawk-Leo +- login: gelezo43 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/199592?v=4 - url: https://github.com/methane -- login: konstantinos1981 + avatarUrl: https://avatars.githubusercontent.com/u/40732698?u=611f39d3c1d2f4207a590937a78c1f10eed6232c&v=4 + url: https://github.com/gelezo43 +- login: dbfreem count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/39465388?v=4 - url: https://github.com/konstantinos1981 -- login: druidance + avatarUrl: https://avatars.githubusercontent.com/u/9778569?u=f2f1e9135b5e4f1b0c6821a548b17f97572720fc&v=4 + url: https://github.com/dbfreem +- login: AliYmn count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/160344534?v=4 - url: https://github.com/druidance -- login: fabianfalon + avatarUrl: https://avatars.githubusercontent.com/u/18416653?u=98c1fca46c7e4dabe8c39d17b5e55d1511d41cf9&v=4 + url: https://github.com/AliYmn +- login: RichieB2B count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/3700760?u=95f69e31280b17ac22299cdcd345323b142fe0af&v=4 - url: https://github.com/fabianfalon -- login: VatsalJagani + avatarUrl: https://avatars.githubusercontent.com/u/1461970?u=edaa57d1077705244ea5c9244f4783d94ff11f12&v=4 + url: https://github.com/RichieB2B +- login: Synrom count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/20964366?u=43552644be05c9107c029e26d5ab3be5a1920f45&v=4 - url: https://github.com/VatsalJagani -- login: khaledadrani + avatarUrl: https://avatars.githubusercontent.com/u/30272537?v=4 + url: https://github.com/Synrom +- login: iiotsrc count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/45245894?u=49ed5056426a149a5af29d385d8bd3847101d3a4&v=4 - url: https://github.com/khaledadrani -- login: ThirVondukr + avatarUrl: https://avatars.githubusercontent.com/u/131771119?u=bcaf2559ef6266af70b151b7fda31a1ee3dbecb3&v=4 + url: https://github.com/iiotsrc +- login: Kfir-G count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 - url: https://github.com/ThirVondukr + avatarUrl: https://avatars.githubusercontent.com/u/57500876?u=0cd29db046a17f12f382d398141319fca7ff230a&v=4 + url: https://github.com/Kfir-G six_months_experts: - login: YuriiMotov - count: 104 + count: 72 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov - login: Kludex - count: 104 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + count: 39 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex +- login: sinisaos + count: 37 + avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 + url: https://github.com/sinisaos +- login: luzzodev + count: 36 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 + url: https://github.com/luzzodev - login: JavierSanchezCastro - count: 40 + count: 16 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro +- login: tiangolo + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo +- login: Kfir-G + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/57500876?u=0cd29db046a17f12f382d398141319fca7ff230a&v=4 + url: https://github.com/Kfir-G +- login: sehraramiz + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 + url: https://github.com/sehraramiz +- login: estebanx64 + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +- login: ceb10n + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 + url: https://github.com/ceb10n +- login: yvallois + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/36999744?v=4 + url: https://github.com/yvallois +- login: n8sty + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty +- login: TomFaulkner + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/14956620?v=4 + url: https://github.com/TomFaulkner +- login: yokwejuste + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/71908316?u=592c1e42aa0ee5cb94890e0b863e2acc78cc3bbc&v=4 + url: https://github.com/yokwejuste - login: jgould22 - count: 40 + count: 4 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 -- login: hasansezertasan - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan -- login: n8sty - count: 19 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty -- login: killjoy1221 - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 - url: https://github.com/killjoy1221 -- login: aanchlia - count: 8 - avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 - url: https://github.com/aanchlia -- login: estebanx64 - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 - url: https://github.com/estebanx64 -- login: PhysicallyActive - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 - url: https://github.com/PhysicallyActive -- login: dolfinus - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 - url: https://github.com/dolfinus -- login: Ventura94 - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 - url: https://github.com/Ventura94 -- login: sehraramiz - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/14166324?v=4 - url: https://github.com/sehraramiz -- login: acidjunk - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk -- login: shashstormer - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/90090313?v=4 - url: https://github.com/shashstormer -- login: GodMoonGoodman - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 - url: https://github.com/GodMoonGoodman -- login: flo-at - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 - url: https://github.com/flo-at -- login: PREPONDERANCE +- login: alv2017 count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 - url: https://github.com/PREPONDERANCE -- login: chrisK824 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 +- login: viniciusCalcantara count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 -- login: angely-dev + avatarUrl: https://avatars.githubusercontent.com/u/108818737?u=3d7ffe5808843ee4372f9cc5a559ff1674cf1792&v=4 + url: https://github.com/viniciusCalcantara +- login: pawelad count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 - url: https://github.com/angely-dev -- login: fmelihh + avatarUrl: https://avatars.githubusercontent.com/u/7062874?u=d27dc220545a8401ad21840590a97d474d7101e6&v=4 + url: https://github.com/pawelad +- login: dbfreem count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=671117dba9022db2237e3da7a39cbc2efc838db0&v=4 - url: https://github.com/fmelihh -- login: ryanisn + avatarUrl: https://avatars.githubusercontent.com/u/9778569?u=f2f1e9135b5e4f1b0c6821a548b17f97572720fc&v=4 + url: https://github.com/dbfreem +- login: Isuxiz count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 - url: https://github.com/ryanisn -- login: JoshYuJump + avatarUrl: https://avatars.githubusercontent.com/u/48672727?u=34d7b4ade252687d22a27cf53037b735b244bfc1&v=4 + url: https://github.com/Isuxiz +- login: bertomaniac count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 - url: https://github.com/JoshYuJump -- login: pythonweb2 + avatarUrl: https://avatars.githubusercontent.com/u/10235051?u=14484a96833228a7b29fee4a7916d411c242c4f6&v=4 + url: https://github.com/bertomaniac +- login: PhysicallyActive count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 - url: https://github.com/pythonweb2 -- login: omarcruzpantoja + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive +- login: Minibrams count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 - url: https://github.com/omarcruzpantoja -- login: bogdan-coman-uv + avatarUrl: https://avatars.githubusercontent.com/u/8108085?u=b028dbc308fa8485e0e2e9402b3d03d8deb22bf9&v=4 + url: https://github.com/Minibrams +- login: AIdjis count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/92912507?v=4 - url: https://github.com/bogdan-coman-uv -- login: ahmedabdou14 + avatarUrl: https://avatars.githubusercontent.com/u/88404339?u=2a80d80b054e9228391e32fb9bb39571509dab6a&v=4 + url: https://github.com/AIdjis +- login: svlandeg count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 - url: https://github.com/ahmedabdou14 -- login: mskrip + avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 + url: https://github.com/svlandeg +- login: PREPONDERANCE count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/17459600?u=10019d5c38ae3374dd4a6743b0223e56a78d4855&v=4 - url: https://github.com/mskrip -- login: leonidktoto + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE +- login: nbx3 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/159561986?v=4 - url: https://github.com/leonidktoto -- login: pedroconceicao + avatarUrl: https://avatars.githubusercontent.com/u/34649527?u=943812f69e0d40adbd3fa1c9b8ef50dd971a2a45&v=4 + url: https://github.com/nbx3 +- login: yanggeorge count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/32837064?u=5a0e6559bc391442629a28b6923790b54deb4464&v=4 - url: https://github.com/pedroconceicao -- login: hwong557 + avatarUrl: https://avatars.githubusercontent.com/u/2434407?v=4 + url: https://github.com/yanggeorge +- login: XiaoXinYo count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/460259?u=7d2f1b33ea5bda4d8e177ab3cb924a673d53087e&v=4 - url: https://github.com/hwong557 -- login: Jackiexiao + avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=b3b7cb758997f283c271a581833e407229dab82c&v=4 + url: https://github.com/XiaoXinYo +- login: pythonweb2 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/18050469?u=a2003e21a7780477ba00bf87a9abef8af58e91d1&v=4 - url: https://github.com/Jackiexiao -- login: admo1 + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 +- login: slafs count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 - url: https://github.com/admo1 -- login: binbjz + avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4 + url: https://github.com/slafs +- login: AmirHmZz count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 - url: https://github.com/binbjz -- login: nameer + avatarUrl: https://avatars.githubusercontent.com/u/38752106?u=07f80e451bda00a9492bbc764e49d24ad3ada8cc&v=4 + url: https://github.com/AmirHmZz +- login: iloveitaly count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/3931725?u=6199fb065df098fc13ac0a5e649f89672b586732&v=4 - url: https://github.com/nameer -- login: moreno-p + avatarUrl: https://avatars.githubusercontent.com/u/150855?v=4 + url: https://github.com/iloveitaly +- login: LincolnPuzey count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/164261630?v=4 - url: https://github.com/moreno-p -- login: 0sahil + avatarUrl: https://avatars.githubusercontent.com/u/18750802?v=4 + url: https://github.com/LincolnPuzey +- login: alejsdev count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/58521386?u=ac00b731c07c712d0baa57b8b70ac8422acf183c&v=4 - url: https://github.com/0sahil -- login: nymous + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 + url: https://github.com/alejsdev +- login: Knighthawk-Leo count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 - url: https://github.com/nymous -- login: patrick91 + avatarUrl: https://avatars.githubusercontent.com/u/72437494?u=27c68db94a3107b605e603cc136f4ba83f0106d5&v=4 + url: https://github.com/Knighthawk-Leo +- login: gelezo43 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/667029?u=e35958a75ac1f99c81b4bc99e22db8cd665ae7f0&v=4 - url: https://github.com/patrick91 -- login: pprunty + avatarUrl: https://avatars.githubusercontent.com/u/40732698?u=611f39d3c1d2f4207a590937a78c1f10eed6232c&v=4 + url: https://github.com/gelezo43 +- login: christiansicari count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/58374462?u=5736576e586429abc97a803b8bcd4a6d828b8a2f&v=4 - url: https://github.com/pprunty -- login: JonnyBootsNpants + avatarUrl: https://avatars.githubusercontent.com/u/29756552?v=4 + url: https://github.com/christiansicari +- login: 1001pepi count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/155071540?u=2d3a72b74a2c4c8eaacdb625c7ac850369579352&v=4 - url: https://github.com/JonnyBootsNpants -- login: richin13 + avatarUrl: https://avatars.githubusercontent.com/u/82064861?u=8c6ffdf2275d6970a07294752c545cd2702c57d3&v=4 + url: https://github.com/1001pepi +- login: AliYmn count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 - url: https://github.com/richin13 -- login: mastizada + avatarUrl: https://avatars.githubusercontent.com/u/18416653?u=98c1fca46c7e4dabe8c39d17b5e55d1511d41cf9&v=4 + url: https://github.com/AliYmn +- login: RichieB2B count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1975818?u=0751a06d7271c8bf17cb73b1b845644ab4d2c6dc&v=4 - url: https://github.com/mastizada -- login: sm-Fifteen + avatarUrl: https://avatars.githubusercontent.com/u/1461970?u=edaa57d1077705244ea5c9244f4783d94ff11f12&v=4 + url: https://github.com/RichieB2B +- login: Synrom count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 - url: https://github.com/sm-Fifteen -- login: amacfie + avatarUrl: https://avatars.githubusercontent.com/u/30272537?v=4 + url: https://github.com/Synrom +- login: ecly + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8410422?v=4 + url: https://github.com/ecly +- login: iiotsrc + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/131771119?u=bcaf2559ef6266af70b151b7fda31a1ee3dbecb3&v=4 + url: https://github.com/iiotsrc +- login: simondale00 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/33907262?u=2721fb37014d50daf473267c808aa678ecaefe09&v=4 + url: https://github.com/simondale00 +- login: jd-solanki + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/47495003?u=6e225cb42c688d0cd70e65c6baedb9f5922b1178&v=4 + url: https://github.com/jd-solanki +- login: AumGupta + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/86357151?u=7d05aa606c0611a18f4db16cf26361ce10a6e195&v=4 + url: https://github.com/AumGupta +- login: DeoLeung + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/3764720?u=4c222ef513814de4c7fb3736d0a7adf11d953d43&v=4 + url: https://github.com/DeoLeung +- login: Reemyos + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/44867003?v=4 + url: https://github.com/Reemyos +- login: deight93 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/37678115?u=a608798b5bd0034183a9c430ebb42fb266db86ce&v=4 + url: https://github.com/deight93 +- login: Jkrox + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/83181939?u=d6a922d97129f7f3916d6a1c166bc011b3a72b7f&v=4 + url: https://github.com/Jkrox +- login: mmzeynalli + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/33568903?u=19efd0c0722730b83a70b7c86c36e5b7d83e07d2&v=4 + url: https://github.com/mmzeynalli +- login: ddahan + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1933516?u=1d200a620e8d6841df017e9f2bb7efb58b580f40&v=4 + url: https://github.com/ddahan +- login: jfeaver + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1091338?u=0bcba366447d8fadad63f6705a52d128da4c7ec2&v=4 + url: https://github.com/jfeaver +- login: Wurstnase count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 - url: https://github.com/amacfie -- login: garg10may + avatarUrl: https://avatars.githubusercontent.com/u/8709415?u=f479af475a97aee9a1dab302cfc35d07e9ea245f&v=4 + url: https://github.com/Wurstnase +- login: tristan count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8787120?u=7028d2b3a2a26534c1806eb76c7425a3fac9732f&v=4 - url: https://github.com/garg10may -- login: methane + avatarUrl: https://avatars.githubusercontent.com/u/1412?u=aab8aaa4cc0f1210ac45fc93873a5909d314c965&v=4 + url: https://github.com/tristan +- login: chandanch count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/199592?v=4 - url: https://github.com/methane -- login: konstantinos1981 + avatarUrl: https://avatars.githubusercontent.com/u/8663552?u=afc484bc0a952c83f1fb6a1583cda443f807cd66&v=4 + url: https://github.com/chandanch +- login: rvishruth count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/39465388?v=4 - url: https://github.com/konstantinos1981 -- login: druidance + avatarUrl: https://avatars.githubusercontent.com/u/79176273?v=4 + url: https://github.com/rvishruth +- login: mattmess1221 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/160344534?v=4 - url: https://github.com/druidance + avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 + url: https://github.com/mattmess1221 +- login: meower1 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/109747197?u=0a5cc2a6ae74e558f0afc2874da85132e5953d8b&v=4 + url: https://github.com/meower1 one_year_experts: -- login: Kludex - count: 207 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 - url: https://github.com/Kludex -- login: jgould22 - count: 118 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 - login: YuriiMotov - count: 104 + count: 223 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov +- login: Kludex + count: 83 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 + url: https://github.com/Kludex - login: JavierSanchezCastro - count: 59 + count: 47 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro +- login: jgould22 + count: 42 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 +- login: sinisaos + count: 39 + avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 + url: https://github.com/sinisaos +- login: luzzodev + count: 36 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 + url: https://github.com/luzzodev +- login: tiangolo + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo - login: n8sty - count: 40 + count: 23 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty -- login: hasansezertasan - count: 27 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan -- login: chrisK824 - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 -- login: ahmedabdou14 - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 - url: https://github.com/ahmedabdou14 -- login: arjwilliams - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/22227620?v=4 - url: https://github.com/arjwilliams -- login: killjoy1221 - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 - url: https://github.com/killjoy1221 -- login: WilliamStam - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/182800?v=4 - url: https://github.com/WilliamStam -- login: iudeen - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 - url: https://github.com/iudeen -- login: nymous - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 - url: https://github.com/nymous -- login: aanchlia - count: 8 - avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 - url: https://github.com/aanchlia - login: estebanx64 - count: 7 + count: 19 avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 url: https://github.com/estebanx64 -- login: pythonweb2 - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 - url: https://github.com/pythonweb2 -- login: romabozhanovgithub - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/67696229?u=e4b921eef096415300425aca249348f8abb78ad7&v=4 - url: https://github.com/romabozhanovgithub +- login: sehraramiz + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 + url: https://github.com/sehraramiz - login: PhysicallyActive - count: 6 + count: 14 avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 url: https://github.com/PhysicallyActive -- login: mikeedjones - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/4087139?u=cc4a242896ac2fcf88a53acfaf190d0fe0a1f0c9&v=4 - url: https://github.com/mikeedjones -- login: dolfinus - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 - url: https://github.com/dolfinus -- login: ebottos94 - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 - url: https://github.com/ebottos94 -- login: Ventura94 - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 - url: https://github.com/Ventura94 -- login: White-Mask +- login: ceb10n + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 + url: https://github.com/ceb10n +- login: Kfir-G + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/57500876?u=0cd29db046a17f12f382d398141319fca7ff230a&v=4 + url: https://github.com/Kfir-G +- login: mattmess1221 + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 + url: https://github.com/mattmess1221 +- login: hasansezertasan + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan +- login: AIdjis + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/88404339?u=2a80d80b054e9228391e32fb9bb39571509dab6a&v=4 + url: https://github.com/AIdjis +- login: yvallois count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/31826970?u=8625355dc25ddf9c85a8b2b0b9932826c4c8f44c&v=4 - url: https://github.com/White-Mask -- login: sehraramiz + avatarUrl: https://avatars.githubusercontent.com/u/36999744?v=4 + url: https://github.com/yvallois +- login: PREPONDERANCE count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/14166324?v=4 - url: https://github.com/sehraramiz + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE +- login: pythonweb2 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 - login: acidjunk count: 5 avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 url: https://github.com/acidjunk -- login: JoshYuJump +- login: gustavosett count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 - url: https://github.com/JoshYuJump -- login: alex-pobeditel-2004 - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/14791483?v=4 - url: https://github.com/alex-pobeditel-2004 -- login: shashstormer - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/90090313?v=4 - url: https://github.com/shashstormer -- login: wu-clan + avatarUrl: https://avatars.githubusercontent.com/u/99373133?u=1739ca547c3d200f1b72450520bce46a97aab184&v=4 + url: https://github.com/gustavosett +- login: binbjz count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/52145145?u=f8c9e5c8c259d248e1683fedf5027b4ee08a0967&v=4 - url: https://github.com/wu-clan -- login: abhint + avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 + url: https://github.com/binbjz +- login: chyok count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 - url: https://github.com/abhint -- login: anthonycepeda + avatarUrl: https://avatars.githubusercontent.com/u/32629225?u=3b7c30e8a09426a1b9284f6e8a0ae53a525596bf&v=4 + url: https://github.com/chyok +- login: TomFaulkner count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 - url: https://github.com/anthonycepeda -- login: GodMoonGoodman + avatarUrl: https://avatars.githubusercontent.com/u/14956620?v=4 + url: https://github.com/TomFaulkner +- login: yokwejuste count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 - url: https://github.com/GodMoonGoodman + avatarUrl: https://avatars.githubusercontent.com/u/71908316?u=592c1e42aa0ee5cb94890e0b863e2acc78cc3bbc&v=4 + url: https://github.com/yokwejuste +- login: DeoLeung + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/3764720?u=4c222ef513814de4c7fb3736d0a7adf11d953d43&v=4 + url: https://github.com/DeoLeung - login: flo-at count: 4 avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 url: https://github.com/flo-at -- login: yinziyan1206 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 - url: https://github.com/yinziyan1206 -- login: amacfie - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 - url: https://github.com/amacfie -- login: commonism - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/164513?v=4 - url: https://github.com/commonism -- login: dmontagu +- login: GodMoonGoodman count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 - url: https://github.com/dmontagu -- login: sanzoghenzo + avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 + url: https://github.com/GodMoonGoodman +- login: bertomaniac count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/977953?v=4 - url: https://github.com/sanzoghenzo -- login: lucasgadams + avatarUrl: https://avatars.githubusercontent.com/u/10235051?u=14484a96833228a7b29fee4a7916d411c242c4f6&v=4 + url: https://github.com/bertomaniac +- login: alv2017 count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/36425095?v=4 - url: https://github.com/lucasgadams -- login: NeilBotelho + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 +- login: msehnout count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/39030675?u=16fea2ff90a5c67b974744528a38832a6d1bb4f7&v=4 - url: https://github.com/NeilBotelho -- login: hhartzer + avatarUrl: https://avatars.githubusercontent.com/u/9369632?u=8c988f1b008a3f601385a3616f9327820f66e3a5&v=4 + url: https://github.com/msehnout +- login: viniciusCalcantara count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/100533792?v=4 - url: https://github.com/hhartzer -- login: binbjz + avatarUrl: https://avatars.githubusercontent.com/u/108818737?u=3d7ffe5808843ee4372f9cc5a559ff1674cf1792&v=4 + url: https://github.com/viniciusCalcantara +- login: pawelad count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 - url: https://github.com/binbjz -- login: PREPONDERANCE + avatarUrl: https://avatars.githubusercontent.com/u/7062874?u=d27dc220545a8401ad21840590a97d474d7101e6&v=4 + url: https://github.com/pawelad +- login: ThirVondukr count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 - url: https://github.com/PREPONDERANCE -- login: nameer + avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 + url: https://github.com/ThirVondukr +- login: dbfreem + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/9778569?u=f2f1e9135b5e4f1b0c6821a548b17f97572720fc&v=4 + url: https://github.com/dbfreem +- login: Isuxiz count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/3931725?u=6199fb065df098fc13ac0a5e649f89672b586732&v=4 - url: https://github.com/nameer + avatarUrl: https://avatars.githubusercontent.com/u/48672727?u=34d7b4ade252687d22a27cf53037b735b244bfc1&v=4 + url: https://github.com/Isuxiz - login: angely-dev count: 3 avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 url: https://github.com/angely-dev -- login: fmelihh +- login: deight93 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/37678115?u=a608798b5bd0034183a9c430ebb42fb266db86ce&v=4 + url: https://github.com/deight93 +- login: mmzeynalli count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=671117dba9022db2237e3da7a39cbc2efc838db0&v=4 - url: https://github.com/fmelihh + avatarUrl: https://avatars.githubusercontent.com/u/33568903?u=19efd0c0722730b83a70b7c86c36e5b7d83e07d2&v=4 + url: https://github.com/mmzeynalli +- login: Minibrams + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/8108085?u=b028dbc308fa8485e0e2e9402b3d03d8deb22bf9&v=4 + url: https://github.com/Minibrams - login: ryanisn count: 3 avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 url: https://github.com/ryanisn -- login: theobouwman +- login: svlandeg count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/16098190?u=dc70db88a7a99b764c9a89a6e471e0b7ca478a35&v=4 - url: https://github.com/theobouwman -- login: methane + avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 + url: https://github.com/svlandeg +- login: alexandercronin count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/199592?v=4 - url: https://github.com/methane -top_contributors: -- login: nilslindemann - count: 130 - avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 - url: https://github.com/nilslindemann -- login: jaystone776 - count: 49 - avatarUrl: https://avatars.githubusercontent.com/u/11191137?u=299205a95e9b6817a43144a48b643346a5aac5cc&v=4 - url: https://github.com/jaystone776 -- login: waynerv - count: 25 - avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 - url: https://github.com/waynerv -- login: tokusumi - count: 24 - avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 - url: https://github.com/tokusumi -- login: SwftAlpc - count: 23 - avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 - url: https://github.com/SwftAlpc -- login: Kludex - count: 22 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 - url: https://github.com/Kludex -- login: hasansezertasan - count: 22 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan -- login: dmontagu - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 - url: https://github.com/dmontagu -- login: Xewus - count: 14 - avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 - url: https://github.com/Xewus -- login: euri10 - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/1104190?u=321a2e953e6645a7d09b732786c7a8061e0f8a8b&v=4 - url: https://github.com/euri10 -- login: mariacamilagl - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 - url: https://github.com/mariacamilagl -- login: AlertRED - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 - url: https://github.com/AlertRED -- login: Smlep - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4 - url: https://github.com/Smlep -- login: alejsdev - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=9ca449ad5161af12766ddd1a22988e9b14315f5c&v=4 - url: https://github.com/alejsdev -- login: hard-coders - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 - url: https://github.com/hard-coders -- login: KaniKim - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=40f8f7f3f36d5f2365ba2ad0b40693e60958ce70&v=4 - url: https://github.com/KaniKim -- login: xzmeng - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/40202897?v=4 - url: https://github.com/xzmeng -- login: Serrones - count: 8 - avatarUrl: https://avatars.githubusercontent.com/u/22691749?u=4795b880e13ca33a73e52fc0ef7dc9c60c8fce47&v=4 - url: https://github.com/Serrones -- login: rjNemo - count: 8 - avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 - url: https://github.com/rjNemo -- login: pablocm83 - count: 8 - avatarUrl: https://avatars.githubusercontent.com/u/28315068?u=3310fbb05bb8bfc50d2c48b6cb64ac9ee4a14549&v=4 - url: https://github.com/pablocm83 -- login: RunningIkkyu - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4 - url: https://github.com/RunningIkkyu -- login: Alexandrhub - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 - url: https://github.com/Alexandrhub -- login: NinaHwang - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/79563565?u=eee6bfe9224c71193025ab7477f4f96ceaa05c62&v=4 - url: https://github.com/NinaHwang -- login: batlopes - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/33462923?u=0fb3d7acb316764616f11e4947faf080e49ad8d9&v=4 - url: https://github.com/batlopes -- login: wshayes - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 - url: https://github.com/wshayes -- login: samuelcolvin - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/4039449?u=42eb3b833047c8c4b4f647a031eaef148c16d93f&v=4 - url: https://github.com/samuelcolvin -- login: Attsun1031 - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/1175560?v=4 - url: https://github.com/Attsun1031 -- login: ComicShrimp - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=d2fbf412e7730183ce91686ca48d4147e1b7dc74&v=4 - url: https://github.com/ComicShrimp -- login: rostik1410 - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4 - url: https://github.com/rostik1410 -- login: tamtam-fitness - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/62091034?u=8da19a6bd3d02f5d6ba30c7247d5b46c98dd1403&v=4 - url: https://github.com/tamtam-fitness -- login: jekirl - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/2546697?u=a027452387d85bd4a14834e19d716c99255fb3b7&v=4 - url: https://github.com/jekirl -- login: jfunez - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/805749?v=4 - url: https://github.com/jfunez -- login: ycd - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 - url: https://github.com/ycd -- login: komtaki - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 - url: https://github.com/komtaki -- login: hitrust - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/3360631?u=5fa1f475ad784d64eb9666bdd43cc4d285dcc773&v=4 - url: https://github.com/hitrust -- login: JulianMaurin - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/63545168?u=b7d15ac865268cbefc2d739e2f23d9aeeac1a622&v=4 - url: https://github.com/JulianMaurin -- login: lsglucas - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 - url: https://github.com/lsglucas -- login: BilalAlpaslan - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 - url: https://github.com/BilalAlpaslan -- login: adriangb - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 - url: https://github.com/adriangb -- login: iudeen - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 - url: https://github.com/iudeen -- login: axel584 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 - url: https://github.com/axel584 -- login: ivan-abc - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 - url: https://github.com/ivan-abc -- login: divums + avatarUrl: https://avatars.githubusercontent.com/u/8014288?u=69580504c51a0cdd756fc47b23bb7f404bd694e7&v=4 + url: https://github.com/alexandercronin +- login: aanchlia count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/1397556?v=4 - url: https://github.com/divums -- login: prostomarkeloff + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia +- login: chrisK824 count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/28061158?u=72309cc1f2e04e40fa38b29969cb4e9d3f722e7b&v=4 - url: https://github.com/prostomarkeloff -- login: nsidnev + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 +- login: omarcruzpantoja count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4 - url: https://github.com/nsidnev -- login: pawamoy + avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 + url: https://github.com/omarcruzpantoja +- login: ahmedabdou14 count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4 - url: https://github.com/pawamoy -top_reviewers: -- login: Kludex - count: 158 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 - url: https://github.com/Kludex -- login: BilalAlpaslan - count: 86 - avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 - url: https://github.com/BilalAlpaslan -- login: yezz123 - count: 85 - avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=d7062cbc6eb7671d5dc9cc0e32a24ae335e0f225&v=4 - url: https://github.com/yezz123 -- login: iudeen - count: 55 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 - url: https://github.com/iudeen -- login: tokusumi - count: 51 - avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 - url: https://github.com/tokusumi -- login: Xewus - count: 50 - avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 - url: https://github.com/Xewus -- login: hasansezertasan - count: 50 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan -- login: waynerv - count: 47 - avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 - url: https://github.com/waynerv -- login: Laineyzhang55 - count: 47 - avatarUrl: https://avatars.githubusercontent.com/u/59285379?v=4 - url: https://github.com/Laineyzhang55 -- login: ycd - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 - url: https://github.com/ycd -- login: cikay - count: 41 - avatarUrl: https://avatars.githubusercontent.com/u/24587499?u=e772190a051ab0eaa9c8542fcff1892471638f2b&v=4 - url: https://github.com/cikay -- login: alejsdev - count: 38 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=9ca449ad5161af12766ddd1a22988e9b14315f5c&v=4 - url: https://github.com/alejsdev -- login: JarroVGIT - count: 34 - avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4 - url: https://github.com/JarroVGIT -- login: AdrianDeAnda - count: 33 - avatarUrl: https://avatars.githubusercontent.com/u/1024932?u=b2ea249c6b41ddf98679c8d110d0f67d4a3ebf93&v=4 - url: https://github.com/AdrianDeAnda -- login: ArcLightSlavik - count: 31 - avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4 - url: https://github.com/ArcLightSlavik -- login: cassiobotaro - count: 28 - avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=a08022b191ddbd0a6159b2981d9d878b6d5bb71f&v=4 - url: https://github.com/cassiobotaro -- login: lsglucas - count: 27 - avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 - url: https://github.com/lsglucas -- login: komtaki - count: 27 - avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 - url: https://github.com/komtaki -- login: YuriiMotov - count: 25 - avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 - url: https://github.com/YuriiMotov -- login: Ryandaydev - count: 25 - avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 - url: https://github.com/Ryandaydev -- login: LorhanSohaky - count: 24 - avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 - url: https://github.com/LorhanSohaky -- login: dmontagu - count: 23 - avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 - url: https://github.com/dmontagu -- login: nilslindemann - count: 23 - avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 - url: https://github.com/nilslindemann -- login: hard-coders - count: 23 - avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 - url: https://github.com/hard-coders -- login: rjNemo - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 - url: https://github.com/rjNemo -- login: odiseo0 - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 - url: https://github.com/odiseo0 -- login: 0417taehyun - count: 19 - avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4 - url: https://github.com/0417taehyun -- login: JavierSanchezCastro - count: 19 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro -- login: Smlep - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4 - url: https://github.com/Smlep -- login: zy7y - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/67154681?u=5d634834cc514028ea3f9115f7030b99a1f4d5a4&v=4 - url: https://github.com/zy7y -- login: junah201 - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/75025529?u=2451c256e888fa2a06bcfc0646d09b87ddb6a945&v=4 - url: https://github.com/junah201 -- login: peidrao - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/32584628?u=a66902b40c13647d0ed0e573d598128240a4dd04&v=4 - url: https://github.com/peidrao -- login: yanever - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/21978760?v=4 - url: https://github.com/yanever -- login: SwftAlpc - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 - url: https://github.com/SwftAlpc -- login: axel584 - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 - url: https://github.com/axel584 -- login: codespearhead - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/72931357?u=0fce6b82219b604d58adb614a761556425579cb5&v=4 - url: https://github.com/codespearhead -- login: Alexandrhub - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 - url: https://github.com/Alexandrhub -- login: DevDae - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/87962045?u=08e10fa516e844934f4b3fc7c38b33c61697e4a1&v=4 - url: https://github.com/DevDae -- login: Aruelius - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/25380989?u=574f8cfcda3ea77a3f81884f6b26a97068e36a9d&v=4 - url: https://github.com/Aruelius -- login: OzgunCaglarArslan - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/86166426?v=4 - url: https://github.com/OzgunCaglarArslan -- login: pedabraham - count: 15 - avatarUrl: https://avatars.githubusercontent.com/u/16860088?u=abf922a7b920bf8fdb7867d8b43e091f1e796178&v=4 - url: https://github.com/pedabraham -- login: delhi09 - count: 15 - avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4 - url: https://github.com/delhi09 -- login: wdh99 - count: 14 - avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 - url: https://github.com/wdh99 -- login: sh0nk - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 - url: https://github.com/sh0nk -- login: r0b2g1t - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/5357541?u=6428442d875d5d71aaa1bb38bb11c4be1a526bc2&v=4 - url: https://github.com/r0b2g1t -- login: RunningIkkyu - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4 - url: https://github.com/RunningIkkyu -- login: ivan-abc - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 - url: https://github.com/ivan-abc -- login: AlertRED - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 - url: https://github.com/AlertRED -- login: solomein-sv - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=789927ee09cfabd752d3bd554fa6baf4850d2777&v=4 - url: https://github.com/solomein-sv -top_translations_reviewers: -- login: s111d - count: 146 - avatarUrl: https://avatars.githubusercontent.com/u/4954856?v=4 - url: https://github.com/s111d -- login: Xewus - count: 128 - avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 - url: https://github.com/Xewus -- login: tokusumi - count: 104 - avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 - url: https://github.com/tokusumi -- login: hasansezertasan - count: 91 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan -- login: AlertRED - count: 70 - avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 - url: https://github.com/AlertRED -- login: Alexandrhub - count: 68 - avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 - url: https://github.com/Alexandrhub -- login: waynerv - count: 63 - avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 - url: https://github.com/waynerv -- login: hard-coders - count: 53 - avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 - url: https://github.com/hard-coders -- login: Laineyzhang55 - count: 48 - avatarUrl: https://avatars.githubusercontent.com/u/59285379?v=4 - url: https://github.com/Laineyzhang55 -- login: Kludex - count: 46 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 - url: https://github.com/Kludex -- login: komtaki - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 - url: https://github.com/komtaki -- login: alperiox - count: 42 - avatarUrl: https://avatars.githubusercontent.com/u/34214152?u=2c5acad3461d4dbc2d48371ba86cac56ae9b25cc&v=4 - url: https://github.com/alperiox -- login: Winand - count: 40 - avatarUrl: https://avatars.githubusercontent.com/u/53390?u=bb0e71a2fc3910a8e0ee66da67c33de40ea695f8&v=4 - url: https://github.com/Winand -- login: solomein-sv - count: 38 - avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=789927ee09cfabd752d3bd554fa6baf4850d2777&v=4 - url: https://github.com/solomein-sv -- login: lsglucas - count: 36 - avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 - url: https://github.com/lsglucas -- login: SwftAlpc - count: 36 - avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 - url: https://github.com/SwftAlpc -- login: nilslindemann - count: 35 - avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 - url: https://github.com/nilslindemann -- login: rjNemo - count: 34 - avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 - url: https://github.com/rjNemo -- login: akarev0 - count: 33 - avatarUrl: https://avatars.githubusercontent.com/u/53393089?u=6e528bb4789d56af887ce6fe237bea4010885406&v=4 - url: https://github.com/akarev0 -- login: romashevchenko - count: 32 - avatarUrl: https://avatars.githubusercontent.com/u/132477732?v=4 - url: https://github.com/romashevchenko -- login: wdh99 - count: 31 - avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 - url: https://github.com/wdh99 -- login: LorhanSohaky - count: 30 - avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 - url: https://github.com/LorhanSohaky -- login: cassiobotaro - count: 29 - avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=a08022b191ddbd0a6159b2981d9d878b6d5bb71f&v=4 - url: https://github.com/cassiobotaro -- login: pedabraham - count: 28 - avatarUrl: https://avatars.githubusercontent.com/u/16860088?u=abf922a7b920bf8fdb7867d8b43e091f1e796178&v=4 - url: https://github.com/pedabraham -- login: Smlep - count: 28 - avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4 - url: https://github.com/Smlep -- login: dedkot01 - count: 28 - avatarUrl: https://avatars.githubusercontent.com/u/26196675?u=e2966887124e67932853df4f10f86cb526edc7b0&v=4 - url: https://github.com/dedkot01 -- login: hsuanchi - count: 28 - avatarUrl: https://avatars.githubusercontent.com/u/24913710?u=0b094ae292292fee093818e37ceb645c114d2bff&v=4 - url: https://github.com/hsuanchi -- login: dpinezich - count: 28 - avatarUrl: https://avatars.githubusercontent.com/u/3204540?u=a2e1465e3ee10d537614d513589607eddefde09f&v=4 - url: https://github.com/dpinezich -- login: maoyibo - count: 27 - avatarUrl: https://avatars.githubusercontent.com/u/7887703?v=4 - url: https://github.com/maoyibo -- login: 0417taehyun - count: 27 - avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4 - url: https://github.com/0417taehyun -- login: BilalAlpaslan - count: 26 - avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 - url: https://github.com/BilalAlpaslan -- login: zy7y - count: 25 - avatarUrl: https://avatars.githubusercontent.com/u/67154681?u=5d634834cc514028ea3f9115f7030b99a1f4d5a4&v=4 - url: https://github.com/zy7y -- login: mycaule - count: 25 - avatarUrl: https://avatars.githubusercontent.com/u/6161385?u=e3cec75bd6d938a0d73fae0dc5534d1ab2ed1b0e&v=4 - url: https://github.com/mycaule -- login: sh0nk - count: 23 - avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 - url: https://github.com/sh0nk -- login: axel584 - count: 23 - avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 - url: https://github.com/axel584 -- login: AGolicyn - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/86262613?u=3c21606ab8d210a061a1673decff1e7d5592b380&v=4 - url: https://github.com/AGolicyn -- login: OzgunCaglarArslan - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/86166426?v=4 - url: https://github.com/OzgunCaglarArslan -- login: Attsun1031 - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/1175560?v=4 - url: https://github.com/Attsun1031 -- login: ycd - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 - url: https://github.com/ycd -- login: delhi09 - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4 - url: https://github.com/delhi09 -- login: rogerbrinkmann - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/5690226?v=4 - url: https://github.com/rogerbrinkmann -- login: DevDae - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/87962045?u=08e10fa516e844934f4b3fc7c38b33c61697e4a1&v=4 - url: https://github.com/DevDae -- login: sattosan - count: 19 - avatarUrl: https://avatars.githubusercontent.com/u/20574756?u=b0d8474d2938189c6954423ae8d81d91013f80a8&v=4 - url: https://github.com/sattosan -- login: ComicShrimp - count: 18 - avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=d2fbf412e7730183ce91686ca48d4147e1b7dc74&v=4 - url: https://github.com/ComicShrimp -- login: junah201 - count: 18 - avatarUrl: https://avatars.githubusercontent.com/u/75025529?u=2451c256e888fa2a06bcfc0646d09b87ddb6a945&v=4 - url: https://github.com/junah201 -- login: simatheone - count: 18 - avatarUrl: https://avatars.githubusercontent.com/u/78508673?u=1b9658d9ee0bde33f56130dd52275493ddd38690&v=4 - url: https://github.com/simatheone -- login: ivan-abc - count: 18 - avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 - url: https://github.com/ivan-abc -- login: JavierSanchezCastro - count: 18 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro -- login: bezaca - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/69092910?u=4ac58eab99bd37d663f3d23551df96d4fbdbf760&v=4 - url: https://github.com/bezaca + avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=d87b866e7c1db970d6f8e8031643818349b046d5&v=4 + url: https://github.com/ahmedabdou14 +- login: nbx3 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/34649527?u=943812f69e0d40adbd3fa1c9b8ef50dd971a2a45&v=4 + url: https://github.com/nbx3 +- login: yanggeorge + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/2434407?v=4 + url: https://github.com/yanggeorge +- login: XiaoXinYo + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=b3b7cb758997f283c271a581833e407229dab82c&v=4 + url: https://github.com/XiaoXinYo +- login: anantgupta129 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/66518357?u=6e25dcd84638f17d2c6df5dc26f07fd7c6dc118e&v=4 + url: https://github.com/anantgupta129 +- login: slafs + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4 + url: https://github.com/slafs +- login: CarlosOliveira-23 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/102637302?u=cf350a4db956f30cbb2c27d3be0d15c282e32b14&v=4 + url: https://github.com/CarlosOliveira-23 +- login: monchin + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/18521800?v=4 + url: https://github.com/monchin +- login: AmirHmZz + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/38752106?u=07f80e451bda00a9492bbc764e49d24ad3ada8cc&v=4 + url: https://github.com/AmirHmZz +- login: Leon0824 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1922026?v=4 + url: https://github.com/Leon0824 +- login: iloveitaly + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/150855?v=4 + url: https://github.com/iloveitaly +- login: msukmanowsky + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/362755?u=782e6bf5b9f0356c3f74b4d894fda9f179252086&v=4 + url: https://github.com/msukmanowsky +- login: shurshilov + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/11828278?u=6bcadc5ce4f2f56a514331c9f68eb987d4afe29a&v=4 + url: https://github.com/shurshilov +- login: LincolnPuzey + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/18750802?v=4 + url: https://github.com/LincolnPuzey From 8525b879edfd85c1739e513139aab7120b780044 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 28 Jan 2025 20:41:36 +0000 Subject: [PATCH 735/932] =?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 [skip ci] --- 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 3db7042fb..20f800d85 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 👥 Update FastAPI People - Experts. PR [#13269](https://github.com/fastapi/fastapi/pull/13269) by [@tiangolo](https://github.com/tiangolo). + ### Translations * 🌐 Add Japanese translation for `docs/ja/docs/environment-variables.md`. PR [#13226](https://github.com/fastapi/fastapi/pull/13226) by [@k94-ishi](https://github.com/k94-ishi). From 326fec16b9e3d61c584182b212436f88d81d0acb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 28 Jan 2025 21:47:33 +0000 Subject: [PATCH 736/932] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Refactor=20and=20m?= =?UTF-8?q?ove=20`scripts/notify=5Ftranslations.py`,=20no=20need=20for=20a?= =?UTF-8?q?=20custom=20GitHub=20Action=20(#13270)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../actions/notify-translations/Dockerfile | 7 --- .../actions/notify-translations/action.yml | 10 --- .github/workflows/notify-translations.yml | 20 +++--- .../main.py => scripts/notify_translations.py | 63 +++++++++++-------- 4 files changed, 51 insertions(+), 49 deletions(-) delete mode 100644 .github/actions/notify-translations/Dockerfile delete mode 100644 .github/actions/notify-translations/action.yml rename .github/actions/notify-translations/app/main.py => scripts/notify_translations.py (89%) diff --git a/.github/actions/notify-translations/Dockerfile b/.github/actions/notify-translations/Dockerfile deleted file mode 100644 index b68b4bb1a..000000000 --- a/.github/actions/notify-translations/Dockerfile +++ /dev/null @@ -1,7 +0,0 @@ -FROM python:3.9 - -RUN pip install httpx PyGithub "pydantic==1.5.1" "pyyaml>=5.3.1,<6.0.0" - -COPY ./app /app - -CMD ["python", "/app/main.py"] diff --git a/.github/actions/notify-translations/action.yml b/.github/actions/notify-translations/action.yml deleted file mode 100644 index c3579977c..000000000 --- a/.github/actions/notify-translations/action.yml +++ /dev/null @@ -1,10 +0,0 @@ -name: "Notify Translations" -description: "Notify in the issue for a translation when there's a new PR available" -author: "Sebastián Ramírez " -inputs: - token: - description: 'Token, to read the GitHub API. Can be passed in using {{ secrets.GITHUB_TOKEN }}' - required: true -runs: - using: 'docker' - image: 'Dockerfile' diff --git a/.github/workflows/notify-translations.yml b/.github/workflows/notify-translations.yml index 187322bca..c96992689 100644 --- a/.github/workflows/notify-translations.yml +++ b/.github/workflows/notify-translations.yml @@ -15,15 +15,14 @@ on: required: false default: 'false' -permissions: - discussions: write - env: UV_SYSTEM_PYTHON: 1 jobs: - notify-translations: + job: runs-on: ubuntu-latest + permissions: + discussions: write steps: - name: Dump GitHub context env: @@ -42,12 +41,19 @@ jobs: cache-dependency-glob: | requirements**.txt pyproject.toml + - name: Install Dependencies + run: uv pip install -r requirements-github-actions.txt # Allow debugging with tmate - name: Setup tmate session uses: mxschmitt/action-tmate@v3 if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - - uses: ./.github/actions/notify-translations - with: - token: ${{ secrets.GITHUB_TOKEN }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Notify Translations + run: python ./scripts/notify_translations.py + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + NUMBER: ${{ github.event.inputs.number || null }} + DEBUG: ${{ github.event.inputs.debug_enabled || 'false' }} diff --git a/.github/actions/notify-translations/app/main.py b/scripts/notify_translations.py similarity index 89% rename from .github/actions/notify-translations/app/main.py rename to scripts/notify_translations.py index 716232d49..7a43019a6 100644 --- a/.github/actions/notify-translations/app/main.py +++ b/scripts/notify_translations.py @@ -7,12 +7,13 @@ from typing import Any, Dict, List, Union, cast import httpx from github import Github -from pydantic import BaseModel, BaseSettings, SecretStr +from pydantic import BaseModel, SecretStr +from pydantic_settings import BaseSettings awaiting_label = "awaiting-review" lang_all_label = "lang-all" approved_label = "approved-1" -translations_path = Path(__file__).parent / "translations.yml" + github_graphql_url = "https://api.github.com/graphql" questions_translations_category_id = "DIC_kwDOCZduT84CT5P9" @@ -176,19 +177,20 @@ class AllDiscussionsResponse(BaseModel): class Settings(BaseSettings): github_repository: str - input_token: SecretStr + github_token: SecretStr github_event_path: Path github_event_name: Union[str, None] = None httpx_timeout: int = 30 - input_debug: Union[bool, None] = False + debug: Union[bool, None] = False + number: int | None = None class PartialGitHubEventIssue(BaseModel): - number: int + number: int | None = None class PartialGitHubEvent(BaseModel): - pull_request: PartialGitHubEventIssue + pull_request: PartialGitHubEventIssue | None = None def get_graphql_response( @@ -202,9 +204,7 @@ def get_graphql_response( comment_id: Union[str, None] = None, body: Union[str, None] = None, ) -> Dict[str, Any]: - headers = {"Authorization": f"token {settings.input_token.get_secret_value()}"} - # some fields are only used by one query, but GraphQL allows unused variables, so - # keep them here for simplicity + headers = {"Authorization": f"token {settings.github_token.get_secret_value()}"} variables = { "after": after, "category_id": category_id, @@ -228,37 +228,40 @@ def get_graphql_response( data = response.json() if "errors" in data: logging.error(f"Errors in response, after: {after}, category_id: {category_id}") + logging.error(data["errors"]) logging.error(response.text) raise RuntimeError(response.text) return cast(Dict[str, Any], data) -def get_graphql_translation_discussions(*, settings: Settings): +def get_graphql_translation_discussions( + *, settings: Settings +) -> List[AllDiscussionsDiscussionNode]: data = get_graphql_response( settings=settings, query=all_discussions_query, category_id=questions_translations_category_id, ) - graphql_response = AllDiscussionsResponse.parse_obj(data) + graphql_response = AllDiscussionsResponse.model_validate(data) return graphql_response.data.repository.discussions.nodes def get_graphql_translation_discussion_comments_edges( *, settings: Settings, discussion_number: int, after: Union[str, None] = None -): +) -> List[CommentsEdge]: data = get_graphql_response( settings=settings, query=translation_discussion_query, discussion_number=discussion_number, after=after, ) - graphql_response = CommentsResponse.parse_obj(data) + graphql_response = CommentsResponse.model_validate(data) return graphql_response.data.repository.discussion.comments.edges def get_graphql_translation_discussion_comments( *, settings: Settings, discussion_number: int -): +) -> list[Comment]: comment_nodes: List[Comment] = [] discussion_edges = get_graphql_translation_discussion_comments_edges( settings=settings, discussion_number=discussion_number @@ -276,43 +279,49 @@ def get_graphql_translation_discussion_comments( return comment_nodes -def create_comment(*, settings: Settings, discussion_id: str, body: str): +def create_comment(*, settings: Settings, discussion_id: str, body: str) -> Comment: data = get_graphql_response( settings=settings, query=add_comment_mutation, discussion_id=discussion_id, body=body, ) - response = AddCommentResponse.parse_obj(data) + response = AddCommentResponse.model_validate(data) return response.data.addDiscussionComment.comment -def update_comment(*, settings: Settings, comment_id: str, body: str): +def update_comment(*, settings: Settings, comment_id: str, body: str) -> Comment: data = get_graphql_response( settings=settings, query=update_comment_mutation, comment_id=comment_id, body=body, ) - response = UpdateCommentResponse.parse_obj(data) + response = UpdateCommentResponse.model_validate(data) return response.data.updateDiscussionComment.comment -if __name__ == "__main__": +def main() -> None: settings = Settings() - if settings.input_debug: + if settings.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) - logging.debug(f"Using config: {settings.json()}") - g = Github(settings.input_token.get_secret_value()) + logging.debug(f"Using config: {settings.model_dump_json()}") + g = Github(settings.github_token.get_secret_value()) repo = g.get_repo(settings.github_repository) if not settings.github_event_path.is_file(): raise RuntimeError( f"No github event file available at: {settings.github_event_path}" ) contents = settings.github_event_path.read_text() - github_event = PartialGitHubEvent.parse_raw(contents) + github_event = PartialGitHubEvent.model_validate_json(contents) + logging.info(f"Using GitHub event: {github_event}") + number = ( + github_event.pull_request and github_event.pull_request.number + ) or settings.number + if number is None: + raise RuntimeError("No PR number available") # Avoid race conditions with multiple labels sleep_time = random.random() * 10 # random number between 0 and 10 seconds @@ -323,8 +332,8 @@ if __name__ == "__main__": time.sleep(sleep_time) # Get PR - logging.debug(f"Processing PR: #{github_event.pull_request.number}") - pr = repo.get_pull(github_event.pull_request.number) + logging.debug(f"Processing PR: #{number}") + pr = repo.get_pull(number) label_strs = {label.name for label in pr.get_labels()} langs = [] for label in label_strs: @@ -415,3 +424,7 @@ if __name__ == "__main__": f"There doesn't seem to be anything to be done about PR #{pr.number}" ) logging.info("Finished") + + +if __name__ == "__main__": + main() From a058d8ecbc41b329bad2f5ca0575c50b7bc171b2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 28 Jan 2025 21:47:55 +0000 Subject: [PATCH 737/932] =?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 [skip ci] --- 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 20f800d85..2abee78dc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -20,6 +20,7 @@ hide: ### Internal +* ♻️ Refactor and move `scripts/notify_translations.py`, no need for a custom GitHub Action. PR [#13270](https://github.com/fastapi/fastapi/pull/13270) by [@tiangolo](https://github.com/tiangolo). * 🔨 Update FastAPI People Experts script, refactor and optimize data fetching to handle rate limits. PR [#13267](https://github.com/fastapi/fastapi/pull/13267) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump pypa/gh-action-pypi-publish from 1.12.3 to 1.12.4. PR [#13251](https://github.com/fastapi/fastapi/pull/13251) by [@dependabot[bot]](https://github.com/apps/dependabot). From 0a2b24653b2b0e2a4753a1e239013b26fa1516b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 28 Jan 2025 22:30:15 +0000 Subject: [PATCH 738/932] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Fix=20`notify=5Ftr?= =?UTF-8?q?anslations.py`=20empty=20env=20var=20handling=20for=20PR=20labe?= =?UTF-8?q?l=20events=20vs=20workflow=5Fdispatch=20(#13272)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/notify_translations.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/notify_translations.py b/scripts/notify_translations.py index 7a43019a6..c300624db 100644 --- a/scripts/notify_translations.py +++ b/scripts/notify_translations.py @@ -176,6 +176,8 @@ class AllDiscussionsResponse(BaseModel): class Settings(BaseSettings): + model_config = {"env_ignore_empty": True} + github_repository: str github_token: SecretStr github_event_path: Path From 92b745461cb280aea3c5905c5e241502207064fa Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 28 Jan 2025 22:30:38 +0000 Subject: [PATCH 739/932] =?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 [skip ci] --- 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 2abee78dc..e65fe9848 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -20,6 +20,7 @@ hide: ### Internal +* ♻️ Fix `notify_translations.py` empty env var handling for PR label events vs workflow_dispatch. PR [#13272](https://github.com/fastapi/fastapi/pull/13272) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and move `scripts/notify_translations.py`, no need for a custom GitHub Action. PR [#13270](https://github.com/fastapi/fastapi/pull/13270) by [@tiangolo](https://github.com/tiangolo). * 🔨 Update FastAPI People Experts script, refactor and optimize data fetching to handle rate limits. PR [#13267](https://github.com/fastapi/fastapi/pull/13267) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump pypa/gh-action-pypi-publish from 1.12.3 to 1.12.4. PR [#13251](https://github.com/fastapi/fastapi/pull/13251) by [@dependabot[bot]](https://github.com/apps/dependabot). From e747f1938a3853c6af695f6447fd8f8749e1ba9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 28 Jan 2025 22:36:15 +0000 Subject: [PATCH 740/932] =?UTF-8?q?=F0=9F=94=A7=20Update=20Sponsors=20badg?= =?UTF-8?q?es=20(#13271)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/sponsors_badge.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/en/data/sponsors_badge.yml b/docs/en/data/sponsors_badge.yml index 3e885a2f7..d507a500f 100644 --- a/docs/en/data/sponsors_badge.yml +++ b/docs/en/data/sponsors_badge.yml @@ -29,7 +29,12 @@ logins: - andrew-propelauth - svix - zuplo-oss + - zuplo - Kong - speakeasy-api - jess-render - blockbee-io + - liblaber + - render-sponsorships + - renderinc + - stainless-api From 93e9fed2e84554197a0b480104a9e3c5b8897545 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 28 Jan 2025 22:36:38 +0000 Subject: [PATCH 741/932] =?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 [skip ci] --- 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 e65fe9848..c0cb88e21 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -20,6 +20,7 @@ hide: ### Internal +* 🔧 Update Sponsors badges. PR [#13271](https://github.com/fastapi/fastapi/pull/13271) by [@tiangolo](https://github.com/tiangolo). * ♻️ Fix `notify_translations.py` empty env var handling for PR label events vs workflow_dispatch. PR [#13272](https://github.com/fastapi/fastapi/pull/13272) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and move `scripts/notify_translations.py`, no need for a custom GitHub Action. PR [#13270](https://github.com/fastapi/fastapi/pull/13270) by [@tiangolo](https://github.com/tiangolo). * 🔨 Update FastAPI People Experts script, refactor and optimize data fetching to handle rate limits. PR [#13267](https://github.com/fastapi/fastapi/pull/13267) by [@tiangolo](https://github.com/tiangolo). From 8c6f10b64a333cb1395da5cb714fd1aa28e7b5ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 28 Jan 2025 23:35:19 +0000 Subject: [PATCH 742/932] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20AnyIO=20?= =?UTF-8?q?max=20version=20for=20tests,=20new=20range:=20`>=3D3.2.1,<5.0.0?= =?UTF-8?q?`=20(#13273)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/test.yml | 4 ++++ requirements-tests.txt | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e0daf7472..793e789e2 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -81,6 +81,10 @@ jobs: - name: Install Pydantic v2 if: matrix.pydantic-version == 'pydantic-v2' run: uv pip install --upgrade "pydantic>=2.0.2,<3.0.0" + # TODO: Remove this once Python 3.8 is no longer supported + - name: Install older AnyIO in Python 3.8 + if: matrix.python-version == '3.8' + run: uv pip install "anyio[trio]<4.0.0" - run: mkdir coverage - name: Test run: bash scripts/test.sh diff --git a/requirements-tests.txt b/requirements-tests.txt index 5be052307..91e7fb7aa 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -6,7 +6,7 @@ mypy ==1.8.0 dirty-equals ==0.8.0 sqlmodel==0.0.22 flask >=1.1.2,<4.0.0 -anyio[trio] >=3.2.1,<4.0.0 +anyio[trio] >=3.2.1,<5.0.0 PyJWT==2.8.0 pyyaml >=5.3.1,<7.0.0 passlib[bcrypt] >=1.7.2,<2.0.0 From eab0653a346196bff6928710410890a300aee4ae Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 28 Jan 2025 23:35:44 +0000 Subject: [PATCH 743/932] =?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 [skip ci] --- 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 c0cb88e21..ad8b85d0e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -20,6 +20,7 @@ hide: ### Internal +* ⬆️ Upgrade AnyIO max version for tests, new range: `>=3.2.1,<5.0.0`. PR [#13273](https://github.com/fastapi/fastapi/pull/13273) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update Sponsors badges. PR [#13271](https://github.com/fastapi/fastapi/pull/13271) by [@tiangolo](https://github.com/tiangolo). * ♻️ Fix `notify_translations.py` empty env var handling for PR label events vs workflow_dispatch. PR [#13272](https://github.com/fastapi/fastapi/pull/13272) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and move `scripts/notify_translations.py`, no need for a custom GitHub Action. PR [#13270](https://github.com/fastapi/fastapi/pull/13270) by [@tiangolo](https://github.com/tiangolo). From bd106fc750fb0d4b114b69e1f1f9ae5dabaada44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 29 Jan 2025 18:02:27 +0000 Subject: [PATCH 744/932] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Add=20support=20fo?= =?UTF-8?q?r=20Python=203.13=20(#13274)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .github/workflows/test.yml | 1 + pyproject.toml | 3 +++ 2 files changed, 4 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 793e789e2..5e8092641 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -48,6 +48,7 @@ jobs: strategy: matrix: python-version: + - "3.13" - "3.12" - "3.11" - "3.10" diff --git a/pyproject.toml b/pyproject.toml index 381eb50bf..51d63fd44 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,6 +38,7 @@ classifiers = [ "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", "Topic :: Internet :: WWW/HTTP :: HTTP Servers", "Topic :: Internet :: WWW/HTTP", ] @@ -162,6 +163,8 @@ filterwarnings = [ # Ref: https://github.com/python-trio/trio/pull/3054 # Remove once there's a new version of Trio 'ignore:The `hash` argument is deprecated*:DeprecationWarning:trio', + # Ignore flaky coverage / pytest warning about SQLite connection, only applies to Python 3.13 and Pydantic v1 + 'ignore:Exception ignored in. Date: Wed, 29 Jan 2025 18:02:50 +0000 Subject: [PATCH 745/932] =?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 [skip ci] --- 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 ad8b85d0e..e21d2521f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -20,6 +20,7 @@ hide: ### Internal +* ⬆️ Add support for Python 3.13. PR [#13274](https://github.com/fastapi/fastapi/pull/13274) by [@tiangolo](https://github.com/tiangolo). * ⬆️ Upgrade AnyIO max version for tests, new range: `>=3.2.1,<5.0.0`. PR [#13273](https://github.com/fastapi/fastapi/pull/13273) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update Sponsors badges. PR [#13271](https://github.com/fastapi/fastapi/pull/13271) by [@tiangolo](https://github.com/tiangolo). * ♻️ Fix `notify_translations.py` empty env var handling for PR label events vs workflow_dispatch. PR [#13272](https://github.com/fastapi/fastapi/pull/13272) by [@tiangolo](https://github.com/tiangolo). From c5b5af7c532e66d3ac25bd36630e2cd89f24d049 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Thu, 30 Jan 2025 12:04:34 +0000 Subject: [PATCH 746/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20re?= =?UTF-8?q?quest=5Ffiles=20(#13182)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .../test_tutorial003.py | 21 +- .../test_tutorial003_an.py | 273 ----------------- .../test_tutorial003_an_py310.py | 279 ------------------ .../test_tutorial003_an_py39.py | 279 ------------------ .../test_tutorial003_py310.py | 279 ------------------ .../test_request_files/test_tutorial001.py | 42 +-- .../test_request_files/test_tutorial001_02.py | 35 ++- .../test_tutorial001_02_an.py | 208 ------------- .../test_tutorial001_02_an_py310.py | 220 -------------- .../test_tutorial001_02_an_py39.py | 220 -------------- .../test_tutorial001_02_py310.py | 220 -------------- .../test_request_files/test_tutorial001_03.py | 28 +- .../test_tutorial001_03_an.py | 159 ---------- .../test_tutorial001_03_an_py39.py | 167 ----------- .../test_request_files/test_tutorial001_an.py | 218 -------------- .../test_tutorial001_an_py39.py | 228 -------------- .../test_request_files/test_tutorial002.py | 39 ++- .../test_request_files/test_tutorial002_an.py | 249 ---------------- .../test_tutorial002_an_py39.py | 268 ----------------- .../test_tutorial002_py39.py | 279 ------------------ .../test_request_files/test_tutorial003.py | 35 ++- .../test_request_files/test_tutorial003_an.py | 194 ------------ .../test_tutorial003_an_py39.py | 222 -------------- .../test_tutorial003_py39.py | 222 -------------- 24 files changed, 146 insertions(+), 4238 deletions(-) delete mode 100644 tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py delete mode 100644 tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py delete mode 100644 tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py delete mode 100644 tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py delete mode 100644 tests/test_tutorial/test_request_files/test_tutorial001_02_an.py delete mode 100644 tests/test_tutorial/test_request_files/test_tutorial001_02_an_py310.py delete mode 100644 tests/test_tutorial/test_request_files/test_tutorial001_02_an_py39.py delete mode 100644 tests/test_tutorial/test_request_files/test_tutorial001_02_py310.py delete mode 100644 tests/test_tutorial/test_request_files/test_tutorial001_03_an.py delete mode 100644 tests/test_tutorial/test_request_files/test_tutorial001_03_an_py39.py delete mode 100644 tests/test_tutorial/test_request_files/test_tutorial001_an.py delete mode 100644 tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py delete mode 100644 tests/test_tutorial/test_request_files/test_tutorial002_an.py delete mode 100644 tests/test_tutorial/test_request_files/test_tutorial002_an_py39.py delete mode 100644 tests/test_tutorial/test_request_files/test_tutorial002_py39.py delete mode 100644 tests/test_tutorial/test_request_files/test_tutorial003_an.py delete mode 100644 tests/test_tutorial/test_request_files/test_tutorial003_an_py39.py delete mode 100644 tests/test_tutorial/test_request_files/test_tutorial003_py39.py diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py index c26f8b89b..d18ceae48 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py @@ -1,13 +1,26 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient +from ...utils import needs_py39, needs_py310 + -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial003 import app +@pytest.fixture( + name="client", + params=[ + "tutorial003", + pytest.param("tutorial003_py310", marks=needs_py310), + "tutorial003_an", + pytest.param("tutorial003_an_py39", marks=needs_py39), + pytest.param("tutorial003_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.body_multiple_params.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py deleted file mode 100644 index 62c7e2fad..000000000 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py +++ /dev/null @@ -1,273 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial003_an import app - - client = TestClient(app) - return client - - -def test_post_body_valid(client: TestClient): - response = client.put( - "/items/5", - json={ - "importance": 2, - "item": {"name": "Foo", "price": 50.5}, - "user": {"username": "Dave"}, - }, - ) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "importance": 2, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "user": {"username": "Dave", "full_name": None}, - } - - -def test_post_body_no_data(client: TestClient): - response = client.put("/items/5", json=None) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "item"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "user"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "importance"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_post_body_empty_list(client: TestClient): - response = client.put("/items/5", json=[]) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "item"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "user"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "importance"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_update_item_items__item_id__put" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "User": { - "title": "User", - "required": ["username"], - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - }, - }, - "Body_update_item_items__item_id__put": { - "title": "Body_update_item_items__item_id__put", - "required": ["item", "user", "importance"], - "type": "object", - "properties": { - "item": {"$ref": "#/components/schemas/Item"}, - "user": {"$ref": "#/components/schemas/User"}, - "importance": {"title": "Importance", "type": "integer"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py deleted file mode 100644 index f46430fb5..000000000 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py +++ /dev/null @@ -1,279 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial003_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_body_valid(client: TestClient): - response = client.put( - "/items/5", - json={ - "importance": 2, - "item": {"name": "Foo", "price": 50.5}, - "user": {"username": "Dave"}, - }, - ) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "importance": 2, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "user": {"username": "Dave", "full_name": None}, - } - - -@needs_py310 -def test_post_body_no_data(client: TestClient): - response = client.put("/items/5", json=None) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "item"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "user"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "importance"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py310 -def test_post_body_empty_list(client: TestClient): - response = client.put("/items/5", json=[]) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "item"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "user"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "importance"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_update_item_items__item_id__put" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "User": { - "title": "User", - "required": ["username"], - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - }, - }, - "Body_update_item_items__item_id__put": { - "title": "Body_update_item_items__item_id__put", - "required": ["item", "user", "importance"], - "type": "object", - "properties": { - "item": {"$ref": "#/components/schemas/Item"}, - "user": {"$ref": "#/components/schemas/User"}, - "importance": {"title": "Importance", "type": "integer"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py deleted file mode 100644 index 29071cddc..000000000 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py +++ /dev/null @@ -1,279 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial003_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_body_valid(client: TestClient): - response = client.put( - "/items/5", - json={ - "importance": 2, - "item": {"name": "Foo", "price": 50.5}, - "user": {"username": "Dave"}, - }, - ) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "importance": 2, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "user": {"username": "Dave", "full_name": None}, - } - - -@needs_py39 -def test_post_body_no_data(client: TestClient): - response = client.put("/items/5", json=None) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "item"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "user"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "importance"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_post_body_empty_list(client: TestClient): - response = client.put("/items/5", json=[]) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "item"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "user"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "importance"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_update_item_items__item_id__put" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "User": { - "title": "User", - "required": ["username"], - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - }, - }, - "Body_update_item_items__item_id__put": { - "title": "Body_update_item_items__item_id__put", - "required": ["item", "user", "importance"], - "type": "object", - "properties": { - "item": {"$ref": "#/components/schemas/Item"}, - "user": {"$ref": "#/components/schemas/User"}, - "importance": {"title": "Importance", "type": "integer"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py deleted file mode 100644 index 133afe9b5..000000000 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py +++ /dev/null @@ -1,279 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial003_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_body_valid(client: TestClient): - response = client.put( - "/items/5", - json={ - "importance": 2, - "item": {"name": "Foo", "price": 50.5}, - "user": {"username": "Dave"}, - }, - ) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "importance": 2, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "user": {"username": "Dave", "full_name": None}, - } - - -@needs_py310 -def test_post_body_no_data(client: TestClient): - response = client.put("/items/5", json=None) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "item"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "user"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "importance"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py310 -def test_post_body_empty_list(client: TestClient): - response = client.put("/items/5", json=[]) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "item"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "user"], - "msg": "Field required", - "input": None, - }, - { - "type": "missing", - "loc": ["body", "importance"], - "msg": "Field required", - "input": None, - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_update_item_items__item_id__put" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "User": { - "title": "User", - "required": ["username"], - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - }, - }, - "Body_update_item_items__item_id__put": { - "title": "Body_update_item_items__item_id__put", - "required": ["item", "user", "importance"], - "type": "object", - "properties": { - "item": {"$ref": "#/components/schemas/Item"}, - "user": {"$ref": "#/components/schemas/User"}, - "importance": {"title": "Importance", "type": "integer"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001.py b/tests/test_tutorial/test_request_files/test_tutorial001.py index f5817593b..b06919961 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001.py @@ -1,23 +1,28 @@ +import importlib + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.request_files.tutorial001 import app +from ...utils import needs_py39 -client = TestClient(app) +@pytest.fixture( + name="client", + params=[ + "tutorial001", + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.request_files.{request.param}") -file_required = { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - } - ] -} + client = TestClient(mod.app) + return client -def test_post_form_no_body(): +def test_post_form_no_body(client: TestClient): response = client.post("/files/") assert response.status_code == 422, response.text assert response.json() == IsDict( @@ -45,7 +50,7 @@ def test_post_form_no_body(): ) -def test_post_body_json(): +def test_post_body_json(client: TestClient): response = client.post("/files/", json={"file": "Foo"}) assert response.status_code == 422, response.text assert response.json() == IsDict( @@ -73,41 +78,38 @@ def test_post_body_json(): ) -def test_post_file(tmp_path): +def test_post_file(tmp_path, client: TestClient): path = tmp_path / "test.txt" path.write_bytes(b"") - client = TestClient(app) with path.open("rb") as file: response = client.post("/files/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"file_size": 14} -def test_post_large_file(tmp_path): +def test_post_large_file(tmp_path, client: TestClient): default_pydantic_max_size = 2**16 path = tmp_path / "test.txt" path.write_bytes(b"x" * (default_pydantic_max_size + 1)) - client = TestClient(app) with path.open("rb") as file: response = client.post("/files/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"file_size": default_pydantic_max_size + 1} -def test_post_upload_file(tmp_path): +def test_post_upload_file(tmp_path, client: TestClient): path = tmp_path / "test.txt" path.write_bytes(b"") - client = TestClient(app) with path.open("rb") as file: response = client.post("/uploadfile/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"filename": "test.txt"} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_02.py b/tests/test_tutorial/test_request_files/test_tutorial001_02.py index 42f75442a..9075a1756 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001_02.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001_02.py @@ -1,46 +1,63 @@ +import importlib +from pathlib import Path + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.request_files.tutorial001_02 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001_02", + pytest.param("tutorial001_02_py310", marks=needs_py310), + "tutorial001_02_an", + pytest.param("tutorial001_02_an_py39", marks=needs_py39), + pytest.param("tutorial001_02_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.request_files.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_post_form_no_body(): +def test_post_form_no_body(client: TestClient): response = client.post("/files/") assert response.status_code == 200, response.text assert response.json() == {"message": "No file sent"} -def test_post_uploadfile_no_body(): +def test_post_uploadfile_no_body(client: TestClient): response = client.post("/uploadfile/") assert response.status_code == 200, response.text assert response.json() == {"message": "No upload file sent"} -def test_post_file(tmp_path): +def test_post_file(tmp_path: Path, client: TestClient): path = tmp_path / "test.txt" path.write_bytes(b"") - client = TestClient(app) with path.open("rb") as file: response = client.post("/files/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"file_size": 14} -def test_post_upload_file(tmp_path): +def test_post_upload_file(tmp_path: Path, client: TestClient): path = tmp_path / "test.txt" path.write_bytes(b"") - client = TestClient(app) with path.open("rb") as file: response = client.post("/uploadfile/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"filename": "test.txt"} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_02_an.py b/tests/test_tutorial/test_request_files/test_tutorial001_02_an.py deleted file mode 100644 index f63eb339c..000000000 --- a/tests/test_tutorial/test_request_files/test_tutorial001_02_an.py +++ /dev/null @@ -1,208 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.request_files.tutorial001_02_an import app - -client = TestClient(app) - - -def test_post_form_no_body(): - response = client.post("/files/") - assert response.status_code == 200, response.text - assert response.json() == {"message": "No file sent"} - - -def test_post_uploadfile_no_body(): - response = client.post("/uploadfile/") - assert response.status_code == 200, response.text - assert response.json() == {"message": "No upload file sent"} - - -def test_post_file(tmp_path): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": 14} - - -def test_post_upload_file(tmp_path): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file: - response = client.post("/uploadfile/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"filename": "test.txt"} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - ) - } - } - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/uploadfile/": { - "post": { - "summary": "Create Upload File", - "operationId": "create_upload_file_uploadfile__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - ) - } - } - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "type": "object", - "properties": { - "file": IsDict( - { - "title": "File", - "anyOf": [ - {"type": "string", "format": "binary"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "File", "type": "string", "format": "binary"} - ) - }, - }, - "Body_create_upload_file_uploadfile__post": { - "title": "Body_create_upload_file_uploadfile__post", - "type": "object", - "properties": { - "file": IsDict( - { - "title": "File", - "anyOf": [ - {"type": "string", "format": "binary"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "File", "type": "string", "format": "binary"} - ) - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py310.py b/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py310.py deleted file mode 100644 index 94b6ac67e..000000000 --- a/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py310.py +++ /dev/null @@ -1,220 +0,0 @@ -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_files.tutorial001_02_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_form_no_body(client: TestClient): - response = client.post("/files/") - assert response.status_code == 200, response.text - assert response.json() == {"message": "No file sent"} - - -@needs_py310 -def test_post_uploadfile_no_body(client: TestClient): - response = client.post("/uploadfile/") - assert response.status_code == 200, response.text - assert response.json() == {"message": "No upload file sent"} - - -@needs_py310 -def test_post_file(tmp_path: Path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": 14} - - -@needs_py310 -def test_post_upload_file(tmp_path: Path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/uploadfile/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"filename": "test.txt"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - ) - } - } - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/uploadfile/": { - "post": { - "summary": "Create Upload File", - "operationId": "create_upload_file_uploadfile__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - ) - } - } - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "type": "object", - "properties": { - "file": IsDict( - { - "title": "File", - "anyOf": [ - {"type": "string", "format": "binary"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "File", "type": "string", "format": "binary"} - ) - }, - }, - "Body_create_upload_file_uploadfile__post": { - "title": "Body_create_upload_file_uploadfile__post", - "type": "object", - "properties": { - "file": IsDict( - { - "title": "File", - "anyOf": [ - {"type": "string", "format": "binary"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "File", "type": "string", "format": "binary"} - ) - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py39.py b/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py39.py deleted file mode 100644 index fcb39f8f1..000000000 --- a/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py39.py +++ /dev/null @@ -1,220 +0,0 @@ -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_files.tutorial001_02_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_form_no_body(client: TestClient): - response = client.post("/files/") - assert response.status_code == 200, response.text - assert response.json() == {"message": "No file sent"} - - -@needs_py39 -def test_post_uploadfile_no_body(client: TestClient): - response = client.post("/uploadfile/") - assert response.status_code == 200, response.text - assert response.json() == {"message": "No upload file sent"} - - -@needs_py39 -def test_post_file(tmp_path: Path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": 14} - - -@needs_py39 -def test_post_upload_file(tmp_path: Path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/uploadfile/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"filename": "test.txt"} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - ) - } - } - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/uploadfile/": { - "post": { - "summary": "Create Upload File", - "operationId": "create_upload_file_uploadfile__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - ) - } - } - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "type": "object", - "properties": { - "file": IsDict( - { - "title": "File", - "anyOf": [ - {"type": "string", "format": "binary"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "File", "type": "string", "format": "binary"} - ) - }, - }, - "Body_create_upload_file_uploadfile__post": { - "title": "Body_create_upload_file_uploadfile__post", - "type": "object", - "properties": { - "file": IsDict( - { - "title": "File", - "anyOf": [ - {"type": "string", "format": "binary"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "File", "type": "string", "format": "binary"} - ) - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_02_py310.py b/tests/test_tutorial/test_request_files/test_tutorial001_02_py310.py deleted file mode 100644 index a700752a3..000000000 --- a/tests/test_tutorial/test_request_files/test_tutorial001_02_py310.py +++ /dev/null @@ -1,220 +0,0 @@ -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_files.tutorial001_02_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_form_no_body(client: TestClient): - response = client.post("/files/") - assert response.status_code == 200, response.text - assert response.json() == {"message": "No file sent"} - - -@needs_py310 -def test_post_uploadfile_no_body(client: TestClient): - response = client.post("/uploadfile/") - assert response.status_code == 200, response.text - assert response.json() == {"message": "No upload file sent"} - - -@needs_py310 -def test_post_file(tmp_path: Path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": 14} - - -@needs_py310 -def test_post_upload_file(tmp_path: Path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/uploadfile/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"filename": "test.txt"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - ) - } - } - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/uploadfile/": { - "post": { - "summary": "Create Upload File", - "operationId": "create_upload_file_uploadfile__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - ) - } - } - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "type": "object", - "properties": { - "file": IsDict( - { - "title": "File", - "anyOf": [ - {"type": "string", "format": "binary"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "File", "type": "string", "format": "binary"} - ) - }, - }, - "Body_create_upload_file_uploadfile__post": { - "title": "Body_create_upload_file_uploadfile__post", - "type": "object", - "properties": { - "file": IsDict( - { - "title": "File", - "anyOf": [ - {"type": "string", "format": "binary"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "File", "type": "string", "format": "binary"} - ) - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_03.py b/tests/test_tutorial/test_request_files/test_tutorial001_03.py index f02170814..9fbe2166c 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001_03.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001_03.py @@ -1,33 +1,47 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.request_files.tutorial001_03 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001_03", + "tutorial001_03_an", + pytest.param("tutorial001_03_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.request_files.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_post_file(tmp_path): +def test_post_file(tmp_path, client: TestClient): path = tmp_path / "test.txt" path.write_bytes(b"") - client = TestClient(app) with path.open("rb") as file: response = client.post("/files/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"file_size": 14} -def test_post_upload_file(tmp_path): +def test_post_upload_file(tmp_path, client: TestClient): path = tmp_path / "test.txt" path.write_bytes(b"") - client = TestClient(app) with path.open("rb") as file: response = client.post("/uploadfile/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"filename": "test.txt"} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_03_an.py b/tests/test_tutorial/test_request_files/test_tutorial001_03_an.py deleted file mode 100644 index acfb749ce..000000000 --- a/tests/test_tutorial/test_request_files/test_tutorial001_03_an.py +++ /dev/null @@ -1,159 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.request_files.tutorial001_03_an import app - -client = TestClient(app) - - -def test_post_file(tmp_path): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": 14} - - -def test_post_upload_file(tmp_path): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file: - response = client.post("/uploadfile/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"filename": "test.txt"} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/uploadfile/": { - "post": { - "summary": "Create Upload File", - "operationId": "create_upload_file_uploadfile__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "required": ["file"], - "type": "object", - "properties": { - "file": { - "title": "File", - "type": "string", - "description": "A file read as bytes", - "format": "binary", - } - }, - }, - "Body_create_upload_file_uploadfile__post": { - "title": "Body_create_upload_file_uploadfile__post", - "required": ["file"], - "type": "object", - "properties": { - "file": { - "title": "File", - "type": "string", - "description": "A file read as UploadFile", - "format": "binary", - } - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_03_an_py39.py b/tests/test_tutorial/test_request_files/test_tutorial001_03_an_py39.py deleted file mode 100644 index 36e5faac1..000000000 --- a/tests/test_tutorial/test_request_files/test_tutorial001_03_an_py39.py +++ /dev/null @@ -1,167 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_files.tutorial001_03_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_file(tmp_path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": 14} - - -@needs_py39 -def test_post_upload_file(tmp_path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/uploadfile/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"filename": "test.txt"} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/uploadfile/": { - "post": { - "summary": "Create Upload File", - "operationId": "create_upload_file_uploadfile__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "required": ["file"], - "type": "object", - "properties": { - "file": { - "title": "File", - "type": "string", - "description": "A file read as bytes", - "format": "binary", - } - }, - }, - "Body_create_upload_file_uploadfile__post": { - "title": "Body_create_upload_file_uploadfile__post", - "required": ["file"], - "type": "object", - "properties": { - "file": { - "title": "File", - "type": "string", - "description": "A file read as UploadFile", - "format": "binary", - } - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_an.py b/tests/test_tutorial/test_request_files/test_tutorial001_an.py deleted file mode 100644 index 1c78e3679..000000000 --- a/tests/test_tutorial/test_request_files/test_tutorial001_an.py +++ /dev/null @@ -1,218 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.request_files.tutorial001_an import app - -client = TestClient(app) - - -def test_post_form_no_body(): - response = client.post("/files/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "file"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -def test_post_body_json(): - response = client.post("/files/", json={"file": "Foo"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "file"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -def test_post_file(tmp_path): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": 14} - - -def test_post_large_file(tmp_path): - default_pydantic_max_size = 2**16 - path = tmp_path / "test.txt" - path.write_bytes(b"x" * (default_pydantic_max_size + 1)) - - client = TestClient(app) - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": default_pydantic_max_size + 1} - - -def test_post_upload_file(tmp_path): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file: - response = client.post("/uploadfile/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"filename": "test.txt"} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - } - }, - "required": True, - }, - } - }, - "/uploadfile/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Upload File", - "operationId": "create_upload_file_uploadfile__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - } - }, - "required": True, - }, - } - }, - }, - "components": { - "schemas": { - "Body_create_upload_file_uploadfile__post": { - "title": "Body_create_upload_file_uploadfile__post", - "required": ["file"], - "type": "object", - "properties": { - "file": {"title": "File", "type": "string", "format": "binary"} - }, - }, - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "required": ["file"], - "type": "object", - "properties": { - "file": {"title": "File", "type": "string", "format": "binary"} - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py deleted file mode 100644 index 843fcec28..000000000 --- a/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py +++ /dev/null @@ -1,228 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_files.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_form_no_body(client: TestClient): - response = client.post("/files/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "file"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py39 -def test_post_body_json(client: TestClient): - response = client.post("/files/", json={"file": "Foo"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "file"], - "msg": "Field required", - "input": None, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py39 -def test_post_file(tmp_path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": 14} - - -@needs_py39 -def test_post_large_file(tmp_path, client: TestClient): - default_pydantic_max_size = 2**16 - path = tmp_path / "test.txt" - path.write_bytes(b"x" * (default_pydantic_max_size + 1)) - - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": default_pydantic_max_size + 1} - - -@needs_py39 -def test_post_upload_file(tmp_path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/uploadfile/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"filename": "test.txt"} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - } - }, - "required": True, - }, - } - }, - "/uploadfile/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Upload File", - "operationId": "create_upload_file_uploadfile__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - } - }, - "required": True, - }, - } - }, - }, - "components": { - "schemas": { - "Body_create_upload_file_uploadfile__post": { - "title": "Body_create_upload_file_uploadfile__post", - "required": ["file"], - "type": "object", - "properties": { - "file": {"title": "File", "type": "string", "format": "binary"} - }, - }, - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "required": ["file"], - "type": "object", - "properties": { - "file": {"title": "File", "type": "string", "format": "binary"} - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_files/test_tutorial002.py b/tests/test_tutorial/test_request_files/test_tutorial002.py index db1552e5c..446a87657 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial002.py +++ b/tests/test_tutorial/test_request_files/test_tutorial002.py @@ -1,12 +1,35 @@ +import importlib + +import pytest from dirty_equals import IsDict +from fastapi import FastAPI from fastapi.testclient import TestClient -from docs_src.request_files.tutorial002 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="app", + params=[ + "tutorial002", + "tutorial002_an", + pytest.param("tutorial002_py39", marks=needs_py39), + pytest.param("tutorial002_an_py39", marks=needs_py39), + ], +) +def get_app(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.request_files.{request.param}") -client = TestClient(app) + return mod.app + + +@pytest.fixture(name="client") +def get_client(app: FastAPI): + client = TestClient(app) + return client -def test_post_form_no_body(): +def test_post_form_no_body(client: TestClient): response = client.post("/files/") assert response.status_code == 422, response.text assert response.json() == IsDict( @@ -34,7 +57,7 @@ def test_post_form_no_body(): ) -def test_post_body_json(): +def test_post_body_json(client: TestClient): response = client.post("/files/", json={"file": "Foo"}) assert response.status_code == 422, response.text assert response.json() == IsDict( @@ -62,7 +85,7 @@ def test_post_body_json(): ) -def test_post_files(tmp_path): +def test_post_files(tmp_path, app: FastAPI): path = tmp_path / "test.txt" path.write_bytes(b"") path2 = tmp_path / "test2.txt" @@ -81,7 +104,7 @@ def test_post_files(tmp_path): assert response.json() == {"file_sizes": [14, 15]} -def test_post_upload_file(tmp_path): +def test_post_upload_file(tmp_path, app: FastAPI): path = tmp_path / "test.txt" path.write_bytes(b"") path2 = tmp_path / "test2.txt" @@ -100,14 +123,14 @@ def test_post_upload_file(tmp_path): assert response.json() == {"filenames": ["test.txt", "test2.txt"]} -def test_get_root(): +def test_get_root(app: FastAPI): client = TestClient(app) response = client.get("/") assert response.status_code == 200, response.text assert b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/files/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"file_sizes": [14, 15]} - - -def test_post_upload_file(tmp_path): - path = tmp_path / "test.txt" - path.write_bytes(b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/uploadfiles/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"filenames": ["test.txt", "test2.txt"]} - - -def test_get_root(): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/files/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"file_sizes": [14, 15]} - - -@needs_py39 -def test_post_upload_file(tmp_path, app: FastAPI): - path = tmp_path / "test.txt" - path.write_bytes(b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/uploadfiles/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"filenames": ["test.txt", "test2.txt"]} - - -@needs_py39 -def test_get_root(app: FastAPI): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/files/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"file_sizes": [14, 15]} - - -@needs_py39 -def test_post_upload_file(tmp_path, app: FastAPI): - path = tmp_path / "test.txt" - path.write_bytes(b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/uploadfiles/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"filenames": ["test.txt", "test2.txt"]} - - -@needs_py39 -def test_get_root(app: FastAPI): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"") path2 = tmp_path / "test2.txt" @@ -24,7 +47,7 @@ def test_post_files(tmp_path): assert response.json() == {"file_sizes": [14, 15]} -def test_post_upload_file(tmp_path): +def test_post_upload_file(tmp_path, app: FastAPI): path = tmp_path / "test.txt" path.write_bytes(b"") path2 = tmp_path / "test2.txt" @@ -43,14 +66,14 @@ def test_post_upload_file(tmp_path): assert response.json() == {"filenames": ["test.txt", "test2.txt"]} -def test_get_root(): +def test_get_root(app: FastAPI): client = TestClient(app) response = client.get("/") assert response.status_code == 200, response.text assert b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/files/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"file_sizes": [14, 15]} - - -def test_post_upload_file(tmp_path): - path = tmp_path / "test.txt" - path.write_bytes(b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/uploadfiles/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"filenames": ["test.txt", "test2.txt"]} - - -def test_get_root(): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/files/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"file_sizes": [14, 15]} - - -@needs_py39 -def test_post_upload_file(tmp_path, app: FastAPI): - path = tmp_path / "test.txt" - path.write_bytes(b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/uploadfiles/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"filenames": ["test.txt", "test2.txt"]} - - -@needs_py39 -def test_get_root(app: FastAPI): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/files/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"file_sizes": [14, 15]} - - -@needs_py39 -def test_post_upload_file(tmp_path, app: FastAPI): - path = tmp_path / "test.txt" - path.write_bytes(b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/uploadfiles/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"filenames": ["test.txt", "test2.txt"]} - - -@needs_py39 -def test_get_root(app: FastAPI): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b" Date: Thu, 30 Jan 2025 12:04:59 +0000 Subject: [PATCH 747/932] =?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 [skip ci] --- 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 e21d2521f..2f9da1465 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Refactors + +* ✅ Simplify tests for request_files. PR [#13182](https://github.com/fastapi/fastapi/pull/13182) by [@alejsdev](https://github.com/alejsdev). + ### Docs * 👥 Update FastAPI People - Experts. PR [#13269](https://github.com/fastapi/fastapi/pull/13269) by [@tiangolo](https://github.com/tiangolo). From d5ecbaceae3a4e19191bf3771a1dbfd33aa1e8f5 Mon Sep 17 00:00:00 2001 From: Rahul Pai <50425728+skarfie123@users.noreply.github.com> Date: Thu, 30 Jan 2025 12:17:09 +0000 Subject: [PATCH 748/932] =?UTF-8?q?=F0=9F=90=9B=20Fix=20`OAuth2PasswordReq?= =?UTF-8?q?uestForm`=20and=20`OAuth2PasswordRequestFormStrict`=20fixed=20`?= =?UTF-8?q?grant=5Ftype`=20"password"=20RegEx=20(#9783)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> Co-authored-by: Sofie Van Landeghem Co-authored-by: svlandeg Co-authored-by: Sebastián Ramírez --- fastapi/security/oauth2.py | 4 +-- tests/test_security_oauth2.py | 25 +++++++++++++------ tests/test_security_oauth2_optional.py | 25 +++++++++++++------ ...st_security_oauth2_optional_description.py | 25 +++++++++++++------ .../test_security/test_tutorial003.py | 4 +-- .../test_security/test_tutorial005.py | 4 +-- 6 files changed, 57 insertions(+), 30 deletions(-) diff --git a/fastapi/security/oauth2.py b/fastapi/security/oauth2.py index 6adc55bfe..5ffad5986 100644 --- a/fastapi/security/oauth2.py +++ b/fastapi/security/oauth2.py @@ -63,7 +63,7 @@ class OAuth2PasswordRequestForm: *, grant_type: Annotated[ Union[str, None], - Form(pattern="password"), + Form(pattern="^password$"), Doc( """ The OAuth2 spec says it is required and MUST be the fixed string @@ -217,7 +217,7 @@ class OAuth2PasswordRequestFormStrict(OAuth2PasswordRequestForm): self, grant_type: Annotated[ str, - Form(pattern="password"), + Form(pattern="^password$"), Doc( """ The OAuth2 spec says it is required and MUST be the fixed string diff --git a/tests/test_security_oauth2.py b/tests/test_security_oauth2.py index 7d914d034..2b7e3457a 100644 --- a/tests/test_security_oauth2.py +++ b/tests/test_security_oauth2.py @@ -1,3 +1,4 @@ +import pytest from dirty_equals import IsDict from fastapi import Depends, FastAPI, Security from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict @@ -137,10 +138,18 @@ def test_strict_login_no_grant_type(): ) -def test_strict_login_incorrect_grant_type(): +@pytest.mark.parametrize( + argnames=["grant_type"], + argvalues=[ + pytest.param("incorrect", id="incorrect value"), + pytest.param("passwordblah", id="password with suffix"), + pytest.param("blahpassword", id="password with prefix"), + ], +) +def test_strict_login_incorrect_grant_type(grant_type: str): response = client.post( "/login", - data={"username": "johndoe", "password": "secret", "grant_type": "incorrect"}, + data={"username": "johndoe", "password": "secret", "grant_type": grant_type}, ) assert response.status_code == 422 assert response.json() == IsDict( @@ -149,9 +158,9 @@ def test_strict_login_incorrect_grant_type(): { "type": "string_pattern_mismatch", "loc": ["body", "grant_type"], - "msg": "String should match pattern 'password'", - "input": "incorrect", - "ctx": {"pattern": "password"}, + "msg": "String should match pattern '^password$'", + "input": grant_type, + "ctx": {"pattern": "^password$"}, } ] } @@ -161,9 +170,9 @@ def test_strict_login_incorrect_grant_type(): "detail": [ { "loc": ["body", "grant_type"], - "msg": 'string does not match regex "password"', + "msg": 'string does not match regex "^password$"', "type": "value_error.str.regex", - "ctx": {"pattern": "password"}, + "ctx": {"pattern": "^password$"}, } ] } @@ -248,7 +257,7 @@ def test_openapi_schema(): "properties": { "grant_type": { "title": "Grant Type", - "pattern": "password", + "pattern": "^password$", "type": "string", }, "username": {"title": "Username", "type": "string"}, diff --git a/tests/test_security_oauth2_optional.py b/tests/test_security_oauth2_optional.py index 0da3b911e..046ac5763 100644 --- a/tests/test_security_oauth2_optional.py +++ b/tests/test_security_oauth2_optional.py @@ -1,5 +1,6 @@ from typing import Optional +import pytest from dirty_equals import IsDict from fastapi import Depends, FastAPI, Security from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict @@ -141,10 +142,18 @@ def test_strict_login_no_grant_type(): ) -def test_strict_login_incorrect_grant_type(): +@pytest.mark.parametrize( + argnames=["grant_type"], + argvalues=[ + pytest.param("incorrect", id="incorrect value"), + pytest.param("passwordblah", id="password with suffix"), + pytest.param("blahpassword", id="password with prefix"), + ], +) +def test_strict_login_incorrect_grant_type(grant_type: str): response = client.post( "/login", - data={"username": "johndoe", "password": "secret", "grant_type": "incorrect"}, + data={"username": "johndoe", "password": "secret", "grant_type": grant_type}, ) assert response.status_code == 422 assert response.json() == IsDict( @@ -153,9 +162,9 @@ def test_strict_login_incorrect_grant_type(): { "type": "string_pattern_mismatch", "loc": ["body", "grant_type"], - "msg": "String should match pattern 'password'", - "input": "incorrect", - "ctx": {"pattern": "password"}, + "msg": "String should match pattern '^password$'", + "input": grant_type, + "ctx": {"pattern": "^password$"}, } ] } @@ -165,9 +174,9 @@ def test_strict_login_incorrect_grant_type(): "detail": [ { "loc": ["body", "grant_type"], - "msg": 'string does not match regex "password"', + "msg": 'string does not match regex "^password$"', "type": "value_error.str.regex", - "ctx": {"pattern": "password"}, + "ctx": {"pattern": "^password$"}, } ] } @@ -252,7 +261,7 @@ def test_openapi_schema(): "properties": { "grant_type": { "title": "Grant Type", - "pattern": "password", + "pattern": "^password$", "type": "string", }, "username": {"title": "Username", "type": "string"}, diff --git a/tests/test_security_oauth2_optional_description.py b/tests/test_security_oauth2_optional_description.py index 85a9f9b39..629cddca2 100644 --- a/tests/test_security_oauth2_optional_description.py +++ b/tests/test_security_oauth2_optional_description.py @@ -1,5 +1,6 @@ from typing import Optional +import pytest from dirty_equals import IsDict from fastapi import Depends, FastAPI, Security from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict @@ -142,10 +143,18 @@ def test_strict_login_no_grant_type(): ) -def test_strict_login_incorrect_grant_type(): +@pytest.mark.parametrize( + argnames=["grant_type"], + argvalues=[ + pytest.param("incorrect", id="incorrect value"), + pytest.param("passwordblah", id="password with suffix"), + pytest.param("blahpassword", id="password with prefix"), + ], +) +def test_strict_login_incorrect_grant_type(grant_type: str): response = client.post( "/login", - data={"username": "johndoe", "password": "secret", "grant_type": "incorrect"}, + data={"username": "johndoe", "password": "secret", "grant_type": grant_type}, ) assert response.status_code == 422 assert response.json() == IsDict( @@ -154,9 +163,9 @@ def test_strict_login_incorrect_grant_type(): { "type": "string_pattern_mismatch", "loc": ["body", "grant_type"], - "msg": "String should match pattern 'password'", - "input": "incorrect", - "ctx": {"pattern": "password"}, + "msg": "String should match pattern '^password$'", + "input": grant_type, + "ctx": {"pattern": "^password$"}, } ] } @@ -166,9 +175,9 @@ def test_strict_login_incorrect_grant_type(): "detail": [ { "loc": ["body", "grant_type"], - "msg": 'string does not match regex "password"', + "msg": 'string does not match regex "^password$"', "type": "value_error.str.regex", - "ctx": {"pattern": "password"}, + "ctx": {"pattern": "^password$"}, } ] } @@ -253,7 +262,7 @@ def test_openapi_schema(): "properties": { "grant_type": { "title": "Grant Type", - "pattern": "password", + "pattern": "^password$", "type": "string", }, "username": {"title": "Username", "type": "string"}, diff --git a/tests/test_tutorial/test_security/test_tutorial003.py b/tests/test_tutorial/test_security/test_tutorial003.py index 7a4c99401..37fc2618f 100644 --- a/tests/test_tutorial/test_security/test_tutorial003.py +++ b/tests/test_tutorial/test_security/test_tutorial003.py @@ -149,7 +149,7 @@ def test_openapi_schema(client: TestClient): { "title": "Grant Type", "anyOf": [ - {"pattern": "password", "type": "string"}, + {"pattern": "^password$", "type": "string"}, {"type": "null"}, ], } @@ -158,7 +158,7 @@ def test_openapi_schema(client: TestClient): # TODO: remove when deprecating Pydantic v1 { "title": "Grant Type", - "pattern": "password", + "pattern": "^password$", "type": "string", } ), diff --git a/tests/test_tutorial/test_security/test_tutorial005.py b/tests/test_tutorial/test_security/test_tutorial005.py index c7f791b03..88c3d7815 100644 --- a/tests/test_tutorial/test_security/test_tutorial005.py +++ b/tests/test_tutorial/test_security/test_tutorial005.py @@ -363,7 +363,7 @@ def test_openapi_schema(mod: ModuleType): { "title": "Grant Type", "anyOf": [ - {"pattern": "password", "type": "string"}, + {"pattern": "^password$", "type": "string"}, {"type": "null"}, ], } @@ -372,7 +372,7 @@ def test_openapi_schema(mod: ModuleType): # TODO: remove when deprecating Pydantic v1 { "title": "Grant Type", - "pattern": "password", + "pattern": "^password$", "type": "string", } ), From 30b270be9ac9cf931b0efaac549ba0ad8112f547 Mon Sep 17 00:00:00 2001 From: Shahriyar Rzayev Date: Thu, 30 Jan 2025 13:17:20 +0100 Subject: [PATCH 749/932] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Move=20duplicated?= =?UTF-8?q?=20code=20portion=20to=20a=20static=20method=20in=20the=20`APIK?= =?UTF-8?q?eyBase`=20super=20class=20(#3142)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sofie Van Landeghem Co-authored-by: svlandeg --- fastapi/security/api_key.py | 37 ++++++++++++------------------------- 1 file changed, 12 insertions(+), 25 deletions(-) diff --git a/fastapi/security/api_key.py b/fastapi/security/api_key.py index d68bdb037..70c2dca8a 100644 --- a/fastapi/security/api_key.py +++ b/fastapi/security/api_key.py @@ -9,7 +9,15 @@ from typing_extensions import Annotated, Doc class APIKeyBase(SecurityBase): - pass + @staticmethod + def check_api_key(api_key: Optional[str], auto_error: bool) -> Optional[str]: + if not api_key: + if auto_error: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" + ) + return None + return api_key class APIKeyQuery(APIKeyBase): @@ -101,14 +109,7 @@ class APIKeyQuery(APIKeyBase): async def __call__(self, request: Request) -> Optional[str]: api_key = request.query_params.get(self.model.name) - if not api_key: - if self.auto_error: - raise HTTPException( - status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" - ) - else: - return None - return api_key + return self.check_api_key(api_key, self.auto_error) class APIKeyHeader(APIKeyBase): @@ -196,14 +197,7 @@ class APIKeyHeader(APIKeyBase): async def __call__(self, request: Request) -> Optional[str]: api_key = request.headers.get(self.model.name) - if not api_key: - if self.auto_error: - raise HTTPException( - status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" - ) - else: - return None - return api_key + return self.check_api_key(api_key, self.auto_error) class APIKeyCookie(APIKeyBase): @@ -291,11 +285,4 @@ class APIKeyCookie(APIKeyBase): async def __call__(self, request: Request) -> Optional[str]: api_key = request.cookies.get(self.model.name) - if not api_key: - if self.auto_error: - raise HTTPException( - status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" - ) - else: - return None - return api_key + return self.check_api_key(api_key, self.auto_error) From 041b2e1c4643c9837d2e7f8589351492cf76497a Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 30 Jan 2025 12:17:34 +0000 Subject: [PATCH 750/932] =?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 [skip ci] --- 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 2f9da1465..a07b2023c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Fixes + +* 🐛 Fix `OAuth2PasswordRequestForm` and `OAuth2PasswordRequestFormStrict` fixed `grant_type` "password" RegEx. PR [#9783](https://github.com/fastapi/fastapi/pull/9783) by [@skarfie123](https://github.com/skarfie123). + ### Refactors * ✅ Simplify tests for request_files. PR [#13182](https://github.com/fastapi/fastapi/pull/13182) by [@alejsdev](https://github.com/alejsdev). From 0541693bc7611da858f71d896a3b9780751c04f8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 30 Jan 2025 12:17:52 +0000 Subject: [PATCH 751/932] =?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 [skip ci] --- 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 a07b2023c..b1c34800c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Refactors +* ♻️ Move duplicated code portion to a static method in the `APIKeyBase` super class. PR [#3142](https://github.com/fastapi/fastapi/pull/3142) by [@ShahriyarR](https://github.com/ShahriyarR). * ✅ Simplify tests for request_files. PR [#13182](https://github.com/fastapi/fastapi/pull/13182) by [@alejsdev](https://github.com/alejsdev). ### Docs From 9667ce87a908eecc2be2a215adcb55c7e1b38040 Mon Sep 17 00:00:00 2001 From: Ysabel <5388340+togogh@users.noreply.github.com> Date: Thu, 30 Jan 2025 20:19:10 +0800 Subject: [PATCH 752/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20Request=20Body'?= =?UTF-8?q?s=20`tutorial002`=20to=20deal=20with=20`tax=3D0`=20case=20(#132?= =?UTF-8?q?30)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: svlandeg --- docs_src/body/tutorial002.py | 2 +- docs_src/body/tutorial002_py310.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs_src/body/tutorial002.py b/docs_src/body/tutorial002.py index 7f5183908..5cd86216b 100644 --- a/docs_src/body/tutorial002.py +++ b/docs_src/body/tutorial002.py @@ -17,7 +17,7 @@ app = FastAPI() @app.post("/items/") async def create_item(item: Item): item_dict = item.dict() - if item.tax: + if item.tax is not None: price_with_tax = item.price + item.tax item_dict.update({"price_with_tax": price_with_tax}) return item_dict diff --git a/docs_src/body/tutorial002_py310.py b/docs_src/body/tutorial002_py310.py index 8928b72b8..454c45c88 100644 --- a/docs_src/body/tutorial002_py310.py +++ b/docs_src/body/tutorial002_py310.py @@ -15,7 +15,7 @@ app = FastAPI() @app.post("/items/") async def create_item(item: Item): item_dict = item.dict() - if item.tax: + if item.tax is not None: price_with_tax = item.price + item.tax item_dict.update({"price_with_tax": price_with_tax}) return item_dict From d97647fd572169cf0434919464de5406057e32f4 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 30 Jan 2025 12:19:41 +0000 Subject: [PATCH 753/932] =?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 [skip ci] --- 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 b1c34800c..76955df17 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -18,6 +18,7 @@ hide: ### Docs +* 📝 Update Request Body's `tutorial002` to deal with `tax=0` case. PR [#13230](https://github.com/fastapi/fastapi/pull/13230) by [@togogh](https://github.com/togogh). * 👥 Update FastAPI People - Experts. PR [#13269](https://github.com/fastapi/fastapi/pull/13269) by [@tiangolo](https://github.com/tiangolo). ### Translations From 3d02a920ab7c4b2d26bab67b10e35fc90a923ce1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 30 Jan 2025 12:20:24 +0000 Subject: [PATCH 755/932] =?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 [skip ci] --- 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 76955df17..e343337a7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Refactors +* ✅ Simplify tests for body_multiple_params . PR [#13237](https://github.com/fastapi/fastapi/pull/13237) by [@alejsdev](https://github.com/alejsdev). * ♻️ Move duplicated code portion to a static method in the `APIKeyBase` super class. PR [#3142](https://github.com/fastapi/fastapi/pull/3142) by [@ShahriyarR](https://github.com/ShahriyarR). * ✅ Simplify tests for request_files. PR [#13182](https://github.com/fastapi/fastapi/pull/13182) by [@alejsdev](https://github.com/alejsdev). From 83ab6ac95797395b5664626b66d1c3f1f5b0e8dc Mon Sep 17 00:00:00 2001 From: timothy <53824764+timothy-jeong@users.noreply.github.com> Date: Thu, 30 Jan 2025 21:21:44 +0900 Subject: [PATCH 756/932] =?UTF-8?q?=F0=9F=93=9D=20Change=20the=20word=20"u?= =?UTF-8?q?nwrap"=20to=20"unpack"=20in=20`docs/en/docs/tutorial/extra-mode?= =?UTF-8?q?ls.md`=20(#13061)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: timothy <53824764+jts8257@users.noreply.github.com> Co-authored-by: Sofie Van Landeghem --- docs/en/docs/tutorial/extra-models.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/en/docs/tutorial/extra-models.md b/docs/en/docs/tutorial/extra-models.md index 5fac3f69e..ed1590ece 100644 --- a/docs/en/docs/tutorial/extra-models.md +++ b/docs/en/docs/tutorial/extra-models.md @@ -70,9 +70,9 @@ we would get a Python `dict` with: } ``` -#### Unwrapping a `dict` +#### Unpacking a `dict` -If we take a `dict` like `user_dict` and pass it to a function (or class) with `**user_dict`, Python will "unwrap" it. It will pass the keys and values of the `user_dict` directly as key-value arguments. +If we take a `dict` like `user_dict` and pass it to a function (or class) with `**user_dict`, Python will "unpack" it. It will pass the keys and values of the `user_dict` directly as key-value arguments. So, continuing with the `user_dict` from above, writing: @@ -117,11 +117,11 @@ would be equivalent to: UserInDB(**user_in.dict()) ``` -...because `user_in.dict()` is a `dict`, and then we make Python "unwrap" it by passing it to `UserInDB` prefixed with `**`. +...because `user_in.dict()` is a `dict`, and then we make Python "unpack" it by passing it to `UserInDB` prefixed with `**`. So, we get a Pydantic model from the data in another Pydantic model. -#### Unwrapping a `dict` and extra keywords +#### Unpacking a `dict` and extra keywords And then adding the extra keyword argument `hashed_password=hashed_password`, like in: From 55f8a446c7c02ac6bb26e7adcdeb5ade2408a0ba Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 30 Jan 2025 12:23:00 +0000 Subject: [PATCH 757/932] =?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 [skip ci] --- 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 e343337a7..e4e8a339a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Docs +* 📝 Change the word "unwrap" to "unpack" in `docs/en/docs/tutorial/extra-models.md`. PR [#13061](https://github.com/fastapi/fastapi/pull/13061) by [@timothy-jeong](https://github.com/timothy-jeong). * 📝 Update Request Body's `tutorial002` to deal with `tax=0` case. PR [#13230](https://github.com/fastapi/fastapi/pull/13230) by [@togogh](https://github.com/togogh). * 👥 Update FastAPI People - Experts. PR [#13269](https://github.com/fastapi/fastapi/pull/13269) by [@tiangolo](https://github.com/tiangolo). From 7128971f1d61e2e1e6f220a5f66baa925b635278 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 30 Jan 2025 13:58:14 +0000 Subject: [PATCH 758/932] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?5.8?= 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 e4e8a339a..9dd9cc65c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.115.8 + ### Fixes * 🐛 Fix `OAuth2PasswordRequestForm` and `OAuth2PasswordRequestFormStrict` fixed `grant_type` "password" RegEx. PR [#9783](https://github.com/fastapi/fastapi/pull/9783) by [@skarfie123](https://github.com/skarfie123). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index c92279cfd..e3e0200ae 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.7" +__version__ = "0.115.8" from starlette import status as status From df8f281674a1aec51d98ab74b6d8073bcc298ab0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 31 Jan 2025 17:01:48 +0000 Subject: [PATCH 759/932] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors,=20add?= =?UTF-8?q?=20Permit=20(#13288)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + docs/en/data/sponsors.yml | 3 +++ docs/en/docs/img/sponsors/permit.png | Bin 0 -> 39234 bytes 3 files changed, 4 insertions(+) create mode 100644 docs/en/docs/img/sponsors/permit.png diff --git a/README.md b/README.md index 6492ad745..f6da22b21 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ The key features are: + diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 4231452e4..f9bf33ae9 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -48,6 +48,9 @@ silver: - url: https://www.stainlessapi.com/?utm_source=fastapi&utm_medium=referral title: Stainless | Generate best-in-class SDKs img: https://fastapi.tiangolo.com/img/sponsors/stainless.png + - url: https://www.permit.io/blog/implement-authorization-in-fastapi?utm_source=github&utm_medium=referral&utm_campaign=fastapi + title: Fine-Grained Authorization for FastAPI + img: https://fastapi.tiangolo.com/img/sponsors/permit.png bronze: - url: https://www.exoflare.com/open-source/?utm_source=FastAPI&utm_campaign=open_source title: Biosecurity risk assessments made easy. diff --git a/docs/en/docs/img/sponsors/permit.png b/docs/en/docs/img/sponsors/permit.png new file mode 100644 index 0000000000000000000000000000000000000000..4f07f22e27326c34108ca177f0a974182bb44914 GIT binary patch literal 39234 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%0A$XJ`3vlcLYN0j|tw?edFE(d{H`gM~vIza4ktrPP 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

    =WMDDAr#Fp;TDW7fKOeyNR&^B(cOS7csl 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 Date: Fri, 31 Jan 2025 17:02:11 +0000 Subject: [PATCH 760/932] =?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 [skip ci] --- 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 9dd9cc65c..12d6487aa 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Internal + +* 🔧 Update sponsors, add Permit. PR [#13288](https://github.com/fastapi/fastapi/pull/13288) by [@tiangolo](https://github.com/tiangolo). + ## 0.115.8 ### Fixes From 633ed1d8aff74a2575512d95c644ba9f2084b801 Mon Sep 17 00:00:00 2001 From: Rishat-F <66554797+Rishat-F@users.noreply.github.com> Date: Mon, 3 Feb 2025 16:33:39 +0300 Subject: [PATCH 761/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/advanced/websockets.md`=20(#13279)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/advanced/websockets.md | 186 ++++++++++++++++++++++++++++ 1 file changed, 186 insertions(+) create mode 100644 docs/ru/docs/advanced/websockets.md diff --git a/docs/ru/docs/advanced/websockets.md b/docs/ru/docs/advanced/websockets.md new file mode 100644 index 000000000..bc9dfcbff --- /dev/null +++ b/docs/ru/docs/advanced/websockets.md @@ -0,0 +1,186 @@ +# Веб-сокеты + +Вы можете использовать веб-сокеты в **FastAPI**. + +## Установка `WebSockets` + +Убедитесь, что [виртуальная среда](../virtual-environments.md){.internal-link target=_blank} создана, активируйте её и установите `websockets`: + +

    + +```console +$ pip install websockets + +---> 100% +``` + +
    + +## Клиент WebSockets + +### Рабочее приложение + +Скорее всего, в вашей реальной продуктовой системе есть фронтенд, реализованный при помощи современных фреймворков React, Vue.js или Angular. + +И наверняка для взаимодействия с бекендом через веб-сокеты вы будете использовать средства фронтенда. + +Также у вас может быть нативное мобильное приложение, коммуницирующее непосредственно с веб-сокетами на бекенд-сервере. + +Либо вы можете сделать какой-либо другой способ взаимодействия с веб-сокетами. + +--- + +Но для этого примера мы воспользуемся очень простым HTML документом с небольшими вставками JavaScript кода. + +Конечно же это неоптимально, и на практике так делать не стоит. + +В реальных приложениях стоит воспользоваться одним из вышеупомянутых способов. + +Для примера нам нужен наиболее простой способ, который позволит сосредоточиться на серверной части веб-сокетов и получить рабочий код: + +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} + +## Создание `websocket` + +Создайте `websocket` в своем **FastAPI** приложении: + +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} + +/// note | Технические детали + +Вы также можете использовать `from starlette.websockets import WebSocket`. + +**FastAPI** напрямую предоставляет тот же самый `WebSocket` просто для удобства. На самом деле это `WebSocket` из Starlette. + +/// + +## Ожидание и отправка сообщений + +Через эндпоинт веб-сокета вы можете получать и отправлять сообщения. + +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} + +Вы можете получать и отправлять двоичные, текстовые и JSON данные. + +## Проверка в действии + +Если ваш файл называется `main.py`, то запустите приложение командой: + +
    + +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
    + +Откройте браузер по адресу http://127.0.0.1:8000. + +Вы увидите следующую простенькую страницу: + + + +Вы можете набирать сообщения в поле ввода и отправлять их: + + + +И ваше **FastAPI** приложение с веб-сокетами ответит: + + + +Вы можете отправлять и получать множество сообщений: + + + +И все они будут использовать одно и то же веб-сокет соединение. + +## Использование `Depends` и не только + +Вы можете импортировать из `fastapi` и использовать в эндпоинте вебсокета: + +* `Depends` +* `Security` +* `Cookie` +* `Header` +* `Path` +* `Query` + +Они работают так же, как и в других FastAPI эндпоинтах/*операциях пути*: + +{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *} + +/// info | Примечание + +В веб-сокете вызывать `HTTPException` не имеет смысла. Вместо этого нужно использовать `WebSocketException`. + +Закрывающий статус код можно использовать из valid codes defined in the specification. + +/// + +### Веб-сокеты с зависимостями: проверка в действии + +Если ваш файл называется `main.py`, то запустите приложение командой: + +
    + +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
    + +Откройте браузер по адресу http://127.0.0.1:8000. + +Там вы можете задать: + +* "Item ID", используемый в пути. +* "Token", используемый как query-параметр. + +/// tip | Подсказка + +Обратите внимание, что query-параметр `token` будет обработан в зависимости. + +/// + +Теперь вы можете подключиться к веб-сокету и начинать отправку и получение сообщений: + + + +## Обработка отключений и работа с несколькими клиентами + +Если веб-сокет соединение закрыто, то `await websocket.receive_text()` вызовет исключение `WebSocketDisconnect`, которое можно поймать и обработать как в этом примере: + +{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *} + +Чтобы воспроизвести пример: + +* Откройте приложение в нескольких вкладках браузера. +* Отправьте из них сообщения. +* Затем закройте одну из вкладок. + +Это вызовет исключение `WebSocketDisconnect`, и все остальные клиенты получат следующее сообщение: + +``` +Client #1596980209979 left the chat +``` + +/// tip | Примечание + +Приложение выше - это всего лишь простой минимальный пример, демонстрирующий обработку и передачу сообщений нескольким веб-сокет соединениям. + +Но имейте в виду, что это будет работать только в одном процессе и только пока он активен, так как всё обрабатывается в простом списке в оперативной памяти. + +Если нужно что-то легко интегрируемое с FastAPI, но более надежное и с поддержкой Redis, PostgreSQL или другого, то можно воспользоваться encode/broadcaster. + +/// + +## Дополнительная информация + +Для более глубокого изучения темы воспользуйтесь документацией Starlette: + +* The `WebSocket` class. +* Class-based WebSocket handling. From 0310af3557ef1fba1d2487f929c5080180642e4b Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 3 Feb 2025 13:34:01 +0000 Subject: [PATCH 762/932] =?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 [skip ci] --- 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 12d6487aa..a9d86d854 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Translations + +* 🌐 Add Russian translation for `docs/ru/docs/advanced/websockets.md`. PR [#13279](https://github.com/fastapi/fastapi/pull/13279) by [@Rishat-F](https://github.com/Rishat-F). + ### Internal * 🔧 Update sponsors, add Permit. PR [#13288](https://github.com/fastapi/fastapi/pull/13288) by [@tiangolo](https://github.com/tiangolo). From c73e895b8639b6d69e3ff1849825c03b9a8e7b60 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Feb 2025 13:51:01 +0000 Subject: [PATCH 763/932] =?UTF-8?q?=E2=AC=86=20Bump=20inline-snapshot=20fr?= =?UTF-8?q?om=200.18.1=20to=200.19.3=20(#13298)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [inline-snapshot](https://github.com/15r10nk/inline-snapshot) from 0.18.1 to 0.19.3. - [Release notes](https://github.com/15r10nk/inline-snapshot/releases) - [Changelog](https://github.com/15r10nk/inline-snapshot/blob/main/CHANGELOG.md) - [Commits](https://github.com/15r10nk/inline-snapshot/compare/0.18.1...0.19.3) --- updated-dependencies: - dependency-name: inline-snapshot dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-tests.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-tests.txt b/requirements-tests.txt index 91e7fb7aa..4a15844e4 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -10,7 +10,7 @@ anyio[trio] >=3.2.1,<5.0.0 PyJWT==2.8.0 pyyaml >=5.3.1,<7.0.0 passlib[bcrypt] >=1.7.2,<2.0.0 -inline-snapshot==0.18.1 +inline-snapshot==0.19.3 # types types-ujson ==5.10.0.20240515 types-orjson ==3.6.2 From ae724b05ceef1a7d62a8aa549fc9dc34c9bd3ad9 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 3 Feb 2025 13:51:28 +0000 Subject: [PATCH 764/932] =?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 [skip ci] --- 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 a9d86d854..d3e652d19 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Internal +* ⬆ Bump inline-snapshot from 0.18.1 to 0.19.3. PR [#13298](https://github.com/fastapi/fastapi/pull/13298) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Update sponsors, add Permit. PR [#13288](https://github.com/fastapi/fastapi/pull/13288) by [@tiangolo](https://github.com/tiangolo). ## 0.115.8 From fb19d9895d1b4ca2baf1695204c0f9753ed737fe Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Fri, 7 Feb 2025 19:01:55 -0300 Subject: [PATCH 765/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Portuguese=20Tr?= =?UTF-8?q?anslation=20for=20`docs/pt/docs/index.md`=20(#13328)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/index.md | 139 +++++++++++++++++++++++++++--------------- 1 file changed, 89 insertions(+), 50 deletions(-) diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md index bc23114dc..138048f06 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -11,15 +11,18 @@ Framework FastAPI, alta performance, fácil de aprender, fácil de codar, pronto para produção

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

    --- @@ -60,7 +63,7 @@ Os recursos chave são: -Outros patrocinadores +Outros patrocinadores ## Opiniões @@ -70,6 +73,18 @@ Os recursos chave são: --- +"_Nós adotamos a biblioteca **FastAPI** para iniciar um servidor **REST** que pode ser consultado para obter **previsões**. [para o Ludwig]_" + +
    Piero Molino, Yaroslav Dudin, e Sai Sumanth Miryala - Uber (ref)
    + +--- + +"_A **Netflix** tem o prazer de anunciar o lançamento open-source do nosso framework de orquestração de **gerenciamento de crises**: **Dispatch**! [criado com **FastAPI**]_" + +
    Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
    + +--- + "*Estou extremamente entusiasmado com o **FastAPI**. É tão divertido!*"
    Brian Okken - Python Bytes podcaster (ref)
    @@ -90,9 +105,9 @@ Os recursos chave são: --- -"*Nós adotamos a biblioteca **FastAPI** para criar um servidor **REST** que possa ser chamado para obter **predições**. [para o Ludwig]*" +"_Se alguém estiver procurando construir uma API Python para produção, eu recomendaria fortemente o **FastAPI**. Ele é **lindamente projetado**, **simples de usar** e **altamente escalável**. Ele se tornou um **componente chave** para a nossa estratégia API first de desenvolvimento e está impulsionando diversas automações e serviços, como o nosso Virtual TAC Engineer._" -
    Piero Molino, Yaroslav Dudin e Sai Sumanth Miryala - Uber (ref)
    +
    Deon Pillsbury - Cisco (ref)
    --- @@ -113,28 +128,20 @@ FastAPI está nos ombros de gigantes: ## Instalação -
    - -```console -$ pip install fastapi - ----> 100% -``` - -
    - -Você também precisará de um servidor ASGI para produção, tal como Uvicorn ou Hypercorn. +Crie e ative um ambiente virtual, e então instale o FastAPI:
    ```console -$ pip install "uvicorn[standard]" +$ pip install "fastapi[standard]" ---> 100% ```
    +**Nota**: Certifique-se de que você colocou `"fastapi[standard]"` com aspas, para garantir que funcione em todos os terminais. + ## Exemplo ### Crie @@ -184,7 +191,7 @@ async def read_item(item_id: int, q: Union[str, None] = None): **Nota**: -Se você não sabe, verifique a seção _"In a hurry?"_ sobre `async` e `await` nas docs. +Se você não sabe, verifique a seção _"Com pressa?"_ sobre `async` e `await` nas docs. @@ -195,11 +202,24 @@ Rode o servidor com:
    ```console -$ uvicorn main:app --reload - +$ fastapi dev main.py + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + │ fastapi run │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] +INFO: Started reloader process [2248755] using WatchFiles +INFO: Started server process [2248757] INFO: Waiting for application startup. INFO: Application startup complete. ``` @@ -207,13 +227,13 @@ INFO: Application startup complete.
    -Sobre o comando uvicorn main:app --reload... +Sobre o comando fastapi dev main.py... -O comando `uvicorn main:app` se refere a: +O comando `fastapi dev` lê o seu arquivo `main.py`, identifica o aplicativo **FastAPI** nele, e inicia um servidor usando o Uvicorn. -* `main`: o arquivo `main.py` (o "módulo" Python). -* `app`: o objeto criado dentro de `main.py` com a linha `app = FastAPI()`. -* `--reload`: faz o servidor recarregar após mudanças de código. Somente faça isso para desenvolvimento. +Por padrão, o `fastapi dev` iniciará com *auto-reload* habilitado para desenvolvimento local. + +Você pode ler mais sobre isso na documentação do FastAPI CLI.
    @@ -268,7 +288,7 @@ app = FastAPI() class Item(BaseModel): name: str price: float - is_offer: Union[bool] = None + is_offer: Union[bool, None] = None @app.get("/") @@ -286,7 +306,7 @@ def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id} ``` -O servidor deverá recarregar automaticamente (porquê você adicionou `--reload` ao comando `uvicorn` acima). +O servidor `fastapi dev` deverá recarregar automaticamente. ### Evoluindo a Documentação Interativa da API @@ -316,7 +336,7 @@ E agora, vá para Tutorial - Guia do Usuário. +Para um exemplo mais completo incluindo mais recursos, veja Tutorial - Guia do Usuário. **Alerta de Spoiler**: o tutorial - guia do usuário inclui: @@ -416,9 +436,9 @@ Para um exemplo mais completo incluindo mais recursos, veja Injeção de Dependência**. * Segurança e autenticação, incluindo suporte para **OAuth2** com autenticação **JWT tokens** e **HTTP Basic**. * Técnicas mais avançadas (mas igualmente fáceis) para declaração de **modelos JSON profundamente aninhados** (graças ao Pydantic). +* Integrações **GraphQL** com o Strawberry e outras bibliotecas. * Muitos recursos extras (graças ao Starlette) como: * **WebSockets** - * **GraphQL** * testes extrememamente fáceis baseados em HTTPX e `pytest` * **CORS** * **Cookie Sessions** @@ -428,30 +448,49 @@ Para um exemplo mais completo incluindo mais recursos, veja um dos _frameworks_ Python mais rápidos disponíveis, somente atrás de Starlette e Uvicorn (utilizados internamente pelo FastAPI). (*) -Para entender mais sobre performance, veja a seção Benchmarks. +Para entender mais sobre performance, veja a seção Comparações. + +## Dependências + +O FastAPI depende do Pydantic e do Starlette. + -## Dependências opcionais +### Dependências `standard` -Usados por Pydantic: +Quando você instala o FastAPI com `pip install "fastapi[standard]"`, ele vêm com o grupo `standard` (padrão) de dependências opcionais: + +Utilizado pelo Pydantic: * email-validator - para validação de email. -Usados por Starlette: +Utilizado pelo Starlette: + +* httpx - Obrigatório caso você queira utilizar o `TestClient`. +* jinja2 - Obrigatório se você quer utilizar a configuração padrão de templates. +* python-multipart - Obrigatório se você deseja suporte a "parsing" de formulário, com `request.form()`. + +Utilizado pelo FastAPI / Starlette: + +* uvicorn - para o servidor que carrega e serve a sua aplicação. Isto inclui `uvicorn[standard]`, que inclui algumas dependências (e.g. `uvloop`) necessárias para servir em alta performance. +* `fastapi-cli` - que disponibiliza o comando `fastapi`. + +### Sem as dependências `standard` + +Se você não deseja incluir as dependências opcionais `standard`, você pode instalar utilizando `pip install fastapi` ao invés de `pip install "fastapi[standard]"`. + +### Dpendências opcionais adicionais + +Existem algumas dependências adicionais que você pode querer instalar. -* httpx - Necessário se você quiser utilizar o `TestClient`. -* jinja2 - Necessário se você quiser utilizar a configuração padrão de templates. -* python-multipart - Necessário se você quiser suporte com "parsing" de formulário, com `request.form()`. -* itsdangerous - Necessário para suporte a `SessionMiddleware`. -* pyyaml - Necessário para suporte a `SchemaGenerator` da Starlette (você provavelmente não precisará disso com o FastAPI). -* graphene - Necessário para suporte a `GraphQLApp`. +Dependências opcionais adicionais do Pydantic: -Usados por FastAPI / Starlette: +* pydantic-settings - para gerenciamento de configurações. +* pydantic-extra-types - tipos extras para serem utilizados com o Pydantic. -* uvicorn - para o servidor que carrega e serve sua aplicação. -* orjson - Necessário se você quer utilizar `ORJSONResponse`. -* ujson - Necessário se você quer utilizar `UJSONResponse`. +Dependências opcionais adicionais do FastAPI: -Você pode instalar todas essas dependências com `pip install fastapi[all]`. +* orjson - Obrigatório se você deseja utilizar o `ORJSONResponse`. +* ujson - Obrigatório se você deseja utilizar o `UJSONResponse`. ## Licença From 3958e5a113fbe9b80e24b46b6d91334ec842beb7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 7 Feb 2025 22:02:19 +0000 Subject: [PATCH 766/932] =?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 [skip ci] --- 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 d3e652d19..07d620043 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Update Portuguese Translation for `docs/pt/docs/index.md`. PR [#13328](https://github.com/fastapi/fastapi/pull/13328) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Russian translation for `docs/ru/docs/advanced/websockets.md`. PR [#13279](https://github.com/fastapi/fastapi/pull/13279) by [@Rishat-F](https://github.com/Rishat-F). ### Internal From 52c1488a372f1c5808429aebc1fbbfd7ca2ba6be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Pedro?= Date: Fri, 7 Feb 2025 19:02:59 -0300 Subject: [PATCH 767/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Portuguese=20Tr?= =?UTF-8?q?anslation=20for=20`docs/pt/docs/deployment/https.md`=20(#13317)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/deployment/https.md | 194 +++++++++++++++++++++++++++---- 1 file changed, 171 insertions(+), 23 deletions(-) diff --git a/docs/pt/docs/deployment/https.md b/docs/pt/docs/deployment/https.md index 9a13977ec..9ad419934 100644 --- a/docs/pt/docs/deployment/https.md +++ b/docs/pt/docs/deployment/https.md @@ -14,38 +14,186 @@ Para aprender o básico de HTTPS de uma perspectiva do usuário, verifique SNI. - * Esta extensão SNI permite que um único servidor (com um único endereço IP) tenha vários certificados HTTPS e atenda a vários domínios / aplicativos HTTPS. - * Para que isso funcione, um único componente (programa) em execução no servidor, ouvindo no endereço IP público, deve ter todos os certificados HTTPS no servidor. -* Depois de obter uma conexão segura, o protocolo de comunicação ainda é HTTP. - * Os conteúdos são criptografados, embora sejam enviados com o protocolo HTTP. + * No entanto, existe uma **solução** para isso. +* Há uma **extensão** para o protocolo **TLS** (aquele que lida com a criptografia no nível TCP, antes do HTTP) chamado **SNI**. + * Esta extensão SNI permite que um único servidor (com um **único endereço IP**) tenha **vários certificados HTTPS** e atenda a **vários domínios / aplicativos HTTPS**. + * Para que isso funcione, um **único** componente (programa) em execução no servidor, ouvindo no **endereço IP público**, deve ter **todos os certificados HTTPS** no servidor. +* **Depois** de obter uma conexão segura, o protocolo de comunicação **ainda é HTTP**. + * Os conteúdos são **criptografados**, embora sejam enviados com o **protocolo HTTP**. -É uma prática comum ter um programa/servidor HTTP em execução no servidor (máquina, host, etc.) e gerenciar todas as partes HTTPS: enviando as solicitações HTTP descriptografadas para o aplicativo HTTP real em execução no mesmo servidor (a aplicação **FastAPI**, neste caso), pegue a resposta HTTP do aplicativo, criptografe-a usando o certificado apropriado e envie-a de volta ao cliente usando HTTPS. Este servidor é frequentemente chamado de TLS Termination Proxy. +É uma prática comum ter um **programa/servidor HTTP** em execução no servidor (máquina, host, etc.) e **gerenciar todas as partes HTTPS**: **recebendo as requisições encriptadas**, enviando as **solicitações HTTP descriptografadas** para o aplicativo HTTP real em execução no mesmo servidor (a aplicação **FastAPI**, neste caso), pegue a **resposta HTTP** do aplicativo, **criptografe-a** usando o **certificado HTTPS** apropriado e envie-a de volta ao cliente usando **HTTPS**. Este servidor é frequentemente chamado de **Proxy de Terminação TLS**. + +Algumas das opções que você pode usar como Proxy de Terminação TLS são: + +* Traefik (que também pode gerenciar a renovação de certificados) +* Caddy (que também pode gerenciar a renovação de certificados) +* Nginx +* HAProxy ## Let's Encrypt -Antes de Let's Encrypt, esses certificados HTTPS eram vendidos por terceiros confiáveis. +Antes de Let's Encrypt, esses **certificados HTTPS** eram vendidos por terceiros confiáveis. O processo de aquisição de um desses certificados costumava ser complicado, exigia bastante papelada e os certificados eram bastante caros. -Mas então Let's Encrypt foi criado. +Mas então o **Let's Encrypt** foi criado. -Ele é um projeto da Linux Foundation que fornece certificados HTTPS gratuitamente. De forma automatizada. Esses certificados usam toda a segurança criptográfica padrão e têm vida curta (cerca de 3 meses), então a segurança é realmente melhor por causa de sua vida útil reduzida. +Ele é um projeto da Linux Foundation que fornece **certificados HTTPS gratuitamente** . De forma automatizada. Esses certificados usam toda a segurança criptográfica padrão e têm vida curta (cerca de 3 meses), então a **segurança é, na verdade, melhor** por causa de sua vida útil reduzida. Os domínios são verificados com segurança e os certificados são gerados automaticamente. Isso também permite automatizar a renovação desses certificados. -A ideia é automatizar a aquisição e renovação desses certificados, para que você tenha HTTPS seguro, de graça e para sempre. +A ideia é automatizar a aquisição e renovação desses certificados, para que você tenha **HTTPS seguro, de graça e para sempre**. + +## HTTPS para Desenvolvedores + +Aqui está um exemplo de como uma API HTTPS poderia ser estruturada, passo a passo, com foco principal nas ideias relevantes para desenvolvedores. + +### Nome do domínio + +A etapa inicial provavelmente seria **adquirir** algum **nome de domínio**. Então, você iria configurá-lo em um servidor DNS (possivelmente no mesmo provedor em nuvem). + +Você provavelmente usaria um servidor em nuvem (máquina virtual) ou algo parecido, e ele teria fixed **Endereço IP público**. + +No(s) servidor(es) DNS, você configuraria um registro (`registro A`) para apontar **seu domínio** para o **endereço IP público do seu servidor**. + +Você provavelmente fará isso apenas uma vez, na primeira vez em que tudo estiver sendo configurado. + +/// tip | Dica + +Essa parte do Nome do Domínio se dá muito antes do HTTPS, mas como tudo depende do domínio e endereço IP público, vale a pena mencioná-la aqui. + +/// + +### DNS + +Agora vamos focar em todas as partes que realmente fazem parte do HTTPS. + +Primeiro, o navegador iria verificar com os **servidores DNS** qual o **IP do domínio**, nesse caso, `someapp.example.com`. + +Os servidores DNS iriam informar o navegador para utilizar algum **endereço IP** específico. Esse seria o endereço IP público em uso no seu servidor, que você configurou nos servidores DNS. + + + +### Início do Handshake TLS + +O navegador então irá comunicar-se com esse endereço IP na **porta 443** (a porta HTTPS). + +A primeira parte dessa comunicação é apenas para estabelecer a conexão entre o cliente e o servidor e para decidir as chaves criptográficas a serem utilizadas, etc. + + + +Esse interação entre o cliente e o servidor para estabelecer uma conexão TLS é chamada de **Handshake TLS**. + +### TLS com a Extensão SNI + +**Apenas um processo** no servidor pode se conectar a uma **porta** em um **endereço IP**. Poderiam existir outros processos conectados em outras portas desse mesmo endereço IP, mas apenas um para cada combinação de endereço IP e porta. + +TLS (HTTPS) usa a porta `443` por padrão. Então essa é a porta que precisamos. + +Como apenas um único processo pode se comunicar com essa porta, o processo que faria isso seria o **Proxy de Terminação TLS**. + +O Proxy de Terminação TLS teria acesso a um ou mais **certificados TLS** (certificados HTTPS). + +Utilizando a **extensão SNI** discutida acima, o Proxy de Terminação TLS iria checar qual dos certificados TLS (HTTPS) disponíveis deve ser usado para essa conexão, utilizando o que corresponda ao domínio esperado pelo cliente. + +Nesse caso, ele usaria o certificado para `someapp.example.com`. + + + +O cliente já **confia** na entidade que gerou o certificado TLS (nesse caso, o Let's Encrypt, mas veremos sobre isso mais tarde), então ele pode **verificar** que o certificado é válido. + +Então, utilizando o certificado, o cliente e o Proxy de Terminação TLS **decidem como encriptar** o resto da **comunicação TCP**. Isso completa a parte do **Handshake TLS**. + +Após isso, o cliente e o servidor possuem uma **conexão TCP encriptada**, que é provida pelo TLS. E então eles podem usar essa conexão para começar a **comunicação HTTP** propriamente dita. + +E isso resume o que é **HTTPS**, apenas **HTTP** simples dentro de uma **conexão TLS segura** em vez de uma conexão TCP pura (não encriptada). + +/// tip | Dica + +Percebe que a encriptação da comunicação acontece no **nível do TCP**, não no nível do HTTP. + +/// + +### Solicitação HTTPS + +Agora que o cliente e servidor (especialmente o navegador e o Proxy de Terminação TLS) possuem uma **conexão TCP encriptada**, eles podem iniciar a **comunicação HTTP**. + +Então, o cliente envia uma **solicitação HTTPS**. Que é apenas uma solicitação HTTP sobre uma conexão TLS encriptada. + + + +### Desencriptando a Solicitação + +O Proxy de Terminação TLS então usaria a encriptação combinada para **desencriptar a solicitação**, e transmitiria a **solicitação básica (desencriptada)** para o processo executando a aplicação (por exemplo, um processo com Uvicorn executando a aplicação FastAPI). + + + +### Resposta HTTP + +A aplicação processaria a solicitação e retornaria uma **resposta HTTP básica (não encriptada)** para o Proxy de Terminação TLS. + + + +### Resposta HTTPS + +O Proxy de Terminação TLS iria **encriptar a resposta** utilizando a criptografia combinada anteriormente (que foi definida com o certificado para `someapp.example.com`), e devolveria para o navegador. + +No próximo passo, o navegador verifica que a resposta é válida e encriptada com a chave criptográfica correta, etc. E depois **desencripta a resposta** e a processa. + + + +O cliente (navegador) saberá que a resposta vem do servidor correto por que ela usa a criptografia que foi combinada entre eles usando o **certificado HTTPS** anterior. + +### Múltiplas Aplicações + +Podem existir **múltiplas aplicações** em execução no mesmo servidor (ou servidores), por exemplo: outras APIs ou um banco de dados. + +Apenas um processo pode estar vinculado a um IP e porta (o Proxy de Terminação TLS, por exemplo), mas outras aplicações/processos também podem estar em execução no(s) servidor(es), desde que não tentem usar a mesma **combinação de IP público e porta**. + + + +Dessa forma, o Proxy de Terminação TLS pode gerenciar o HTTPS e os certificados de **múltiplos domínios**, para múltiplas aplicações, e então transmitir as requisições para a aplicação correta em cada caso. + +### Renovação de Certificados + +Em algum momento futuro, cada certificado irá **expirar** (aproximadamente 3 meses após a aquisição). + +E então, haverá outro programa (em alguns casos pode ser o próprio Proxy de Terminação TLS) que irá interagir com o Let's Encrypt e renovar o(s) certificado(s). + + + +Os **certificados TLS** são **associados com um nome de domínio**, e não a um endereço IP. + +Então para renovar os certificados, o programa de renovação precisa **provar** para a autoridade (Let's Encrypt) que ele realmente **possui e controla esse domínio**> + +Para fazer isso, e acomodar as necessidades de diferentes aplicações, existem diferentes opções para esse programa. Algumas escolhas populares são: + +* **Modificar alguns registros DNS** + * Para isso, o programa de renovação precisa ter suporte as APIs do provedor DNS, então, dependendo do provedor DNS que você utilize, isso pode ou não ser uma opção viável. +* **Executar como um servidor** (ao menos durante o processo de aquisição do certificado) no endereço IP público associado com o domínio. + * Como dito anteriormente, apenas um processo pode estar ligado a uma porta e IP específicos. + * Essa é uma dos motivos que fazem utilizar o mesmo Proxy de Terminação TLS para gerenciar a renovação de certificados ser tão útil. + * Caso contrário, você pode ter que parar a execução do Proxy de Terminação TLS momentaneamente, inicializar o programa de renovação para renovar os certificados, e então reiniciar o Proxy de Terminação TLS. Isso não é o ideal, já que sua(s) aplicação(ões) não vão estar disponíveis enquanto o Proxy de Terminação TLS estiver desligado. + +Todo esse processo de renovação, enquanto o aplicativo ainda funciona, é uma das principais razões para preferir um **sistema separado para gerenciar HTTPS** com um Proxy de Terminação TLS em vez de usar os certificados TLS no servidor da aplicação diretamente (e.g. com o Uvicorn). + +## Recapitulando + +Possuir **HTTPS** habilitado na sua aplicação é bastante importante, e até **crítico** na maioria dos casos. A maior parte do esforço que você tem que colocar sobre o HTTPS como desenvolvedor está em **entender esses conceitos** e como eles funcionam. + +Mas uma vez que você saiba o básico de **HTTPS para desenvolvedores**, você pode combinar e configurar diferentes ferramentas facilmente para gerenciar tudo de uma forma simples. + +Em alguns dos próximos capítulos, eu mostrarei para você vários exemplos concretos de como configurar o **HTTPS** para aplicações **FastAPI**. 🔒 From f97c8de41a401ce04ef1c5e8f7891f01b54b0261 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 7 Feb 2025 22:04:25 +0000 Subject: [PATCH 768/932] =?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 [skip ci] --- 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 07d620043..6a8b0f5d1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Update Portuguese Translation for `docs/pt/docs/deployment/https.md`. PR [#13317](https://github.com/fastapi/fastapi/pull/13317) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Update Portuguese Translation for `docs/pt/docs/index.md`. PR [#13328](https://github.com/fastapi/fastapi/pull/13328) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Russian translation for `docs/ru/docs/advanced/websockets.md`. PR [#13279](https://github.com/fastapi/fastapi/pull/13279) by [@Rishat-F](https://github.com/Rishat-F). From 0c24d0607b843027b827b556beef5ead7eb61695 Mon Sep 17 00:00:00 2001 From: Valentyn Date: Sat, 8 Feb 2025 00:06:37 +0200 Subject: [PATCH 769/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/learn/index.md`=20(#13306)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/uk/docs/learn/index.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 docs/uk/docs/learn/index.md diff --git a/docs/uk/docs/learn/index.md b/docs/uk/docs/learn/index.md new file mode 100644 index 000000000..7f9f21e57 --- /dev/null +++ b/docs/uk/docs/learn/index.md @@ -0,0 +1,5 @@ +# Навчання + +У цьому розділі надані вступні та навчальні матеріали для вивчення FastAPI. + +Це можна розглядати як **книгу**, **курс**, або **офіційний** та рекомендований спосіб освоїти FastAPI. 😎 From eee8d4c58a6620f240564655d11b355d3945f802 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 7 Feb 2025 22:07:12 +0000 Subject: [PATCH 770/932] =?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 [skip ci] --- 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 6a8b0f5d1..b6145c9bb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/learn/index.md`. PR [#13306](https://github.com/fastapi/fastapi/pull/13306) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Update Portuguese Translation for `docs/pt/docs/deployment/https.md`. PR [#13317](https://github.com/fastapi/fastapi/pull/13317) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Update Portuguese Translation for `docs/pt/docs/index.md`. PR [#13328](https://github.com/fastapi/fastapi/pull/13328) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Russian translation for `docs/ru/docs/advanced/websockets.md`. PR [#13279](https://github.com/fastapi/fastapi/pull/13279) by [@Rishat-F](https://github.com/Rishat-F). From 701f5791d373ec82f3660b9d94b97574d4fbddbe Mon Sep 17 00:00:00 2001 From: Valentyn Date: Sat, 8 Feb 2025 00:08:49 +0200 Subject: [PATCH 771/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/features.md`=20(#13308)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/uk/docs/features.md | 189 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 189 insertions(+) create mode 100644 docs/uk/docs/features.md diff --git a/docs/uk/docs/features.md b/docs/uk/docs/features.md new file mode 100644 index 000000000..7d679d8ee --- /dev/null +++ b/docs/uk/docs/features.md @@ -0,0 +1,189 @@ +# Функціональні можливості + +## Функціональні можливості FastAPI + +**FastAPI** надає вам такі можливості: + +### Використання відкритих стандартів + +* OpenAPI для створення API, включаючи оголошення шляхів, операцій, параметрів, тіл запитів, безпеки тощо. +* Автоматична документація моделей даних за допомогою JSON Schema (оскільки OpenAPI базується саме на JSON Schema). +* Розроблено на основі цих стандартів після ретельного аналізу, а не як додатковий рівень поверх основної архітектури. +* Це також дає змогу автоматично **генерувати код клієнта** багатьма мовами. + +### Автоматична генерація документації + +Інтерактивна документація API та вебінтерфейс для його дослідження. Оскільки фреймворк базується на OpenAPI, є кілька варіантів, два з яких включені за замовчуванням. + +* Swagger UI — дозволяє інтерактивно переглядати API, викликати та тестувати його прямо у браузері. + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Альтернативна документація API за допомогою ReDoc. + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Тільки сучасний Python + +FastAPI використовує стандартні **типи Python** (завдяки Pydantic). Вам не потрібно вивчати новий синтаксис — лише стандартний сучасний Python. + +Якщо вам потрібне коротке нагадування про використання типів у Python (навіть якщо ви не використовуєте FastAPI), перегляньте короткий підручник: [Вступ до типів Python](python-types.md){.internal-link target=_blank}. + +Ось приклад стандартного Python-коду з типами: + +```Python +from datetime import date +from pydantic import BaseModel + +# Оголошення змінної як str +# з підтримкою автодоповнення у редакторі +def main(user_id: str): + return user_id + +# Модель Pydantic +class User(BaseModel): + id: int + name: str + joined: date +``` + +Приклад використання цієї моделі: + +```Python +my_user: User = User(id=3, name="John Doe", joined="2018-07-19") + +second_user_data = { + "id": 4, + "name": "Mary", + "joined": "2018-11-30", +} + +my_second_user: User = User(**second_user_data) +``` + +/// info | Інформація + +`**second_user_data` означає: + +Передати ключі та значення словника `second_user_data` як аргументи у вигляді "ключ-значення", еквівалентно `User(id=4, name="Mary", joined="2018-11-30")`. + +/// + +### Підтримка редакторів (IDE) + +Фреймворк спроєктований так, щоб бути легким і інтуїтивно зрозумілим. Усі рішення тестувалися у різних редакторах ще до початку розробки, щоб забезпечити найкращий досвід програмування. + +За результатами опитувань розробників Python однією з найпопулярніших функцій є "автодоповнення". + +**FastAPI** повністю підтримує автодоповнення у всіх місцях, тому вам рідко доведеться повертатися до документації. + +Приклад автодоповнення у редакторах: + +* у Visual Studio Code: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +* у PyCharm: + +![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png) + +### Короткий код +FastAPI має розумні налаштування **за замовчуванням**, але всі параметри можна налаштовувати відповідно до ваших потреб. Однак за замовчуванням все "просто працює". + +### Валідація +* Підтримка валідації для більшості (або всіх?) **типів даних Python**, зокрема: + * JSON-об'єктів (`dict`). + * JSON-списків (`list`) з визначенням типів елементів. + * Рядків (`str`) із мінімальною та максимальною довжиною. + * Чисел (`int`, `float`) з обмеженнями мінімальних та максимальних значень тощо. + +* Валідація складніших типів, таких як: + * URL. + * Email. + * UUID. + * ...та інші. + +Уся валідація виконується через надійний та перевірений **Pydantic**. + +### Безпека та автентифікація + +**FastAPI** підтримує вбудовану автентифікацію та авторизацію, без прив’язки до конкретних баз даних чи моделей даних. + +Підтримуються всі схеми безпеки OpenAPI, включаючи: + +* HTTP Basic. +* **OAuth2** (також із підтримкою **JWT-токенів**). Див. підручник: [OAuth2 із JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. +* Ключі API в: + * Заголовках. + * Параметрах запиту. + * Cookies тощо. + +А також усі можливості безпеки від Starlette (зокрема **сесійні cookies**). + +Усі вони створені як багаторазові інструменти та компоненти, які легко інтегруються з вашими системами, сховищами даних, реляційними та NoSQL базами даних тощо. + +### Впровадження залежностей + +**FastAPI** містить надзвичайно просту у використанні, але потужну систему впровадження залежностей. + +* Залежності можуть мати власні залежності, утворюючи ієрархію або **"граф залежностей"**. +* Усі залежності автоматично керуються фреймворком. +* Усі залежності можуть отримувати дані з запитів і розширювати **обмеження операції за шляхом** та автоматичну документацію. +* **Автоматична валідація** навіть для параметрів *операцій шляху*, визначених у залежностях. +* Підтримка складних систем автентифікації користувачів, **з'єднань із базами даних** тощо. +* **Жодних обмежень** щодо використання баз даних, фронтендів тощо, але водночас проста інтеграція з усіма ними. + +### Немає обмежень на "плагіни" + +Або іншими словами, вони не потрібні – просто імпортуйте та використовуйте необхідний код. + +Будь-яка інтеграція спроєктована настільки просто (з використанням залежностей), що ви можете створити "плагін" для свого застосунку всього у 2 рядках коду, використовуючи ту саму структуру та синтаксис, що й для ваших *операцій шляху*. + +### Протестовано + +* 100% покриття тестами. +* 100% анотована типами кодова база. +* Використовується у робочих середовищах. + +## Можливості Starlette + +**FastAPI** повністю сумісний із (та побудований на основі) Starlette. Тому будь-який додатковий код Starlette, який ви маєте, також працюватиме. + +**FastAPI** фактично є підкласом **Starlette**. Тому, якщо ви вже знайомі зі Starlette або використовуєте його, більшість функціональності працюватиме так само. + +З **FastAPI** ви отримуєте всі можливості **Starlette** (адже FastAPI — це, по суті, Starlette на стероїдах): + +* Разюча продуктивність. Це один із найшвидших фреймворків на Python, на рівні з **NodeJS** і **Go**. +* Підтримка **WebSocket**. +* Фонові задачі у процесі. +* Події запуску та завершення роботи. +* Клієнт для тестування, побудований на HTTPX. +* Підтримка **CORS**, **GZip**, статичних файлів, потокових відповідей. +* Підтримка **сесій** і **cookie**. +* 100% покриття тестами. +* 100% анотована типами кодова база. + +## Можливості Pydantic + +**FastAPI** повністю сумісний із (та побудований на основі) Pydantic. Тому будь-який додатковий код Pydantic, який ви маєте, також працюватиме. + +Включаючи зовнішні бібліотеки, побудовані також на Pydantic, такі як ORM, ODM для баз даних. + +Це також означає, що в багатьох випадках ви можете передати той самий об'єкт, який отримуєте з запиту, **безпосередньо в базу даних**, оскільки все автоматично перевіряється. + +Те ж саме відбувається й у зворотному напрямку — у багатьох випадках ви можете просто передати об'єкт, який отримуєте з бази даних, **безпосередньо клієнту**. + +З **FastAPI** ви отримуєте всі можливості **Pydantic** (адже FastAPI базується на Pydantic для обробки всіх даних): + +* **Ніякої плутанини** : + * Не потрібно вчити нову мову для визначення схем. + * Якщо ви знаєте типи Python, ви знаєте, як використовувати Pydantic. +* Легко працює з вашим **IDE/лінтером/мозком**: + * Оскільки структури даних Pydantic є просто екземплярами класів, які ви визначаєте; автодоповнення, лінтинг, mypy і ваша інтуїція повинні добре працювати з вашими перевіреними даними. +* Валідація **складних структур**: + * Використання ієрархічних моделей Pydantic. Python `typing`, `List` і `Dict` тощо. + * Валідатори дозволяють чітко і просто визначати, перевіряти й документувати складні схеми даних у вигляді JSON-схеми. + * Ви можете мати глибоко **вкладені JSON об'єкти** та перевірити та анотувати їх всі. +* **Розширюваність**: + * Pydantic дозволяє визначати користувацькі типи даних або розширювати валідацію методами в моделі декоратором `validator`. +* 100% покриття тестами. From 2d7d5dafb0ad59c0a19f996a85ec1210f80a141e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=C6=B0=C6=A1ng=20T=E1=BA=A5n=20Th=C3=A0nh?= <51350651+ptt3199@users.noreply.github.com> Date: Sat, 8 Feb 2025 05:09:16 +0700 Subject: [PATCH 772/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Vietnamese=20trans?= =?UTF-8?q?lation=20for=20`docs/vi/docs/fastapi-cli.md`=20(#13294)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/vi/docs/fastapi-cli.md | 75 +++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 docs/vi/docs/fastapi-cli.md diff --git a/docs/vi/docs/fastapi-cli.md b/docs/vi/docs/fastapi-cli.md new file mode 100644 index 000000000..d9e315ae4 --- /dev/null +++ b/docs/vi/docs/fastapi-cli.md @@ -0,0 +1,75 @@ +# FastAPI CLI + +**FastAPI CLI** là một chương trình dòng lệnh có thể được sử dụng để phục vụ ứng dụng FastAPI của bạn, quản lý dự án FastAPI của bạn và nhiều hoạt động khác. + +Khi bạn cài đặt FastAPI (vd với `pip install "fastapi[standard]"`), nó sẽ bao gồm một gói được gọi là `fastapi-cli`, gói này cung cấp lệnh `fastapi` trong terminal. + +Để chạy ứng dụng FastAPI của bạn cho quá trình phát triển (development), bạn có thể sử dụng lệnh `fastapi dev`: + +
    + +```console +$ fastapi dev main.py + + FastAPI Starting development server 🚀 + + Searching for package file structure from directories with + __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with the + following code: + + from main import app + + app Using import string: main:app + + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: + + 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 [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. +``` + +
    + +Chương trình dòng lệnh `fastapi` là **FastAPI CLI**. + +FastAPI CLI nhận đường dẫn đến chương trình Python của bạn (vd `main.py`) và tự động phát hiện đối tượng `FastAPI` (thường được gọi là `app`), xác định quá trình nhập đúng, và sau đó chạy nó (serve). + +Đối với vận hành thực tế (production), bạn sẽ sử dụng `fastapi run` thay thế. 🚀 + +Ở bên trong, **FastAPI CLI** sử dụng Uvicorn, một server ASGI có hiệu suất cao, sẵn sàng cho vận hành thực tế (production). 😎 + +## `fastapi dev` + +Chạy `fastapi dev` sẽ khởi động quá trình phát triển. + +Mặc định, **auto-reload** được bật, tự động tải lại server khi bạn thay đổi code của bạn. Điều này tốn nhiều tài nguyên và có thể kém ổn định hơn khi nó bị tắt. Bạn nên sử dụng nó cho quá trình phát triển. Nó cũng lắng nghe địa chỉ IP `127.0.0.1`, đó là địa chỉ IP của máy tính để tự giao tiếp với chính nó (`localhost`). + +## `fastapi run` + +Chạy `fastapi run` mặc định sẽ khởi động FastAPI cho quá trình vận hành thực tế. + +Mặc định, **auto-reload** bị tắt. Nó cũng lắng nghe địa chỉ IP `0.0.0.0`, đó là tất cả các địa chỉ IP có sẵn, như vậy nó sẽ được truy cập công khai bởi bất kỳ ai có thể giao tiếp với máy tính. Đây là cách bạn thường chạy nó trong sản phẩm hoàn thiện, ví dụ trong một container. + +Trong hầu hết các trường hợp, bạn sẽ (và nên) có một "proxy điểm cuối (termination proxy)" xử lý HTTPS cho bạn, điều này sẽ phụ thuộc vào cách bạn triển khai ứng dụng của bạn, nhà cung cấp có thể làm điều này cho bạn, hoặc bạn có thể cần thiết lập nó. + +/// tip + +Bạn có thể tìm hiểu thêm về FastAPI CLI trong [tài liệu triển khai](deployment/index.md){.internal-link target=_blank}. + +/// From 2bb94fb90bccd4a0545b477b67f6076ba2e2945c Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 7 Feb 2025 22:09:51 +0000 Subject: [PATCH 773/932] =?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 [skip ci] --- 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 b6145c9bb..75a024a0b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/features.md`. PR [#13308](https://github.com/fastapi/fastapi/pull/13308) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/learn/index.md`. PR [#13306](https://github.com/fastapi/fastapi/pull/13306) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Update Portuguese Translation for `docs/pt/docs/deployment/https.md`. PR [#13317](https://github.com/fastapi/fastapi/pull/13317) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Update Portuguese Translation for `docs/pt/docs/index.md`. PR [#13328](https://github.com/fastapi/fastapi/pull/13328) by [@ceb10n](https://github.com/ceb10n). From 50b307c9f68ad9a966e86d7f62c82d476abd0cc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 7 Feb 2025 22:10:25 +0000 Subject: [PATCH 774/932] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e=20-=20Contributors=20and=20Translators=20(#13293)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- docs/en/data/contributors.yml | 41 +++++--- docs/en/data/translation_reviewers.yml | 125 +++++++++++++++---------- docs/en/data/translators.yml | 45 +++++---- 3 files changed, 128 insertions(+), 83 deletions(-) diff --git a/docs/en/data/contributors.yml b/docs/en/data/contributors.yml index f679d7286..0e1a6505b 100644 --- a/docs/en/data/contributors.yml +++ b/docs/en/data/contributors.yml @@ -1,13 +1,18 @@ tiangolo: login: tiangolo - count: 697 + count: 713 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 url: https://github.com/tiangolo dependabot: login: dependabot - count: 89 + count: 90 avatarUrl: https://avatars.githubusercontent.com/in/29110?v=4 url: https://github.com/apps/dependabot +alejsdev: + login: alejsdev + count: 47 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 + url: https://github.com/alejsdev github-actions: login: github-actions count: 26 @@ -15,7 +20,7 @@ github-actions: url: https://github.com/apps/github-actions Kludex: login: Kludex - count: 22 + count: 23 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex pre-commit-ci: @@ -23,11 +28,6 @@ pre-commit-ci: count: 22 avatarUrl: https://avatars.githubusercontent.com/in/68672?v=4 url: https://github.com/apps/pre-commit-ci -alejsdev: - login: alejsdev - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 - url: https://github.com/alejsdev dmontagu: login: dmontagu count: 17 @@ -108,6 +108,11 @@ hitrust: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/3360631?u=5fa1f475ad784d64eb9666bdd43cc4d285dcc773&v=4 url: https://github.com/hitrust +ShahriyarR: + login: ShahriyarR + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/3852029?u=c9a1691e5ebdc94cbf543086099a6ed705cdb873&v=4 + url: https://github.com/ShahriyarR adriangb: login: adriangb count: 4 @@ -208,11 +213,6 @@ graingert: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/413772?u=64b77b6aa405c68a9c6bcf45f84257c66eea5f32&v=4 url: https://github.com/graingert -ShahriyarR: - login: ShahriyarR - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/3852029?u=c9a1691e5ebdc94cbf543086099a6ed705cdb873&v=4 - url: https://github.com/ShahriyarR jaystone776: login: jaystone776 count: 3 @@ -433,6 +433,11 @@ imba-tjd: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/24759802?u=01e901a4fe004b4b126549d3ff1c4000fe3720b5&v=4 url: https://github.com/imba-tjd +johnthagen: + login: johnthagen + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/10340167?u=47147fc4e4db1f573bee3fe428deeacb3197bc5f&v=4 + url: https://github.com/johnthagen paxcodes: login: paxcodes count: 2 @@ -443,6 +448,11 @@ kaustubhgupta: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/43691873?u=8dd738718ac7ffad4ef31e86b5d780a1141c695d&v=4 url: https://github.com/kaustubhgupta +kinuax: + login: kinuax + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/13321374?u=22dc9873d6d9f2c7e4fc44c6480c3505efb1531f&v=4 + url: https://github.com/kinuax wakabame: login: wakabame count: 2 @@ -503,3 +513,8 @@ AyushSinghal1794: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/89984761?v=4 url: https://github.com/AyushSinghal1794 +DanielKusyDev: + login: DanielKusyDev + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/36250676?u=2ea6114ff751fc48b55f231987a0e2582c6b1bd2&v=4 + url: https://github.com/DanielKusyDev diff --git a/docs/en/data/translation_reviewers.yml b/docs/en/data/translation_reviewers.yml index 6cc09a7c1..6f16893ba 100644 --- a/docs/en/data/translation_reviewers.yml +++ b/docs/en/data/translation_reviewers.yml @@ -5,12 +5,12 @@ s111d: url: https://github.com/s111d Xewus: login: Xewus - count: 139 + count: 140 avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 url: https://github.com/Xewus ceb10n: login: ceb10n - count: 108 + count: 110 avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 url: https://github.com/ceb10n tokusumi: @@ -33,21 +33,26 @@ AlertRED: count: 81 avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 url: https://github.com/AlertRED +nazarepiedady: + login: nazarepiedady + count: 81 + avatarUrl: https://avatars.githubusercontent.com/u/31008635?u=8dc25777dc9cb51fb0dbba2f137988953d330b78&v=4 + url: https://github.com/nazarepiedady sodaMelon: login: sodaMelon count: 81 avatarUrl: https://avatars.githubusercontent.com/u/66295123?u=be939db90f1119efee9e6110cc05066ff1f40f00&v=4 url: https://github.com/sodaMelon -nazarepiedady: - login: nazarepiedady - count: 78 - avatarUrl: https://avatars.githubusercontent.com/u/31008635?u=8dc25777dc9cb51fb0dbba2f137988953d330b78&v=4 - url: https://github.com/nazarepiedady Alexandrhub: login: Alexandrhub count: 68 avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 url: https://github.com/Alexandrhub +alv2017: + login: alv2017 + count: 64 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 waynerv: login: waynerv count: 63 @@ -55,7 +60,7 @@ waynerv: url: https://github.com/waynerv cassiobotaro: login: cassiobotaro - count: 61 + count: 62 avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=a08022b191ddbd0a6159b2981d9d878b6d5bb71f&v=4 url: https://github.com/cassiobotaro mattwang44: @@ -138,26 +143,21 @@ romashevchenko: count: 32 avatarUrl: https://avatars.githubusercontent.com/u/132477732?v=4 url: https://github.com/romashevchenko +alejsdev: + login: alejsdev + count: 32 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 + url: https://github.com/alejsdev wdh99: login: wdh99 count: 31 avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 url: https://github.com/wdh99 -alv2017: - login: alv2017 - count: 31 - avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 - url: https://github.com/alv2017 LorhanSohaky: login: LorhanSohaky count: 30 avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 url: https://github.com/LorhanSohaky -alejsdev: - login: alejsdev - count: 30 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 - url: https://github.com/alejsdev black-redoc: login: black-redoc count: 29 @@ -246,7 +246,7 @@ axel584: wisderfin: login: wisderfin count: 23 - avatarUrl: https://avatars.githubusercontent.com/u/77553770?u=94478d3e1ef7d36d70479c5bd35d8de28b071c10&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/77553770?u=f3b00a26736ba664e9927a1116c6e8088295e073&v=4 url: https://github.com/wisderfin rostik1410: login: rostik1410 @@ -353,6 +353,11 @@ mastizada: count: 16 avatarUrl: https://avatars.githubusercontent.com/u/1975818?u=0751a06d7271c8bf17cb73b1b845644ab4d2c6dc&v=4 url: https://github.com/mastizada +Joao-Pedro-P-Holanda: + login: Joao-Pedro-P-Holanda + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/110267046?u=331bd016326dac4cf3df4848f6db2dbbf8b5f978&v=4 + url: https://github.com/Joao-Pedro-P-Holanda JaeHyuckSa: login: JaeHyuckSa count: 16 @@ -363,11 +368,6 @@ Jedore: count: 15 avatarUrl: https://avatars.githubusercontent.com/u/17944025?u=81d503e1c800eb666b3861ca47a3a773bbc3f539&v=4 url: https://github.com/Jedore -Joao-Pedro-P-Holanda: - login: Joao-Pedro-P-Holanda - count: 15 - avatarUrl: https://avatars.githubusercontent.com/u/110267046?u=331bd016326dac4cf3df4848f6db2dbbf8b5f978&v=4 - url: https://github.com/Joao-Pedro-P-Holanda kim-sangah: login: kim-sangah count: 15 @@ -386,7 +386,7 @@ dukkee: mkdir700: login: mkdir700 count: 14 - avatarUrl: https://avatars.githubusercontent.com/u/56359329?u=0ba13427420e7f6e4c83947736de247326f2c292&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/56359329?u=3d6ea8714f5000829b60dcf7b13a75b1e73aaf47&v=4 url: https://github.com/mkdir700 BORA040126: login: BORA040126 @@ -473,6 +473,11 @@ kwang1215: count: 12 avatarUrl: https://avatars.githubusercontent.com/u/74170199?u=2a63ff6692119dde3f5e5693365b9fcd6f977b08&v=4 url: https://github.com/kwang1215 +Rishat-F: + login: Rishat-F + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/66554797?v=4 + url: https://github.com/Rishat-F AdrianDeAnda: login: AdrianDeAnda count: 11 @@ -513,6 +518,11 @@ KNChiu: count: 11 avatarUrl: https://avatars.githubusercontent.com/u/36751646?v=4 url: https://github.com/KNChiu +gitgernit: + login: gitgernit + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/129539613?u=d04f10143ab32c93f563ea14bf242d1d2bc991b0&v=4 + url: https://github.com/gitgernit mariacamilagl: login: mariacamilagl count: 10 @@ -538,6 +548,11 @@ RobotToI: count: 10 avatarUrl: https://avatars.githubusercontent.com/u/44951382?u=e41dbc19191ce7abed86694b1a44ea0523e1c60e&v=4 url: https://github.com/RobotToI +vitumenezes: + login: vitumenezes + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/9680878?u=05fd25cfafdc09382bf8907c37293a696c205754&v=4 + url: https://github.com/vitumenezes fcrozetta: login: fcrozetta count: 10 @@ -626,7 +641,7 @@ marcelomarkus: JoaoGustavoRogel: login: JoaoGustavoRogel count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/29525510?u=1dd3096c6c2be2576fd5e818b1be15b2c9768aa5&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/29525510?u=a0a91251f5e43e132608d55d28ccb8645c5ea405&v=4 url: https://github.com/JoaoGustavoRogel Zhongheng-Cheng: login: Zhongheng-Cheng @@ -673,11 +688,6 @@ camigomezdev: count: 8 avatarUrl: https://avatars.githubusercontent.com/u/16061815?u=25b5ebc042fff53fa03dc107ded10e36b1b7a5b9&v=4 url: https://github.com/camigomezdev -gitgernit: - login: gitgernit - count: 8 - avatarUrl: https://avatars.githubusercontent.com/u/129539613?u=d04f10143ab32c93f563ea14bf242d1d2bc991b0&v=4 - url: https://github.com/gitgernit Serrones: login: Serrones count: 7 @@ -698,11 +708,6 @@ anthonycepeda: count: 7 avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 url: https://github.com/anthonycepeda -vitumenezes: - login: vitumenezes - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/9680878?u=e7c6865aec49c3c94b8c8edc1198d1eac3e50b26&v=4 - url: https://github.com/vitumenezes fabioueno: login: fabioueno count: 7 @@ -956,7 +961,7 @@ devluisrodrigues: timothy-jeong: login: timothy-jeong count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/53824764?u=659311b6f6aeb0fbb8b527723fd4c83642f04327&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/53824764?u=db3d0cea2f5fab64d810113c5039a369699a2774&v=4 url: https://github.com/timothy-jeong lpdswing: login: lpdswing @@ -1053,6 +1058,11 @@ matiasbertani: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/65260383?u=d5edd86a6e2ab4fb1aab7751931fe045a963afd7&v=4 url: https://github.com/matiasbertani +k94-ishi: + login: k94-ishi + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/32672580?u=bc7c5c07af0656be9fe4f1784a444af8d81ded89&v=4 + url: https://github.com/k94-ishi javillegasna: login: javillegasna count: 4 @@ -1063,6 +1073,16 @@ javillegasna: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/174453744?v=4 url: https://github.com/9zimin9 +ilhamfadillah: + login: ilhamfadillah + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/20577838?u=c56192cf99b55affcaad408b240259c62e633450&v=4 + url: https://github.com/ilhamfadillah +Yarous: + login: Yarous + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/61277193?u=5b462347458a373b2d599c6f416d2b75eddbffad&v=4 + url: https://github.com/Yarous tyronedamasceno: login: tyronedamasceno count: 3 @@ -1151,7 +1171,7 @@ rafsaf: frnsimoes: login: frnsimoes count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/66239468?u=771c4b0c403a42ccf2676ac987ac4999e5ad09bc&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/66239468?u=a405e8f10654251e239a4a1d9dd5bda59216727d&v=4 url: https://github.com/frnsimoes lieryan: login: lieryan @@ -1283,11 +1303,16 @@ celestywang: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/184830753?v=4 url: https://github.com/celestywang -ilhamfadillah: - login: ilhamfadillah +RyaWcksn: + login: RyaWcksn count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/20577838?u=c56192cf99b55affcaad408b240259c62e633450&v=4 - url: https://github.com/ilhamfadillah + avatarUrl: https://avatars.githubusercontent.com/u/42831964?u=0cb4265faf3e3425a89e59b6fddd3eb2de180af0&v=4 + url: https://github.com/RyaWcksn +gerry-sabar: + login: gerry-sabar + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/1120123?v=4 + url: https://github.com/gerry-sabar blaisep: login: blaisep count: 2 @@ -1633,13 +1658,13 @@ logan2d5: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/146642263?u=dbd6621f8b0330d6919f6a7131277b92e26fbe87&v=4 url: https://github.com/logan2d5 -RyaWcksn: - login: RyaWcksn +tiaggo16: + login: tiaggo16 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/42831964?u=0cb4265faf3e3425a89e59b6fddd3eb2de180af0&v=4 - url: https://github.com/RyaWcksn -gerry-sabar: - login: gerry-sabar + avatarUrl: https://avatars.githubusercontent.com/u/62227573?u=359f4e2c51a4b13c8553ac5af405d635b07bb61f&v=4 + url: https://github.com/tiaggo16 +kiharito: + login: kiharito count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1120123?v=4 - url: https://github.com/gerry-sabar + avatarUrl: https://avatars.githubusercontent.com/u/38311245?v=4 + url: https://github.com/kiharito diff --git a/docs/en/data/translators.yml b/docs/en/data/translators.yml index 7b199dc08..13859044d 100644 --- a/docs/en/data/translators.yml +++ b/docs/en/data/translators.yml @@ -8,6 +8,11 @@ jaystone776: count: 46 avatarUrl: https://avatars.githubusercontent.com/u/11191137?u=299205a95e9b6817a43144a48b643346a5aac5cc&v=4 url: https://github.com/jaystone776 +ceb10n: + login: ceb10n + count: 26 + avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 + url: https://github.com/ceb10n tokusumi: login: tokusumi count: 23 @@ -23,11 +28,6 @@ hasansezertasan: count: 22 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan -ceb10n: - login: ceb10n - count: 22 - avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 - url: https://github.com/ceb10n waynerv: login: waynerv count: 20 @@ -55,7 +55,7 @@ Xewus: url: https://github.com/Xewus Joao-Pedro-P-Holanda: login: Joao-Pedro-P-Holanda - count: 12 + count: 13 avatarUrl: https://avatars.githubusercontent.com/u/110267046?u=331bd016326dac4cf3df4848f6db2dbbf8b5f978&v=4 url: https://github.com/Joao-Pedro-P-Holanda Smlep: @@ -78,6 +78,11 @@ Vincy1230: count: 9 avatarUrl: https://avatars.githubusercontent.com/u/81342412?u=ab5e256a4077a4a91f3f9cd2115ba80780454cbe&v=4 url: https://github.com/Vincy1230 +Zhongheng-Cheng: + login: Zhongheng-Cheng + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/95612344?u=a0f7730a3cc7486827965e01a119ad610bda4b0a&v=4 + url: https://github.com/Zhongheng-Cheng rjNemo: login: rjNemo count: 8 @@ -93,11 +98,6 @@ pablocm83: count: 8 avatarUrl: https://avatars.githubusercontent.com/u/28315068?u=3310fbb05bb8bfc50d2c48b6cb64ac9ee4a14549&v=4 url: https://github.com/pablocm83 -Zhongheng-Cheng: - login: Zhongheng-Cheng - count: 8 - avatarUrl: https://avatars.githubusercontent.com/u/95612344?u=a0f7730a3cc7486827965e01a119ad610bda4b0a&v=4 - url: https://github.com/Zhongheng-Cheng batlopes: login: batlopes count: 6 @@ -188,6 +188,11 @@ kwang1215: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/74170199?u=2a63ff6692119dde3f5e5693365b9fcd6f977b08&v=4 url: https://github.com/kwang1215 +alv2017: + login: alv2017 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 jfunez: login: jfunez count: 3 @@ -313,11 +318,11 @@ nahyunkeem: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/174440096?u=e12401d492eee58570f8914d0872b52e421a776e&v=4 url: https://github.com/nahyunkeem -alv2017: - login: alv2017 +gerry-sabar: + login: gerry-sabar count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 - url: https://github.com/alv2017 + avatarUrl: https://avatars.githubusercontent.com/u/1120123?v=4 + url: https://github.com/gerry-sabar izaguerreiro: login: izaguerreiro count: 2 @@ -481,10 +486,10 @@ saeye: timothy-jeong: login: timothy-jeong count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/53824764?u=659311b6f6aeb0fbb8b527723fd4c83642f04327&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/53824764?u=db3d0cea2f5fab64d810113c5039a369699a2774&v=4 url: https://github.com/timothy-jeong -gerry-sabar: - login: gerry-sabar +Rishat-F: + login: Rishat-F count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1120123?v=4 - url: https://github.com/gerry-sabar + avatarUrl: https://avatars.githubusercontent.com/u/66554797?v=4 + url: https://github.com/Rishat-F From 495ff5baa9694c773015abfaaf233a5b74ceaec5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 7 Feb 2025 22:10:37 +0000 Subject: [PATCH 775/932] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20GitHu?= =?UTF-8?q?b=20topic=20repositories=20(#13302)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions --- docs/en/data/topic_repos.yml | 334 +++++++++++++++++------------------ 1 file changed, 167 insertions(+), 167 deletions(-) diff --git a/docs/en/data/topic_repos.yml b/docs/en/data/topic_repos.yml index c1176e55c..302dc3bb5 100644 --- a/docs/en/data/topic_repos.yml +++ b/docs/en/data/topic_repos.yml @@ -1,495 +1,495 @@ - name: full-stack-fastapi-template html_url: https://github.com/fastapi/full-stack-fastapi-template - stars: 28796 + stars: 29409 owner_login: fastapi owner_html_url: https://github.com/fastapi - name: Hello-Python html_url: https://github.com/mouredev/Hello-Python - stars: 27554 + stars: 28113 owner_login: mouredev owner_html_url: https://github.com/mouredev - name: serve html_url: https://github.com/jina-ai/serve - stars: 21225 + stars: 21264 owner_login: jina-ai owner_html_url: https://github.com/jina-ai - name: sqlmodel html_url: https://github.com/fastapi/sqlmodel - stars: 14921 + stars: 15109 owner_login: fastapi owner_html_url: https://github.com/fastapi - name: HivisionIDPhotos html_url: https://github.com/Zeyi-Lin/HivisionIDPhotos - stars: 14025 + stars: 14564 owner_login: Zeyi-Lin owner_html_url: https://github.com/Zeyi-Lin - name: Douyin_TikTok_Download_API html_url: https://github.com/Evil0ctal/Douyin_TikTok_Download_API - stars: 10001 + stars: 10701 owner_login: Evil0ctal owner_html_url: https://github.com/Evil0ctal - name: fastapi-best-practices html_url: https://github.com/zhanymkanov/fastapi-best-practices - stars: 9820 + stars: 10180 owner_login: zhanymkanov owner_html_url: https://github.com/zhanymkanov - name: awesome-fastapi html_url: https://github.com/mjhea0/awesome-fastapi - stars: 8899 + stars: 9061 owner_login: mjhea0 owner_html_url: https://github.com/mjhea0 - name: FastUI html_url: https://github.com/pydantic/FastUI - stars: 8400 + stars: 8644 owner_login: pydantic owner_html_url: https://github.com/pydantic - name: nonebot2 html_url: https://github.com/nonebot/nonebot2 - stars: 6235 + stars: 6312 owner_login: nonebot owner_html_url: https://github.com/nonebot - name: serge html_url: https://github.com/serge-chat/serge - stars: 5685 + stars: 5686 owner_login: serge-chat owner_html_url: https://github.com/serge-chat -- name: fastapi-users - html_url: https://github.com/fastapi-users/fastapi-users - stars: 4787 - owner_login: fastapi-users - owner_html_url: https://github.com/fastapi-users - name: FileCodeBox html_url: https://github.com/vastsa/FileCodeBox - stars: 4479 + stars: 4933 owner_login: vastsa owner_html_url: https://github.com/vastsa +- name: fastapi-users + html_url: https://github.com/fastapi-users/fastapi-users + stars: 4849 + owner_login: fastapi-users + owner_html_url: https://github.com/fastapi-users - name: hatchet html_url: https://github.com/hatchet-dev/hatchet - stars: 4413 + stars: 4514 owner_login: hatchet-dev owner_html_url: https://github.com/hatchet-dev - name: chatgpt-web-share html_url: https://github.com/chatpire/chatgpt-web-share - stars: 4322 + stars: 4319 owner_login: chatpire owner_html_url: https://github.com/chatpire -- name: atrilabs-engine - html_url: https://github.com/Atri-Labs/atrilabs-engine - stars: 4115 - owner_login: Atri-Labs - owner_html_url: https://github.com/Atri-Labs +- name: polar + html_url: https://github.com/polarsource/polar + stars: 4216 + owner_login: polarsource + owner_html_url: https://github.com/polarsource - name: strawberry html_url: https://github.com/strawberry-graphql/strawberry - stars: 4084 + stars: 4126 owner_login: strawberry-graphql owner_html_url: https://github.com/strawberry-graphql +- name: atrilabs-engine + html_url: https://github.com/Atri-Labs/atrilabs-engine + stars: 4114 + owner_login: Atri-Labs + owner_html_url: https://github.com/Atri-Labs - name: dynaconf html_url: https://github.com/dynaconf/dynaconf - stars: 3844 + stars: 3874 owner_login: dynaconf owner_html_url: https://github.com/dynaconf - name: poem html_url: https://github.com/poem-web/poem - stars: 3698 + stars: 3746 owner_login: poem-web owner_html_url: https://github.com/poem-web -- name: polar - html_url: https://github.com/polarsource/polar - stars: 3355 - owner_login: polarsource - owner_html_url: https://github.com/polarsource - name: opyrator html_url: https://github.com/ml-tooling/opyrator - stars: 3114 + stars: 3117 owner_login: ml-tooling owner_html_url: https://github.com/ml-tooling - name: farfalle html_url: https://github.com/rashadphz/farfalle - stars: 3022 + stars: 3094 owner_login: rashadphz owner_html_url: https://github.com/rashadphz - name: fastapi-admin html_url: https://github.com/fastapi-admin/fastapi-admin - stars: 3002 + stars: 3040 owner_login: fastapi-admin owner_html_url: https://github.com/fastapi-admin - name: docarray html_url: https://github.com/docarray/docarray - stars: 2998 + stars: 3007 owner_login: docarray owner_html_url: https://github.com/docarray - name: datamodel-code-generator html_url: https://github.com/koxudaxi/datamodel-code-generator - stars: 2845 + stars: 2914 owner_login: koxudaxi owner_html_url: https://github.com/koxudaxi - name: fastapi-realworld-example-app html_url: https://github.com/nsidnev/fastapi-realworld-example-app - stars: 2832 + stars: 2840 owner_login: nsidnev owner_html_url: https://github.com/nsidnev -- name: uvicorn-gunicorn-fastapi-docker - html_url: https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker - stars: 2727 - owner_login: tiangolo - owner_html_url: https://github.com/tiangolo -- name: WrenAI - html_url: https://github.com/Canner/WrenAI - stars: 2699 - owner_login: Canner - owner_html_url: https://github.com/Canner - name: LitServe html_url: https://github.com/Lightning-AI/LitServe - stars: 2664 + stars: 2804 owner_login: Lightning-AI owner_html_url: https://github.com/Lightning-AI +- name: uvicorn-gunicorn-fastapi-docker + html_url: https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker + stars: 2730 + owner_login: tiangolo + owner_html_url: https://github.com/tiangolo - name: logfire html_url: https://github.com/pydantic/logfire - stars: 2495 + stars: 2620 owner_login: pydantic owner_html_url: https://github.com/pydantic - name: huma html_url: https://github.com/danielgtaylor/huma - stars: 2479 + stars: 2567 owner_login: danielgtaylor owner_html_url: https://github.com/danielgtaylor - name: tracecat html_url: https://github.com/TracecatHQ/tracecat - stars: 2446 + stars: 2494 owner_login: TracecatHQ owner_html_url: https://github.com/TracecatHQ -- name: RasaGPT - html_url: https://github.com/paulpierre/RasaGPT - stars: 2378 - owner_login: paulpierre - owner_html_url: https://github.com/paulpierre - name: best-of-web-python html_url: https://github.com/ml-tooling/best-of-web-python - stars: 2374 + stars: 2433 owner_login: ml-tooling owner_html_url: https://github.com/ml-tooling +- name: RasaGPT + html_url: https://github.com/paulpierre/RasaGPT + stars: 2386 + owner_login: paulpierre + owner_html_url: https://github.com/paulpierre - name: fastapi-react html_url: https://github.com/Buuntu/fastapi-react - stars: 2274 + stars: 2293 owner_login: Buuntu owner_html_url: https://github.com/Buuntu - name: nextpy html_url: https://github.com/dot-agent/nextpy - stars: 2244 + stars: 2256 owner_login: dot-agent owner_html_url: https://github.com/dot-agent - name: 30-Days-of-Python html_url: https://github.com/codingforentrepreneurs/30-Days-of-Python - stars: 2154 + stars: 2155 owner_login: codingforentrepreneurs owner_html_url: https://github.com/codingforentrepreneurs - name: FastAPI-template html_url: https://github.com/s3rius/FastAPI-template - stars: 2067 + stars: 2121 owner_login: s3rius owner_html_url: https://github.com/s3rius -- name: langserve - html_url: https://github.com/langchain-ai/langserve - stars: 1980 - owner_login: langchain-ai - owner_html_url: https://github.com/langchain-ai - name: sqladmin html_url: https://github.com/aminalaee/sqladmin - stars: 1980 + stars: 2021 owner_login: aminalaee owner_html_url: https://github.com/aminalaee +- name: langserve + html_url: https://github.com/langchain-ai/langserve + stars: 2006 + owner_login: langchain-ai + owner_html_url: https://github.com/langchain-ai - name: fastapi-utils html_url: https://github.com/fastapiutils/fastapi-utils - stars: 1970 + stars: 2002 owner_login: fastapiutils owner_html_url: https://github.com/fastapiutils - name: solara html_url: https://github.com/widgetti/solara - stars: 1950 + stars: 1967 owner_login: widgetti owner_html_url: https://github.com/widgetti -- name: python-week-2022 - html_url: https://github.com/rochacbruno/python-week-2022 - stars: 1836 - owner_login: rochacbruno - owner_html_url: https://github.com/rochacbruno - name: supabase-py html_url: https://github.com/supabase/supabase-py - stars: 1803 + stars: 1848 owner_login: supabase owner_html_url: https://github.com/supabase +- name: python-week-2022 + html_url: https://github.com/rochacbruno/python-week-2022 + stars: 1832 + owner_login: rochacbruno + owner_html_url: https://github.com/rochacbruno - name: mangum html_url: https://github.com/Kludex/mangum - stars: 1760 + stars: 1789 owner_login: Kludex owner_html_url: https://github.com/Kludex - name: manage-fastapi html_url: https://github.com/ycd/manage-fastapi - stars: 1704 + stars: 1711 owner_login: ycd owner_html_url: https://github.com/ycd - name: ormar html_url: https://github.com/collerek/ormar - stars: 1688 + stars: 1701 owner_login: collerek owner_html_url: https://github.com/collerek - name: agentkit html_url: https://github.com/BCG-X-Official/agentkit - stars: 1615 + stars: 1630 owner_login: BCG-X-Official owner_html_url: https://github.com/BCG-X-Official - name: langchain-serve html_url: https://github.com/jina-ai/langchain-serve - stars: 1615 + stars: 1617 owner_login: jina-ai owner_html_url: https://github.com/jina-ai - name: termpair html_url: https://github.com/cs01/termpair - stars: 1613 + stars: 1612 owner_login: cs01 owner_html_url: https://github.com/cs01 - name: coronavirus-tracker-api html_url: https://github.com/ExpDev07/coronavirus-tracker-api - stars: 1591 + stars: 1590 owner_login: ExpDev07 owner_html_url: https://github.com/ExpDev07 - name: piccolo html_url: https://github.com/piccolo-orm/piccolo - stars: 1477 + stars: 1519 owner_login: piccolo-orm owner_html_url: https://github.com/piccolo-orm - name: fastapi-crudrouter html_url: https://github.com/awtkns/fastapi-crudrouter - stars: 1435 + stars: 1449 owner_login: awtkns owner_html_url: https://github.com/awtkns - name: fastapi-cache html_url: https://github.com/long2ice/fastapi-cache - stars: 1412 + stars: 1447 owner_login: long2ice owner_html_url: https://github.com/long2ice - name: openapi-python-client html_url: https://github.com/openapi-generators/openapi-python-client - stars: 1398 + stars: 1434 owner_login: openapi-generators owner_html_url: https://github.com/openapi-generators - name: awesome-fastapi-projects html_url: https://github.com/Kludex/awesome-fastapi-projects - stars: 1386 + stars: 1398 owner_login: Kludex owner_html_url: https://github.com/Kludex - name: awesome-python-resources html_url: https://github.com/DjangoEx/awesome-python-resources - stars: 1371 + stars: 1380 owner_login: DjangoEx owner_html_url: https://github.com/DjangoEx - name: budgetml html_url: https://github.com/ebhy/budgetml - stars: 1342 + stars: 1344 owner_login: ebhy owner_html_url: https://github.com/ebhy - name: slowapi html_url: https://github.com/laurentS/slowapi - stars: 1289 + stars: 1339 owner_login: laurentS owner_html_url: https://github.com/laurentS - name: fastapi-pagination html_url: https://github.com/uriyyo/fastapi-pagination - stars: 1240 + stars: 1263 owner_login: uriyyo owner_html_url: https://github.com/uriyyo - name: fastapi-boilerplate html_url: https://github.com/teamhide/fastapi-boilerplate - stars: 1173 + stars: 1206 owner_login: teamhide owner_html_url: https://github.com/teamhide - name: fastapi-tutorial html_url: https://github.com/liaogx/fastapi-tutorial - stars: 1162 + stars: 1178 owner_login: liaogx owner_html_url: https://github.com/liaogx - name: fastapi-amis-admin html_url: https://github.com/amisadmin/fastapi-amis-admin - stars: 1118 + stars: 1142 owner_login: amisadmin owner_html_url: https://github.com/amisadmin - name: fastapi-code-generator html_url: https://github.com/koxudaxi/fastapi-code-generator - stars: 1095 + stars: 1119 owner_login: koxudaxi owner_html_url: https://github.com/koxudaxi - name: bolt-python html_url: https://github.com/slackapi/bolt-python - stars: 1086 + stars: 1116 owner_login: slackapi owner_html_url: https://github.com/slackapi - name: odmantic html_url: https://github.com/art049/odmantic - stars: 1085 + stars: 1096 owner_login: art049 owner_html_url: https://github.com/art049 - name: langchain-extract html_url: https://github.com/langchain-ai/langchain-extract - stars: 1068 + stars: 1093 owner_login: langchain-ai owner_html_url: https://github.com/langchain-ai - name: fastapi_production_template html_url: https://github.com/zhanymkanov/fastapi_production_template - stars: 1059 + stars: 1078 owner_login: zhanymkanov owner_html_url: https://github.com/zhanymkanov - name: fastapi-alembic-sqlmodel-async html_url: https://github.com/jonra1993/fastapi-alembic-sqlmodel-async - stars: 1031 + stars: 1055 owner_login: jonra1993 owner_html_url: https://github.com/jonra1993 +- name: Kokoro-FastAPI + html_url: https://github.com/remsky/Kokoro-FastAPI + stars: 1047 + owner_login: remsky + owner_html_url: https://github.com/remsky - name: prometheus-fastapi-instrumentator html_url: https://github.com/trallnag/prometheus-fastapi-instrumentator - stars: 1013 + stars: 1036 owner_login: trallnag owner_html_url: https://github.com/trallnag +- name: SurfSense + html_url: https://github.com/MODSetter/SurfSense + stars: 1018 + owner_login: MODSetter + owner_html_url: https://github.com/MODSetter +- name: bedrock-claude-chat + html_url: https://github.com/aws-samples/bedrock-claude-chat + stars: 1010 + owner_login: aws-samples + owner_html_url: https://github.com/aws-samples - name: runhouse html_url: https://github.com/run-house/runhouse - stars: 988 + stars: 1000 owner_login: run-house owner_html_url: https://github.com/run-house - name: lanarky html_url: https://github.com/ajndkr/lanarky - stars: 982 + stars: 986 owner_login: ajndkr owner_html_url: https://github.com/ajndkr - name: autollm html_url: https://github.com/viddexa/autollm - stars: 981 + stars: 982 owner_login: viddexa owner_html_url: https://github.com/viddexa -- name: bedrock-claude-chat - html_url: https://github.com/aws-samples/bedrock-claude-chat - stars: 977 - owner_login: aws-samples - owner_html_url: https://github.com/aws-samples -- name: SurfSense - html_url: https://github.com/MODSetter/SurfSense - stars: 971 - owner_login: MODSetter - owner_html_url: https://github.com/MODSetter - name: restish html_url: https://github.com/danielgtaylor/restish - stars: 954 + stars: 970 owner_login: danielgtaylor owner_html_url: https://github.com/danielgtaylor +- name: fastcrud + html_url: https://github.com/igorbenav/fastcrud + stars: 929 + owner_login: igorbenav + owner_html_url: https://github.com/igorbenav - name: secure html_url: https://github.com/TypeError/secure - stars: 911 + stars: 921 owner_login: TypeError owner_html_url: https://github.com/TypeError - name: langcorn html_url: https://github.com/msoedov/langcorn - stars: 909 + stars: 915 owner_login: msoedov owner_html_url: https://github.com/msoedov -- name: energy-forecasting - html_url: https://github.com/iusztinpaul/energy-forecasting - stars: 884 - owner_login: iusztinpaul - owner_html_url: https://github.com/iusztinpaul - name: vue-fastapi-admin html_url: https://github.com/mizhexiaoxiao/vue-fastapi-admin - stars: 863 + stars: 915 owner_login: mizhexiaoxiao owner_html_url: https://github.com/mizhexiaoxiao +- name: energy-forecasting + html_url: https://github.com/iusztinpaul/energy-forecasting + stars: 891 + owner_login: iusztinpaul + owner_html_url: https://github.com/iusztinpaul - name: authx html_url: https://github.com/yezz123/authx - stars: 850 + stars: 862 owner_login: yezz123 owner_html_url: https://github.com/yezz123 - name: titiler html_url: https://github.com/developmentseed/titiler - stars: 809 + stars: 823 owner_login: developmentseed owner_html_url: https://github.com/developmentseed - name: marker-api html_url: https://github.com/adithya-s-k/marker-api - stars: 792 + stars: 798 owner_login: adithya-s-k owner_html_url: https://github.com/adithya-s-k +- name: FastAPI-boilerplate + html_url: https://github.com/igorbenav/FastAPI-boilerplate + stars: 774 + owner_login: igorbenav + owner_html_url: https://github.com/igorbenav - name: fastapi_best_architecture html_url: https://github.com/fastapi-practices/fastapi_best_architecture - stars: 742 + stars: 766 owner_login: fastapi-practices owner_html_url: https://github.com/fastapi-practices - name: fastapi-mail html_url: https://github.com/sabuhish/fastapi-mail - stars: 728 + stars: 735 owner_login: sabuhish owner_html_url: https://github.com/sabuhish -- name: fastcrud - html_url: https://github.com/igorbenav/fastcrud - stars: 727 - owner_login: igorbenav - owner_html_url: https://github.com/igorbenav - name: annotated-py-projects html_url: https://github.com/hhstore/annotated-py-projects - stars: 722 + stars: 725 owner_login: hhstore owner_html_url: https://github.com/hhstore -- name: FastAPI-boilerplate - html_url: https://github.com/igorbenav/FastAPI-boilerplate - stars: 716 - owner_login: igorbenav - owner_html_url: https://github.com/igorbenav +- name: fastapi-do-zero + html_url: https://github.com/dunossauro/fastapi-do-zero + stars: 723 + owner_login: dunossauro + owner_html_url: https://github.com/dunossauro - name: lccn_predictor html_url: https://github.com/baoliay2008/lccn_predictor - stars: 707 + stars: 718 owner_login: baoliay2008 owner_html_url: https://github.com/baoliay2008 +- name: fastapi-observability + html_url: https://github.com/blueswen/fastapi-observability + stars: 718 + owner_login: blueswen + owner_html_url: https://github.com/blueswen - name: chatGPT-web html_url: https://github.com/mic1on/chatGPT-web - stars: 706 + stars: 708 owner_login: mic1on owner_html_url: https://github.com/mic1on -- name: fastapi-do-zero - html_url: https://github.com/dunossauro/fastapi-do-zero - stars: 702 - owner_login: dunossauro - owner_html_url: https://github.com/dunossauro +- name: learn-generative-ai + html_url: https://github.com/panaverse/learn-generative-ai + stars: 701 + owner_login: panaverse + owner_html_url: https://github.com/panaverse - name: linbing html_url: https://github.com/taomujian/linbing - stars: 699 + stars: 700 owner_login: taomujian owner_html_url: https://github.com/taomujian -- name: fastapi-observability - html_url: https://github.com/blueswen/fastapi-observability - stars: 698 - owner_login: blueswen - owner_html_url: https://github.com/blueswen - name: FastAPI-Backend-Template html_url: https://github.com/Aeternalis-Ingenium/FastAPI-Backend-Template - stars: 682 + stars: 692 owner_login: Aeternalis-Ingenium owner_html_url: https://github.com/Aeternalis-Ingenium -- name: learn-generative-ai - html_url: https://github.com/panaverse/learn-generative-ai - stars: 673 - owner_login: panaverse - owner_html_url: https://github.com/panaverse +- name: starlette-admin + html_url: https://github.com/jowilf/starlette-admin + stars: 692 + owner_login: jowilf + owner_html_url: https://github.com/jowilf - name: fastapi-jwt-auth html_url: https://github.com/IndominusByte/fastapi-jwt-auth - stars: 668 + stars: 674 owner_login: IndominusByte owner_html_url: https://github.com/IndominusByte - name: pity html_url: https://github.com/wuranxu/pity - stars: 660 + stars: 663 owner_login: wuranxu owner_html_url: https://github.com/wuranxu -- name: starlette-admin - html_url: https://github.com/jowilf/starlette-admin - stars: 653 - owner_login: jowilf - owner_html_url: https://github.com/jowilf - name: fastapi_login html_url: https://github.com/MushroomMaula/fastapi_login - stars: 650 + stars: 656 owner_login: MushroomMaula owner_html_url: https://github.com/MushroomMaula From b6b031b456d825fd8378d280d5d7d7c167784bb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 7 Feb 2025 22:10:51 +0000 Subject: [PATCH 776/932] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e=20-=20Experts=20(#13303)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- docs/en/data/people.yml | 130 +++++++++++++++++++++------------------- 1 file changed, 67 insertions(+), 63 deletions(-) diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml index 112567778..7f910ab34 100644 --- a/docs/en/data/people.yml +++ b/docs/en/data/people.yml @@ -13,7 +13,7 @@ experts: avatarUrl: https://avatars.githubusercontent.com/in/15368?v=4 url: https://github.com/apps/github-actions - login: Kludex - count: 644 + count: 645 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex - login: jgould22 @@ -116,6 +116,10 @@ experts: count: 39 avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 url: https://github.com/sinisaos +- login: luzzodev + count: 37 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 + url: https://github.com/luzzodev - login: chbndrhnns count: 37 avatarUrl: https://avatars.githubusercontent.com/u/7534547?v=4 @@ -124,10 +128,6 @@ experts: count: 37 avatarUrl: https://avatars.githubusercontent.com/u/5167622?u=de8f597c81d6336fcebc37b32dfd61a3f877160c&v=4 url: https://github.com/STeveShary -- login: luzzodev - count: 36 - avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 - url: https://github.com/luzzodev - login: krishnardt count: 35 avatarUrl: https://avatars.githubusercontent.com/u/31960541?u=47f4829c77f4962ab437ffb7995951e41eeebe9b&v=4 @@ -188,6 +188,10 @@ experts: count: 19 avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 url: https://github.com/estebanx64 +- login: sehraramiz + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 + url: https://github.com/sehraramiz - login: zoliknemet count: 18 avatarUrl: https://avatars.githubusercontent.com/u/22326718?u=31ba446ac290e23e56eea8e4f0c558aaf0b40779&v=4 @@ -196,10 +200,6 @@ experts: count: 18 avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4 url: https://github.com/retnikt -- login: sehraramiz - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 - url: https://github.com/sehraramiz - login: caeser1996 count: 17 avatarUrl: https://avatars.githubusercontent.com/u/16540232?u=05d2beb8e034d584d0a374b99d8826327bd7f614&v=4 @@ -224,6 +224,10 @@ experts: count: 16 avatarUrl: https://avatars.githubusercontent.com/u/41964673?u=9f2174f9d61c15c6e3a4c9e3aeee66f711ce311f&v=4 url: https://github.com/dstlny +- login: ceb10n + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 + url: https://github.com/ceb10n - login: jorgerpo count: 15 avatarUrl: https://avatars.githubusercontent.com/u/12537771?u=7444d20019198e34911082780cc7ad73f2b97cb3&v=4 @@ -240,13 +244,9 @@ experts: count: 15 avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 url: https://github.com/abhint -- login: pythonweb2 - count: 14 - avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 - url: https://github.com/pythonweb2 last_month_experts: - login: Kludex - count: 15 + count: 14 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex - login: YuriiMotov @@ -254,11 +254,11 @@ last_month_experts: avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov - login: sehraramiz - count: 8 + count: 7 avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 url: https://github.com/sehraramiz - login: luzzodev - count: 4 + count: 5 avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 url: https://github.com/luzzodev - login: yokwejuste @@ -269,6 +269,10 @@ last_month_experts: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 url: https://github.com/alv2017 +- login: Trinkes + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/9466879?v=4 + url: https://github.com/Trinkes - login: PREPONDERANCE count: 2 avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 @@ -287,19 +291,19 @@ last_month_experts: url: https://github.com/iloveitaly three_months_experts: - login: luzzodev - count: 34 + count: 33 avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 url: https://github.com/luzzodev - login: YuriiMotov - count: 33 + count: 31 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov - login: Kludex - count: 23 + count: 24 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex - login: sehraramiz - count: 10 + count: 11 avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 url: https://github.com/sehraramiz - login: estebanx64 @@ -326,6 +330,10 @@ three_months_experts: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/108818737?u=3d7ffe5808843ee4372f9cc5a559ff1674cf1792&v=4 url: https://github.com/viniciusCalcantara +- login: Trinkes + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/9466879?v=4 + url: https://github.com/Trinkes - login: PREPONDERANCE count: 2 avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 @@ -358,10 +366,6 @@ three_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/40732698?u=611f39d3c1d2f4207a590937a78c1f10eed6232c&v=4 url: https://github.com/gelezo43 -- login: dbfreem - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/9778569?u=f2f1e9135b5e4f1b0c6821a548b17f97572720fc&v=4 - url: https://github.com/dbfreem - login: AliYmn count: 2 avatarUrl: https://avatars.githubusercontent.com/u/18416653?u=98c1fca46c7e4dabe8c39d17b5e55d1511d41cf9&v=4 @@ -388,47 +392,47 @@ six_months_experts: avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov - login: Kludex - count: 39 + count: 40 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex +- login: luzzodev + count: 37 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 + url: https://github.com/luzzodev - login: sinisaos count: 37 avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 url: https://github.com/sinisaos -- login: luzzodev - count: 36 - avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 - url: https://github.com/luzzodev - login: JavierSanchezCastro count: 16 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro -- login: tiangolo - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 - url: https://github.com/tiangolo - login: Kfir-G count: 13 avatarUrl: https://avatars.githubusercontent.com/u/57500876?u=0cd29db046a17f12f382d398141319fca7ff230a&v=4 url: https://github.com/Kfir-G +- login: tiangolo + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo - login: sehraramiz - count: 10 + count: 11 avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 url: https://github.com/sehraramiz -- login: estebanx64 - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 - url: https://github.com/estebanx64 - login: ceb10n - count: 9 + count: 10 avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 url: https://github.com/ceb10n +- login: estebanx64 + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 - login: yvallois count: 6 avatarUrl: https://avatars.githubusercontent.com/u/36999744?v=4 url: https://github.com/yvallois - login: n8sty - count: 6 + count: 5 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty - login: TomFaulkner @@ -483,6 +487,10 @@ six_months_experts: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 url: https://github.com/svlandeg +- login: Trinkes + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/9466879?v=4 + url: https://github.com/Trinkes - login: PREPONDERANCE count: 2 avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 @@ -619,17 +627,13 @@ six_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 url: https://github.com/mattmess1221 -- login: meower1 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/109747197?u=0a5cc2a6ae74e558f0afc2874da85132e5953d8b&v=4 - url: https://github.com/meower1 one_year_experts: - login: YuriiMotov count: 223 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov - login: Kludex - count: 83 + count: 81 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex - login: JavierSanchezCastro @@ -645,7 +649,7 @@ one_year_experts: avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 url: https://github.com/sinisaos - login: luzzodev - count: 36 + count: 37 avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 url: https://github.com/luzzodev - login: tiangolo @@ -660,18 +664,18 @@ one_year_experts: count: 19 avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 url: https://github.com/estebanx64 +- login: ceb10n + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 + url: https://github.com/ceb10n - login: sehraramiz - count: 14 + count: 15 avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 url: https://github.com/sehraramiz - login: PhysicallyActive count: 14 avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 url: https://github.com/PhysicallyActive -- login: ceb10n - count: 14 - avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 - url: https://github.com/ceb10n - login: Kfir-G count: 13 avatarUrl: https://avatars.githubusercontent.com/u/57500876?u=0cd29db046a17f12f382d398141319fca7ff230a&v=4 @@ -812,6 +816,18 @@ one_year_experts: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=d87b866e7c1db970d6f8e8031643818349b046d5&v=4 url: https://github.com/ahmedabdou14 +- login: Trinkes + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/9466879?v=4 + url: https://github.com/Trinkes +- login: Leon0824 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1922026?v=4 + url: https://github.com/Leon0824 +- login: CarlosOliveira-23 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/102637302?u=cf350a4db956f30cbb2c27d3be0d15c282e32b14&v=4 + url: https://github.com/CarlosOliveira-23 - login: nbx3 count: 2 avatarUrl: https://avatars.githubusercontent.com/u/34649527?u=943812f69e0d40adbd3fa1c9b8ef50dd971a2a45&v=4 @@ -832,10 +848,6 @@ one_year_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4 url: https://github.com/slafs -- login: CarlosOliveira-23 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/102637302?u=cf350a4db956f30cbb2c27d3be0d15c282e32b14&v=4 - url: https://github.com/CarlosOliveira-23 - login: monchin count: 2 avatarUrl: https://avatars.githubusercontent.com/u/18521800?v=4 @@ -844,10 +856,6 @@ one_year_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/38752106?u=07f80e451bda00a9492bbc764e49d24ad3ada8cc&v=4 url: https://github.com/AmirHmZz -- login: Leon0824 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1922026?v=4 - url: https://github.com/Leon0824 - login: iloveitaly count: 2 avatarUrl: https://avatars.githubusercontent.com/u/150855?v=4 @@ -860,7 +868,3 @@ one_year_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/11828278?u=6bcadc5ce4f2f56a514331c9f68eb987d4afe29a&v=4 url: https://github.com/shurshilov -- login: LincolnPuzey - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/18750802?v=4 - url: https://github.com/LincolnPuzey From 27d0ccc11cd3621890d24cac0d9236cb4b040081 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 7 Feb 2025 22:11:28 +0000 Subject: [PATCH 777/932] =?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 [skip ci] --- 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 75a024a0b..ac7111cf2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Vietnamese translation for `docs/vi/docs/fastapi-cli.md`. PR [#13294](https://github.com/fastapi/fastapi/pull/13294) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Ukrainian translation for `docs/uk/docs/features.md`. PR [#13308](https://github.com/fastapi/fastapi/pull/13308) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/learn/index.md`. PR [#13306](https://github.com/fastapi/fastapi/pull/13306) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Update Portuguese Translation for `docs/pt/docs/deployment/https.md`. PR [#13317](https://github.com/fastapi/fastapi/pull/13317) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). From 25ee2357d767eaaf46f334c4aecb2fd008703cdc Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 7 Feb 2025 22:12:00 +0000 Subject: [PATCH 778/932] =?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 [skip ci] --- 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 ac7111cf2..7d063b168 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -18,6 +18,7 @@ hide: ### Internal +* 👥 Update FastAPI People - Contributors and Translators. PR [#13293](https://github.com/fastapi/fastapi/pull/13293) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump inline-snapshot from 0.18.1 to 0.19.3. PR [#13298](https://github.com/fastapi/fastapi/pull/13298) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Update sponsors, add Permit. PR [#13288](https://github.com/fastapi/fastapi/pull/13288) by [@tiangolo](https://github.com/tiangolo). From 6e8da9d00a6df82edb1c0179d2c14f07818b378b Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 7 Feb 2025 22:13:23 +0000 Subject: [PATCH 779/932] =?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 [skip ci] --- 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 7d063b168..485454f6a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -18,6 +18,7 @@ hide: ### Internal +* 👥 Update FastAPI GitHub topic repositories. PR [#13302](https://github.com/fastapi/fastapi/pull/13302) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI People - Contributors and Translators. PR [#13293](https://github.com/fastapi/fastapi/pull/13293) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump inline-snapshot from 0.18.1 to 0.19.3. PR [#13298](https://github.com/fastapi/fastapi/pull/13298) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Update sponsors, add Permit. PR [#13288](https://github.com/fastapi/fastapi/pull/13288) by [@tiangolo](https://github.com/tiangolo). From 640a5b6fc3204e953ae82bb99c66d7c0995c5e44 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 7 Feb 2025 22:14:11 +0000 Subject: [PATCH 780/932] =?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 [skip ci] --- 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 485454f6a..18ef5911c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -18,6 +18,7 @@ hide: ### Internal +* 👥 Update FastAPI People - Experts. PR [#13303](https://github.com/fastapi/fastapi/pull/13303) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI GitHub topic repositories. PR [#13302](https://github.com/fastapi/fastapi/pull/13302) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI People - Contributors and Translators. PR [#13293](https://github.com/fastapi/fastapi/pull/13293) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump inline-snapshot from 0.18.1 to 0.19.3. PR [#13298](https://github.com/fastapi/fastapi/pull/13298) by [@dependabot[bot]](https://github.com/apps/dependabot). From e814707cd1daebcdd765e80a35316f8316496b30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 7 Feb 2025 22:15:49 +0000 Subject: [PATCH 781/932] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e=20-=20Sponsors=20(#13295)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions --- docs/en/data/github_sponsors.yml | 63 ++++++++++++++++++++------------ 1 file changed, 39 insertions(+), 24 deletions(-) diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml index 55fe3dda9..feb4e727f 100644 --- a/docs/en/data/github_sponsors.yml +++ b/docs/en/data/github_sponsors.yml @@ -2,6 +2,9 @@ sponsors: - - login: bump-sh avatarUrl: https://avatars.githubusercontent.com/u/33217836?v=4 url: https://github.com/bump-sh + - login: renderinc + avatarUrl: https://avatars.githubusercontent.com/u/36424661?v=4 + url: https://github.com/renderinc - login: Nixtla avatarUrl: https://avatars.githubusercontent.com/u/79945230?v=4 url: https://github.com/Nixtla @@ -20,9 +23,6 @@ sponsors: - login: zuplo avatarUrl: https://avatars.githubusercontent.com/u/85497839?v=4 url: https://github.com/zuplo - - login: render-sponsorships - avatarUrl: https://avatars.githubusercontent.com/u/189296666?v=4 - url: https://github.com/render-sponsorships - login: porter-dev avatarUrl: https://avatars.githubusercontent.com/u/62078005?v=4 url: https://github.com/porter-dev @@ -44,6 +44,9 @@ sponsors: - login: databento avatarUrl: https://avatars.githubusercontent.com/u/64141749?v=4 url: https://github.com/databento + - login: permitio + avatarUrl: https://avatars.githubusercontent.com/u/71775833?v=4 + url: https://github.com/permitio - - login: mercedes-benz avatarUrl: https://avatars.githubusercontent.com/u/34240465?v=4 url: https://github.com/mercedes-benz @@ -95,9 +98,6 @@ sponsors: - - login: samuelcolvin avatarUrl: https://avatars.githubusercontent.com/u/4039449?u=42eb3b833047c8c4b4f647a031eaef148c16d93f&v=4 url: https://github.com/samuelcolvin - - login: vincentkoc - avatarUrl: https://avatars.githubusercontent.com/u/25068?u=cbf098fc04c0473523d373b0dd2145b4ec99ef93&v=4 - url: https://github.com/vincentkoc - login: ProteinQure avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 url: https://github.com/ProteinQure @@ -107,6 +107,9 @@ sponsors: - login: otosky avatarUrl: https://avatars.githubusercontent.com/u/42260747?u=69d089387c743d89427aa4ad8740cfb34045a9e0&v=4 url: https://github.com/otosky + - login: khadrawy + avatarUrl: https://avatars.githubusercontent.com/u/13686061?u=59f25ef42ecf04c22657aac4238ce0e2d3d30304&v=4 + url: https://github.com/khadrawy - login: mjohnsey avatarUrl: https://avatars.githubusercontent.com/u/16784016?u=38fad2e6b411244560b3af99c5f5a4751bc81865&v=4 url: https://github.com/mjohnsey @@ -215,6 +218,9 @@ sponsors: - login: anomaly avatarUrl: https://avatars.githubusercontent.com/u/3654837?v=4 url: https://github.com/anomaly + - login: vincentkoc + avatarUrl: https://avatars.githubusercontent.com/u/25068?u=fbd5b2d51142daa4bdbc21e21953a3b8b8188a4a&v=4 + url: https://github.com/vincentkoc - login: jstanden avatarUrl: https://avatars.githubusercontent.com/u/63288?u=c3658d57d2862c607a0e19c2101c3c51876e36ad&v=4 url: https://github.com/jstanden @@ -248,6 +254,9 @@ sponsors: - login: TrevorBenson avatarUrl: https://avatars.githubusercontent.com/u/9167887?u=dccbea3327a57750923333d8ebf1a0b3f1948949&v=4 url: https://github.com/TrevorBenson + - login: kaangiray26 + avatarUrl: https://avatars.githubusercontent.com/u/11297495?u=e85327a77db45906d44f3ff06dd7f3303c644096&v=4 + url: https://github.com/kaangiray26 - login: wdwinslow avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4 url: https://github.com/wdwinslow @@ -263,9 +272,9 @@ sponsors: - login: dannywade avatarUrl: https://avatars.githubusercontent.com/u/13680237?u=418ee985bd41577b20fde81417fb2d901e875e8a&v=4 url: https://github.com/dannywade - - login: khadrawy - avatarUrl: https://avatars.githubusercontent.com/u/13686061?u=59f25ef42ecf04c22657aac4238ce0e2d3d30304&v=4 - url: https://github.com/khadrawy + - login: gorhack + avatarUrl: https://avatars.githubusercontent.com/u/4141690?u=ec119ebc4bdf00a7bc84657a71aa17834f4f27f3&v=4 + url: https://github.com/gorhack - login: Ryandaydev avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 url: https://github.com/Ryandaydev @@ -314,9 +323,9 @@ sponsors: - login: mobyw avatarUrl: https://avatars.githubusercontent.com/u/44370805?v=4 url: https://github.com/mobyw - - login: ArtyomVancyan - avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4 - url: https://github.com/ArtyomVancyan + - login: PelicanQ + avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4 + url: https://github.com/PelicanQ - login: TheR1D avatarUrl: https://avatars.githubusercontent.com/u/16740832?u=b0dfdbdb27b79729430c71c6128962f77b7b53f7&v=4 url: https://github.com/TheR1D @@ -341,6 +350,9 @@ sponsors: - login: dvlpjrs avatarUrl: https://avatars.githubusercontent.com/u/32254642?u=fbd6ad0324d4f1eb6231cf775be1c7bd4404e961&v=4 url: https://github.com/dvlpjrs + - login: ArtyomVancyan + avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4 + url: https://github.com/ArtyomVancyan - login: caviri avatarUrl: https://avatars.githubusercontent.com/u/45425937?u=4e14bd64282bad8f385eafbdb004b5a279366d6e&v=4 url: https://github.com/caviri @@ -356,9 +368,6 @@ sponsors: - login: PunRabbit avatarUrl: https://avatars.githubusercontent.com/u/70463212?u=1a835cfbc99295a60c8282f6aa6199d1b42241a5&v=4 url: https://github.com/PunRabbit - - login: PelicanQ - avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4 - url: https://github.com/PelicanQ - login: tochikuji avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4 url: https://github.com/tochikuji @@ -380,9 +389,9 @@ sponsors: - login: Alisa-lisa avatarUrl: https://avatars.githubusercontent.com/u/4137964?u=e7e393504f554f4ff15863a1e01a5746863ef9ce&v=4 url: https://github.com/Alisa-lisa - - login: Graeme22 - avatarUrl: https://avatars.githubusercontent.com/u/4185684?u=498182a42300d7bcd4de1215190cb17eb501136c&v=4 - url: https://github.com/Graeme22 + - login: hcristea + avatarUrl: https://avatars.githubusercontent.com/u/7814406?u=61d7a4fcf846983a4606788eac25e1c6c1209ba8&v=4 + url: https://github.com/hcristea - login: ddanier avatarUrl: https://avatars.githubusercontent.com/u/113563?u=ed1dc79de72f93bd78581f88ebc6952b62f472da&v=4 url: https://github.com/ddanier @@ -434,6 +443,9 @@ sponsors: - login: artempronevskiy avatarUrl: https://avatars.githubusercontent.com/u/12235104?u=03df6e1e55c9c6fe5d230adabb8dd7d43d8bbe8f&v=4 url: https://github.com/artempronevskiy + - login: Graeme22 + avatarUrl: https://avatars.githubusercontent.com/u/4185684?u=498182a42300d7bcd4de1215190cb17eb501136c&v=4 + url: https://github.com/Graeme22 - login: danielunderwood avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4 url: https://github.com/danielunderwood @@ -458,9 +470,6 @@ sponsors: - login: harsh183 avatarUrl: https://avatars.githubusercontent.com/u/7780198?v=4 url: https://github.com/harsh183 - - login: hcristea - avatarUrl: https://avatars.githubusercontent.com/u/7814406?u=61d7a4fcf846983a4606788eac25e1c6c1209ba8&v=4 - url: https://github.com/hcristea - - login: larsyngvelundin avatarUrl: https://avatars.githubusercontent.com/u/34173819?u=74958599695bf83ac9f1addd935a51548a10c6b0&v=4 url: https://github.com/larsyngvelundin @@ -479,9 +488,15 @@ sponsors: - login: FabulousCodingFox avatarUrl: https://avatars.githubusercontent.com/u/78906517?u=924a27cbee3db7e0ece5cc1509921402e1445e74&v=4 url: https://github.com/FabulousCodingFox - - login: anqorithm - avatarUrl: https://avatars.githubusercontent.com/u/61029571?u=468256fa4e2d9ce2870b608299724bebb7a33f18&v=4 - url: https://github.com/anqorithm + - login: gateremark + avatarUrl: https://avatars.githubusercontent.com/u/91592218?u=969314eb2cfb035196f4d19499ec6f5050d7583a&v=4 + url: https://github.com/gateremark + - login: morzan1001 + avatarUrl: https://avatars.githubusercontent.com/u/47593005?u=c30ab7230f82a12a9b938dcb54f84a996931409a&v=4 + url: https://github.com/morzan1001 + - login: Toothwitch + avatarUrl: https://avatars.githubusercontent.com/u/1710406?u=5eebb23b46cd26e48643b9e5179536cad491c17a&v=4 + url: https://github.com/Toothwitch - login: ssbarnea avatarUrl: https://avatars.githubusercontent.com/u/102495?u=c7bd9ddf127785286fc939dd18cb02db0a453bce&v=4 url: https://github.com/ssbarnea From 38d409dd67513de0983814f7b5e1918c6ed1521e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=C6=B0=C6=A1ng=20T=E1=BA=A5n=20Th=C3=A0nh?= <51350651+ptt3199@users.noreply.github.com> Date: Sat, 8 Feb 2025 05:17:13 +0700 Subject: [PATCH 782/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Vietnamese=20trans?= =?UTF-8?q?lation=20for=20`docs/vi/docs/environment-variables.md`=20(#1328?= =?UTF-8?q?7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/vi/docs/environment-variables.md | 300 ++++++++++++++++++++++++++ 1 file changed, 300 insertions(+) create mode 100644 docs/vi/docs/environment-variables.md diff --git a/docs/vi/docs/environment-variables.md b/docs/vi/docs/environment-variables.md new file mode 100644 index 000000000..dd06f8959 --- /dev/null +++ b/docs/vi/docs/environment-variables.md @@ -0,0 +1,300 @@ +# Biến môi trường (Environment Variables) + +/// tip + +Nếu bạn đã biết về "biến môi trường" và cách sử dụng chúng, bạn có thể bỏ qua phần này. + +/// + +Một biến môi trường (còn được gọi là "**env var**") là một biến mà tồn tại **bên ngoài** đoạn mã Python, ở trong **hệ điều hành**, và có thể được đọc bởi đoạn mã Python của bạn (hoặc bởi các chương trình khác). + +Các biến môi trường có thể được sử dụng để xử lí **các thiết lập** của ứng dụng, như một phần của **các quá trình cài đặt** Python, v.v. + +## Tạo và Sử dụng các Biến Môi Trường + +Bạn có thể **tạo** và sử dụng các biến môi trường trong **shell (terminal)**, mà không cần sử dụng Python: + +//// tab | Linux, macOS, Windows Bash + +
    + +```console +// Bạn có thể tạo một biến môi trường MY_NAME với +$ export MY_NAME="Wade Wilson" + +// Sau đó bạn có thể sử dụng nó với các chương trình khác, như +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
    + +//// + +//// tab | Windows PowerShell + +
    + +```console +// Tạo một biến môi trường MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Sử dụng nó với các chương trình khác, như là +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
    + +//// + +## Đọc các Biến Môi Trường trong Python + +Bạn cũng có thể tạo các biến môi trường **bên ngoài** đoạn mã Python, trong terminal (hoặc bằng bất kỳ phương pháp nào khác), và sau đó **đọc chúng trong Python**. + +Ví dụ, bạn có một file `main.py` với: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +Tham số thứ hai cho `os.getenv()` là giá trị mặc định để trả về. + +Nếu không được cung cấp, nó mặc định là `None`, ở đây chúng ta cung cấp `"World"` là giá trị mặc định để sử dụng. + +/// + +Sau đó bạn có thể gọi chương trình Python: + +//// tab | Linux, macOS, Windows Bash + +
    + +```console +// Ở đây chúng ta chưa cài đặt biến môi trường +$ python main.py + +// Vì chúng ta chưa cài đặt biến môi trường, chúng ta nhận được giá trị mặc định + +Hello World from Python + +// Nhưng nếu chúng ta tạo một biến môi trường trước đó +$ export MY_NAME="Wade Wilson" + +// Và sau đó gọi chương trình lại +$ python main.py + +// Bây giờ nó có thể đọc biến môi trường + +Hello Wade Wilson from Python +``` + +
    + +//// + +//// tab | Windows PowerShell + +
    + +```console +// Ở đây chúng ta chưa cài đặt biến môi trường +$ python main.py + +// Vì chúng ta chưa cài đặt biến môi trường, chúng ta nhận được giá trị mặc định + +Hello World from Python + +// Nhưng nếu chúng ta tạo một biến môi trường trước đó +$ $Env:MY_NAME = "Wade Wilson" + +// Và sau đó gọi chương trình lại +$ python main.py + +// Bây giờ nó có thể đọc biến môi trường + +Hello Wade Wilson from Python +``` + +
    + +//// + +Vì các biến môi trường có thể được tạo bên ngoài đoạn mã Python, nhưng có thể được đọc bởi đoạn mã Python, và không cần được lưu trữ (commit vào `git`) cùng với các file khác, nên chúng thường được sử dụng để lưu các thiết lập hoặc **cấu hình**. + +Bạn cũng có thể tạo ra một biến môi trường dành riêng cho một **lần gọi chương trình**, chỉ có thể được sử dụng bởi chương trình đó, và chỉ trong thời gian chạy của chương trình. + +Để làm điều này, tạo nó ngay trước chương trình đó, trên cùng một dòng: + +
    + +```console +// Tạo một biến môi trường MY_NAME cho lần gọi chương trình này +$ MY_NAME="Wade Wilson" python main.py + +// Bây giờ nó có thể đọc biến môi trường + +Hello Wade Wilson from Python + +// Biến môi trường không còn tồn tại sau đó +$ python main.py + +Hello World from Python +``` + +
    + +/// tip + +Bạn có thể đọc thêm về điều này tại The Twelve-Factor App: Config. + +/// + +## Các Kiểu (Types) và Kiểm tra (Validation) + +Các biến môi trường có thể chỉ xử lí **chuỗi ký tự**, vì chúng nằm bên ngoài đoạn mã Python và phải tương thích với các chương trình khác và phần còn lại của hệ thống (và thậm chí với các hệ điều hành khác, như Linux, Windows, macOS). + +Điều này có nghĩa là **bất kỳ giá trị nào** được đọc trong Python từ một biến môi trường **sẽ là một `str`**, và bất kỳ hành động chuyển đổi sang kiểu dữ liệu khác hoặc hành động kiểm tra nào cũng phải được thực hiện trong đoạn mã. + +Bạn sẽ học thêm về việc sử dụng biến môi trường để xử lí **các thiết lập ứng dụng** trong [Hướng dẫn nâng cao - Các thiết lập và biến môi trường](./advanced/settings.md){.internal-link target=_blank}. + +## Biến môi trường `PATH` + +Có một biến môi trường **đặc biệt** được gọi là **`PATH`** được sử dụng bởi các hệ điều hành (Linux, macOS, Windows) nhằm tìm các chương trình để thực thi. + +Giá trị của biến môi trường `PATH` là một chuỗi dài được tạo bởi các thư mục được phân tách bởi dấu hai chấm `:` trên Linux và macOS, và bởi dấu chấm phẩy `;` trên Windows. + +Ví dụ, biến môi trường `PATH` có thể có dạng như sau: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Điều này có nghĩa là hệ thống sẽ tìm kiếm các chương trình trong các thư mục: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +Điều này có nghĩa là hệ thống sẽ tìm kiếm các chương trình trong các thư mục: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +Khi bạn gõ một **lệnh** trong terminal, hệ điều hành **tìm kiếm** chương trình trong **mỗi thư mục** được liệt kê trong biến môi trường `PATH`. + +Ví dụ, khi bạn gõ `python` trong terminal, hệ điều hành tìm kiếm một chương trình được gọi `python` trong **thư mục đầu tiên** trong danh sách đó. + +Nếu tìm thấy, nó sẽ **sử dụng** nó. Nếu không tìm thấy, nó sẽ tiếp tục tìm kiếm trong **các thư mục khác**. + +### Cài đặt Python và cập nhật biến môi trường `PATH` + +Khi bạn cài đặt Python, bạn có thể được hỏi nếu bạn muốn cập nhật biến môi trường `PATH`. + +//// tab | Linux, macOS + +Giả sử bạn cài đặt Python vào thư mục `/opt/custompython/bin`. + +Nếu bạn chọn cập nhật biến môi trường `PATH`, thì cài đặt sẽ thêm `/opt/custompython/bin` vào biến môi trường `PATH`. + +Nó có thể có dạng như sau: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +Như vậy, khi bạn gõ `python` trong terminal, hệ thống sẽ tìm thấy chương trình Python trong `/opt/custompython/bin` (thư mục cuối) và sử dụng nó. + +//// + +//// tab | Windows + +Giả sử bạn cài đặt Python vào thư mục `C:\opt\custompython\bin`. + +Nếu bạn chọn cập nhật biến môi trường `PATH`, thì cài đặt sẽ thêm `C:\opt\custompython\bin` vào biến môi trường `PATH`. + +Nó có thể có dạng như sau: + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +Như vậy, khi bạn gõ `python` trong terminal, hệ thống sẽ tìm thấy chương trình Python trong `C:\opt\custompython\bin` (thư mục cuối) và sử dụng nó. + +//// + +Vậy, nếu bạn gõ: + +
    + +```console +$ python +``` + +
    + +//// tab | Linux, macOS + +Hệ thống sẽ **tìm kiếm** chương trình `python` trong `/opt/custompython/bin` và thực thi nó. + +Nó tương đương với việc bạn gõ: + +
    + +```console +$ /opt/custompython/bin/python +``` + +
    + +//// + +//// tab | Windows + +Hệ thống sẽ **tìm kiếm** chương trình `python` trong `C:\opt\custompython\bin\python` và thực thi nó. + +Nó tương đương với việc bạn gõ: + +
    + +```console +$ C:\opt\custompython\bin\python +``` + +
    + +//// + +Thông tin này sẽ hữu ích khi bạn học về [Môi trường ảo](virtual-environments.md){.internal-link target=_blank}. + +## Kết luận + +Với những thông tin này, bạn có thể hiểu được **các biến môi trường là gì** và **cách sử dụng chúng trong Python**. + +Bạn có thể đọc thêm về chúng tại Wikipedia cho Biến môi trường. + +Trong nhiều trường hợp, cách các biến môi trường trở nên hữu ích và có thể áp dụng không thực sự rõ ràng ngay từ đầu, nhưng chúng sẽ liên tục xuất hiện trong rất nhiều tình huống khi bạn phát triển ứng dụng, vì vậy việc hiểu biết về chúng là hữu ích. + +Chẳng hạn, bạn sẽ cần những thông tin này khi bạn học về [Môi trường ảo](virtual-environments.md). From f9352c18de97dc8867e69c3a0695092495c2ff1f Mon Sep 17 00:00:00 2001 From: Valentyn Date: Sat, 8 Feb 2025 00:17:53 +0200 Subject: [PATCH 783/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/tutorial/static-files.md`=20(#13285?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/uk/docs/tutorial/static-files.md | 40 +++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 docs/uk/docs/tutorial/static-files.md diff --git a/docs/uk/docs/tutorial/static-files.md b/docs/uk/docs/tutorial/static-files.md new file mode 100644 index 000000000..a84782d8f --- /dev/null +++ b/docs/uk/docs/tutorial/static-files.md @@ -0,0 +1,40 @@ +# Статичні файли + +Ви можете автоматично надавати статичні файли з каталогу, використовуючи `StaticFiles`. + +## Використання `StaticFiles` + +* Імпортуйте `StaticFiles`. +* "Під'єднати" екземпляр `StaticFiles()` з вказанням необхідного шляху. + +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} + +/// note | Технічні деталі + +Ви також можете використовувати `from starlette.staticfiles import StaticFiles`. + +**FastAPI** надає той самий `starlette.staticfiles`, що й `fastapi.staticfiles` для зручності розробників. Але фактично він безпосередньо походить із Starlette. + +/// + +### Що таке "Під'єднання" + +"Під'єднання" означає додавання повноцінного "незалежного" застосунку за певним шляхом, який потім обробляє всі під шляхи. + +Це відрізняється від використання `APIRouter`, оскільки під'єднаний застосунок є повністю незалежним. OpenAPI та документація вашого основного застосунку не будуть знати нічого про ваш під'єднаний застосунок. + +Ви можете дізнатися більше про це в [Посібнику для просунутих користувачів](../advanced/index.md){.internal-link target=_blank}. + +## Деталі + +Перше `"/static"` вказує на під шлях, за яким буде "під'єднано" цей новий "застосунок". Тому будь-який шлях, який починається з `"/static"`, буде оброблятися ним. + +`directory="static"` визначає каталог, що містить ваші статичні файли. + +`name="static"` це ім'я, яке можна використовувати всередині **FastAPI**. + +Усі ці параметри можуть бути змінені відповідно до потреб і особливостей вашого застосунку. + +## Додаткова інформація + +Детальніше про налаштування та можливості можна дізнатися в документації Starlette про статичні файли. From 8a6d81afad05ad57efbce7d72bf5d803029b93bc Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 7 Feb 2025 22:17:59 +0000 Subject: [PATCH 784/932] =?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 [skip ci] --- 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 18ef5911c..c52fb0f63 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -18,6 +18,7 @@ hide: ### Internal +* 👥 Update FastAPI People - Sponsors. PR [#13295](https://github.com/fastapi/fastapi/pull/13295) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI People - Experts. PR [#13303](https://github.com/fastapi/fastapi/pull/13303) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI GitHub topic repositories. PR [#13302](https://github.com/fastapi/fastapi/pull/13302) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI People - Contributors and Translators. PR [#13293](https://github.com/fastapi/fastapi/pull/13293) by [@tiangolo](https://github.com/tiangolo). From e86ef5e57d17be4e868b495102961b59844bd879 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=C6=B0=C6=A1ng=20T=E1=BA=A5n=20Th=C3=A0nh?= <51350651+ptt3199@users.noreply.github.com> Date: Sat, 8 Feb 2025 05:19:18 +0700 Subject: [PATCH 785/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Vietnamese=20trans?= =?UTF-8?q?lation=20for=20`docs/vi/docs/virtual-environments.md`=20(#13282?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/vi/docs/virtual-environments.md | 842 +++++++++++++++++++++++++++ 1 file changed, 842 insertions(+) create mode 100644 docs/vi/docs/virtual-environments.md diff --git a/docs/vi/docs/virtual-environments.md b/docs/vi/docs/virtual-environments.md new file mode 100644 index 000000000..22d8e153e --- /dev/null +++ b/docs/vi/docs/virtual-environments.md @@ -0,0 +1,842 @@ +# Môi trường ảo (Virtual Environments) + +Khi bạn làm việc trong các dự án Python, bạn có thể sử dụng một **môi trường ảo** (hoặc một cơ chế tương tự) để cách ly các gói bạn cài đặt cho mỗi dự án. + +/// info +Nếu bạn đã biết về các môi trường ảo, cách tạo chúng và sử dụng chúng, bạn có thể bỏ qua phần này. 🤓 + +/// + +/// tip + +Một **môi trường ảo** khác với một **biến môi trường (environment variable)**. + +Một **biến môi trường** là một biến trong hệ thống có thể được sử dụng bởi các chương trình. + +Một **môi trường ảo** là một thư mục với một số tệp trong đó. + +/// + +/// info + +Trang này sẽ hướng dẫn bạn cách sử dụng các **môi trường ảo** và cách chúng hoạt động. + +Nếu bạn đã sẵn sàng sử dụng một **công cụ có thể quản lý tất cả mọi thứ** cho bạn (bao gồm cả việc cài đặt Python), hãy thử uv. + +/// + +## Tạo một Dự án + +Đầu tiên, tạo một thư mục cho dự án của bạn. + +Cách tôi thường làm là tạo một thư mục có tên `code` trong thư mục `home/user`. + +Và trong thư mục đó, tôi tạo một thư mục cho mỗi dự án. + +
    + +```console +// Đi đến thư mục home +$ cd +// Tạo một thư mục cho tất cả các dự án của bạn +$ mkdir code +// Vào thư mục code +$ cd code +// Tạo một thư mục cho dự án này +$ mkdir awesome-project +// Vào thư mục dự án +$ cd awesome-project +``` + +
    + +## Tạo một Môi trường ảo + +Khi bạn bắt đầu làm việc với một dự án Python **trong lần đầu**, hãy tạo một môi trường ảo **trong thư mục dự án của bạn**. + +/// tip + +Bạn cần làm điều này **một lần cho mỗi dự án**, không phải mỗi khi bạn làm việc. +/// + +//// tab | `venv` + +Để tạo một môi trường ảo, bạn có thể sử dụng module `venv` có sẵn của Python. + +
    + +```console +$ python -m venv .venv +``` + +
    + +/// details | Cách các lệnh hoạt động + +* `python`: sử dụng chương trình `python` +* `-m`: gọi một module như một script, chúng ta sẽ nói về module đó sau +* `venv`: sử dụng module `venv` được cài đặt sẵn của Python +* `.venv`: tạo môi trường ảo trong thư mục mới `.venv` + +/// + +//// + +//// tab | `uv` + +Nếu bạn có `uv` được cài đặt, bạn có thể sử dụng nó để tạo một môi trường ảo. + +
    + +```console +$ uv venv +``` + +
    + +/// tip + +Mặc định, `uv` sẽ tạo một môi trường ảo trong một thư mục có tên `.venv`. + +Nhưng bạn có thể tùy chỉnh nó bằng cách thêm một đối số với tên thư mục. + +/// + +//// + +Lệnh này tạo một môi trường ảo mới trong một thư mục có tên `.venv`. + +/// details | `.venv` hoặc tên khác + +Bạn có thể tạo môi trường ảo trong một thư mục khác, nhưng thường người ta quy ước đặt nó là `.venv`. + +/// + +## Kích hoạt Môi trường ảo + +Kích hoạt môi trường ảo mới để bất kỳ lệnh Python nào bạn chạy hoặc gói nào bạn cài đặt sẽ sử dụng nó. + +/// tip + +Làm điều này **mỗi khi** bạn bắt đầu một **phiên terminal mới** để làm việc trên dự án. + +/// + +//// tab | Linux, macOS + +
    + +```console +$ source .venv/bin/activate +``` + +
    + +//// + +//// tab | Windows PowerShell + +
    + +```console +$ .venv\Scripts\Activate.ps1 +``` + +
    + +//// + +//// tab | Windows Bash + +Nếu bạn sử dụng Bash cho Windows (ví dụ: Git Bash): + +
    + +```console +$ source .venv/Scripts/activate +``` + +
    + +//// + +/// tip + +Mỗi khi bạn cài đặt thêm một **package mới** trong môi trường đó, hãy **kích hoạt** môi trường đó lại. + +Điều này đảm bảo rằng khi bạn sử dụng một **chương trình dòng lệnh (CLI)** được cài đặt từ gói đó, bạn sẽ dùng bản cài đặt từ môi trường ảo của mình thay vì bản được cài đặt toàn cục khác có thể có phiên bản khác với phiên bản bạn cần. + +/// + +## Kiểm tra xem Môi trường ảo đã được Kích hoạt chưa + +Kiểm tra xem môi trường ảo đã được kích hoạt chưa (lệnh trước đó đã hoạt động). + +/// tip + +Điều này là **không bắt buộc**, nhưng nó là một cách tốt để **kiểm tra** rằng mọi thứ đang hoạt động như mong đợi và bạn đang sử dụng đúng môi trường ảo mà bạn đã định. + +/// + +//// tab | Linux, macOS, Windows Bash + +
    + +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
    + +Nếu nó hiển thị `python` binary tại `.venv/bin/python`, trong dự án của bạn (trong trường hợp `awesome-project`), thì tức là nó hoạt động. 🎉 + +//// + +//// tab | Windows PowerShell + +
    + +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
    + +Nếu nó hiển thị `python` binary tại `.venv\Scripts\python`, trong dự án của bạn (trong trường hợp `awesome-project`), thì tức là nó hoạt động. 🎉 + +//// + +## Nâng cấp `pip` + +/// tip + +Nếu bạn sử dụng `uv` bạn sử dụng nó để cài đặt thay vì `pip`, thì bạn không cần cập nhật `pip`. 😎 + +/// + +Nếu bạn sử dụng `pip` để cài đặt gói (nó được cài đặt mặc định với Python), bạn nên **nâng cấp** nó lên phiên bản mới nhất. + +Nhiều lỗi khác nhau trong khi cài đặt gói được giải quyết chỉ bằng cách nâng cấp `pip` trước. + +/// tip + +Bạn thường làm điều này **một lần**, ngay sau khi bạn tạo môi trường ảo. + +/// + +Đảm bảo rằng môi trường ảo đã được kích hoạt (với lệnh trên) và sau đó chạy: + +
    + +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
    + +## Thêm `.gitignore` + +Nếu bạn sử dụng **Git** (nên làm), hãy thêm một file `.gitignore` để Git bỏ qua mọi thứ trong `.venv`. + +/// tip + +Nếu bạn sử dụng `uv` để tạo môi trường ảo, nó đã tự động làm điều này cho bạn, bạn có thể bỏ qua bước này. 😎 + +/// + +/// tip + +Làm điều này **một lần**, ngay sau khi bạn tạo môi trường ảo. + +/// + +
    + +```console +$ echo "*" > .venv/.gitignore +``` + +
    + +/// details | Cách lệnh hoạt động + +* `echo "*"`: sẽ "in" văn bản `*` trong terminal (phần tiếp theo sẽ thay đổi điều đó một chút) +* `>`: bất kỳ văn bản nào được in ra terminal bởi lệnh trước `>` không được in ra mà thay vào đó được viết vào file ở phía bên phải của `>` +* `.gitignore`: tên của file mà văn bản sẽ được viết vào + +Và `*` với Git có nghĩa là "mọi thứ". Vì vậy, nó sẽ bỏ qua mọi thứ trong thư mục `.venv`. + +Lệnh này sẽ tạo một file `.gitignore` với nội dung: + +```gitignore +* +``` + +/// + +## Cài đặt gói (packages) + +Sau khi kích hoạt môi trường, bạn có thể cài đặt các gói trong đó. + +/// tip + +Thực hiện điều này **một lần** khi cài đặt hoặc cập nhật gói cần thiết cho dự án của bạn. + +Nếu bạn cần cập nhật phiên bản hoặc thêm một gói mới, bạn sẽ **thực hiện điều này lại**. + +/// + +### Cài đặt gói trực tiếp + +Nếu bạn cần cập nhật phiên bản hoặc thêm một gói mới, bạn sẽ **thực hiện điều này lại**. + +/// tip +Để quản lý dự án tốt hơn, hãy liệt kê tất cả các gói và phiên bản cần thiết trong một file (ví dụ `requirements.txt` hoặc `pyproject.toml`). + +/// + +//// tab | `pip` + +
    + +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
    + +//// + +//// tab | `uv` + +Nếu bạn có `uv`: + +
    + +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
    + +//// + +### Cài đặt từ `requirements.txt` + +Nếu bạn có một tệp `requirements.txt`, bạn có thể sử dụng nó để cài đặt các gói. + +//// tab | `pip` + +
    + +```console +$ pip install -r requirements.txt +---> 100% +``` + +
    + +//// + +//// tab | `uv` + +Nếu bạn có `uv`: + +
    + +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
    + +//// + +/// details | `requirements.txt` + +Một tệp `requirements.txt` với một số gói sẽ trông như thế này: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## Chạy Chương trình của bạn + +Sau khi kích hoạt môi trường ảo, bạn có thể chạy chương trình của mình, nó sẽ sử dụng Python trong môi trường ảo của bạn với các gói bạn đã cài đặt. + +
    + +```console +$ python main.py + +Hello World +``` + +
    + +## Cấu hình Trình soạn thảo của bạn + +Nếu bạn sử dụng một trình soạn thảo, hãy đảm bảo bạn cấu hình nó để sử dụng cùng môi trường ảo mà bạn đã tạo (trình soạn thảo sẽ tự động phát hiện môi trường ảo) để bạn có thể nhận được tính năng tự động hoàn thành câu lệnh (autocomplete) và in lỗi trực tiếp trong trình soạn thảo (inline errors). + +Ví dụ: + +* VS Code +* PyCharm + +/// tip + +Bạn thường chỉ cần làm điều này **một lần**, khi bạn tạo môi trường ảo. + +/// + +## Huỷ kích hoạt Môi trường ảo + +Khi bạn hoàn tất việc làm trên dự án của bạn, bạn có thể **huỷ kích hoạt** môi trường ảo. + +
    + +```console +$ deactivate +``` + +
    + +Như vậy, khi bạn chạy `python`, nó sẽ không chạy từ môi trường ảo đó với các gói đã cài đặt. + +## Sẵn sàng để Làm việc + +Bây giờ bạn đã sẵn sàng để làm việc trên dự án của mình rồi đấy. + +/// tip + +Bạn muốn hiểu tất cả những gì ở trên? + +Tiếp tục đọc. 👇🤓 + +/// + +## Tại sao cần Môi trường ảo + +Để làm việc với FastAPI, bạn cần cài đặt Python. + +Sau đó, bạn sẽ cần **cài đặt** FastAPI và bất kỳ **gói** nào mà bạn muốn sử dụng. + +Để cài đặt gói, bạn thường sử dụng lệnh `pip` có sẵn với Python (hoặc các phiên bản tương tự). + +Tuy nhiên, nếu bạn sử dụng `pip` trực tiếp, các gói sẽ được cài đặt trong **môi trường Python toàn cục** của bạn (phần cài đặt toàn cục của Python). + +### Vấn đề + +Vậy, vấn đề gì khi cài đặt gói trong môi trường Python toàn cục? + +Trong một vài thời điểm, bạn sẽ phải viết nhiều chương trình khác nhau phụ thuộc vào **các gói khác nhau**. Và một số dự án bạn thực hiện lại phụ thuộc vào **các phiên bản khác nhau** của cùng một gói. 😱 + +Ví dụ, bạn có thể tạo một dự án được gọi là `philosophers-stone`, chương trình này phụ thuộc vào một gói khác được gọi là **`harry`, sử dụng phiên bản `1`**. Vì vậy, bạn cần cài đặt `harry`. + +```mermaid +flowchart LR + stone(philosophers-stone) -->|phụ thuộc| harry-1[harry v1] +``` + +Sau đó, vào một vài thời điểm sau, bạn tạo một dự án khác được gọi là `prisoner-of-azkaban`, và dự án này cũng phụ thuộc vào `harry`, nhưng dự án này cần **`harry` phiên bản `3`**. + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |phụ thuộc| harry-3[harry v3] +``` + +Bây giờ, vấn đề là, nếu bạn cài đặt các gói toàn cục (trong môi trường toàn cục) thay vì trong một **môi trường ảo cục bộ**, bạn sẽ phải chọn phiên bản `harry` nào để cài đặt. + +Nếu bạn muốn chạy `philosophers-stone` bạn sẽ cần phải cài đặt `harry` phiên bản `1`, ví dụ với: + +
    + +```console +$ pip install "harry==1" +``` + +
    + +Và sau đó bạn sẽ có `harry` phiên bản `1` được cài đặt trong môi trường Python toàn cục của bạn. + +```mermaid +flowchart LR + subgraph global[môi trường toàn cục] + harry-1[harry v1] + end + subgraph stone-project[dự án philosophers-stone ] + stone(philosophers-stone) -->|phụ thuộc| harry-1 + end +``` + +Nhưng sau đó, nếu bạn muốn chạy `prisoner-of-azkaban`, bạn sẽ cần phải gỡ bỏ `harry` phiên bản `1` và cài đặt `harry` phiên bản `3` (hoặc chỉ cần cài đặt phiên bản `3` sẽ tự động gỡ bỏ phiên bản `1`). + +
    + +```console +$ pip install "harry==3" +``` + +
    + +Và sau đó bạn sẽ có `harry` phiên bản `3` được cài đặt trong môi trường Python toàn cục của bạn. + +Và nếu bạn cố gắng chạy `philosophers-stone` lại, có khả năng nó sẽ **không hoạt động** vì nó cần `harry` phiên bản `1`. + +```mermaid +flowchart LR + subgraph global[môi trường toàn cục] + harry-1[harry v1] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[dự án philosophers-stone ] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[dự án prisoner-of-azkaban ] + azkaban(prisoner-of-azkaban) --> |phụ thuộc| harry-3 + end +``` + +/// tip + +Mặc dù các gói Python thường cố gắng **tránh các thay đổi làm hỏng code** trong **phiên bản mới**, nhưng để đảm bảo an toàn, bạn nên chủ động cài đặt phiên bản mới và chạy kiểm thử để xác nhận mọi thứ vẫn hoạt động đúng. + +/// + +Bây giờ, hãy hình dung về **nhiều** gói khác nhau mà tất cả các dự án của bạn phụ thuộc vào. Rõ ràng rất khó để quản lý. Điều này dẫn tới việc là bạn sẽ có nhiều dự án với **các phiên bản không tương thích** của các gói, và bạn có thể không biết tại sao một số thứ không hoạt động. + +Hơn nữa, tuỳ vào hệ điều hành của bạn (vd Linux, Windows, macOS), có thể đã có Python được cài đặt sẵn. Trong trường hợp ấy, một vài gói nhiều khả năng đã được cài đặt trước với các phiên bản **cần thiết cho hệ thống của bạn**. Nếu bạn cài đặt các gói trong môi trường Python toàn cục, bạn có thể sẽ **phá vỡ** một số chương trình đã được cài đặt sẵn cùng hệ thống. + +## Nơi các Gói được Cài đặt + +Khi bạn cài đặt Python, nó sẽ tạo ra một vài thư mục và tệp trong máy tính của bạn. + +Một vài thư mục này là những thư mục chịu trách nhiệm có tất cả các gói bạn cài đặt. + +Khi bạn chạy: + +
    + +```console +// Đừng chạy lệnh này ngay, đây chỉ là một ví dụ 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
    + +Lệnh này sẽ tải xuống một tệp nén với mã nguồn FastAPI, thường là từ PyPI. + +Nó cũng sẽ **tải xuống** các tệp cho các gói khác mà FastAPI phụ thuộc vào. + +Sau đó, nó sẽ **giải nén** tất cả các tệp đó và đưa chúng vào một thư mục trong máy tính của bạn. + +Mặc định, nó sẽ đưa các tệp đã tải xuống và giải nén vào thư mục được cài đặt cùng Python của bạn, đó là **môi trường toàn cục**. + +## Những Môi trường ảo là gì? + +Cách giải quyết cho vấn đề có tất cả các gói trong môi trường toàn cục là sử dụng một **môi trường ảo cho mỗi dự án** bạn làm việc. + +Một môi trường ảo là một **thư mục**, rất giống với môi trường toàn cục, trong đó bạn có thể cài đặt các gói cho một dự án. + +Vì vậy, mỗi dự án sẽ có một môi trường ảo riêng của nó (thư mục `.venv`) với các gói riêng của nó. + +```mermaid +flowchart TB + subgraph stone-project[dự án philosophers-stone ] + stone(philosophers-stone) --->|phụ thuộc| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[dự án prisoner-of-azkaban ] + azkaban(prisoner-of-azkaban) --->|phụ thuộc| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## Kích hoạt Môi trường ảo nghĩa là gì + +Khi bạn kích hoạt một môi trường ảo, ví dụ với: + +//// tab | Linux, macOS + +
    + +```console +$ source .venv/bin/activate +``` + +
    + +//// + +//// tab | Windows PowerShell + +
    + +```console +$ .venv\Scripts\Activate.ps1 +``` + +
    + +//// + +//// tab | Windows Bash + +Nếu bạn sử dụng Bash cho Windows (ví dụ Git Bash): + +
    + +```console +$ source .venv/Scripts/activate +``` + +
    + +//// + +Lệnh này sẽ tạo hoặc sửa đổi một số [biến môi trường](environment-variables.md){.internal-link target=_blank} mà sẽ được sử dụng cho các lệnh tiếp theo. + +Một trong số đó là biến `PATH`. + +/// tip + +Bạn có thể tìm hiểu thêm về biến `PATH` trong [Biến môi trường](environment-variables.md#path-environment-variable){.internal-link target=_blank} section. + +/// + +Kích hoạt môi trường ảo thêm đường dẫn `.venv/bin` (trên Linux và macOS) hoặc `.venv\Scripts` (trên Windows) vào biến `PATH`. + +Giả sử rằng trước khi kích hoạt môi trường, biến `PATH` như sau: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +Nghĩa là hệ thống sẽ tìm kiếm chương trình trong: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +Nghĩa là hệ thống sẽ tìm kiếm chương trình trong: + +* `C:\Windows\System32` + +//// + +Sau khi kích hoạt môi trường ảo, biến `PATH` sẽ như sau: + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Nghĩa là hệ thống sẽ bắt đầu tìm kiếm chương trình trong: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +trước khi tìm kiếm trong các thư mục khác. + +Vì vậy, khi bạn gõ `python` trong terminal, hệ thống sẽ tìm thấy chương trình Python trong: + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +và sử dụng chương trình đó. + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +Nghĩa là hệ thống sẽ bắt đầu tìm kiếm chương trình trong: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +trước khi tìm kiếm trong các thư mục khác. + +Vì vậy, khi bạn gõ `python` trong terminal, hệ thống sẽ tìm thấy chương trình Python trong: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +và sử dụng chương trình đó. + +//// + +Một chi tiết quan trọng là nó sẽ đưa địa chỉ của môi trường ảo vào **đầu** của biến `PATH`. Hệ thống sẽ tìm kiếm nó **trước** khi tìm kiếm bất kỳ Python nào khác có sẵn. Vì vậy, khi bạn chạy `python`, nó sẽ sử dụng Python **từ môi trường ảo** thay vì bất kỳ Python nào khác (ví dụ, Python từ môi trường toàn cục). + +Kích hoạt một môi trường ảo cũng thay đổi một vài thứ khác, nhưng đây là một trong những điều quan trọng nhất mà nó thực hiện. + +## Kiểm tra một Môi trường ảo + +Khi bạn kiểm tra một môi trường ảo đã được kích hoạt chưa, ví dụ với: + +//// tab | Linux, macOS, Windows Bash + +
    + +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
    + +//// + +//// tab | Windows PowerShell + +
    + +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
    + +//// + + +Điều đó có nghĩa là chương trình `python` sẽ được sử dụng là chương trình **trong môi trường ảo**. + +Bạn sử dụng `which` trên Linux và macOS và `Get-Command` trên Windows PowerShell. + +Cách hoạt động của lệnh này là nó sẽ đi và kiểm tra biến `PATH`, đi qua **mỗi đường dẫn theo thứ tự**, tìm kiếm chương trình được gọi là `python`. Khi nó tìm thấy nó, nó sẽ **hiển thị cho bạn đường dẫn** đến chương trình đó. + +Điều quan trọng nhất là khi bạn gọi `python`, đó chính là chương trình `python` được thực thi. + +Vì vậy, bạn có thể xác nhận nếu bạn đang ở trong môi trường ảo đúng. + +/// tip + +Dễ dàng kích hoạt một môi trường ảo, cài đặt Python, và sau đó **chuyển đến một dự án khác**. + +Và dự án thứ hai **sẽ không hoạt động** vì bạn đang sử dụng **Python không đúng**, từ một môi trường ảo cho một dự án khác. + +Thật tiện lợi khi có thể kiểm tra `python` nào đang được sử dụng 🤓 + +/// + +## Tại sao lại Huỷ kích hoạt một Môi trường ảo + +Ví dụ, bạn có thể làm việc trên một dự án `philosophers-stone`, **kích hoạt môi trường ảo**, cài đặt các gói và làm việc với môi trường ảo đó. + +Sau đó, bạn muốn làm việc trên **dự án khác** `prisoner-of-azkaban`. + +Bạn đi đến dự án đó: + +
    + +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
    + +Nếu bạn không tắt môi trường ảo cho `philosophers-stone`, khi bạn chạy `python` trong terminal, nó sẽ cố gắng sử dụng Python từ `philosophers-stone`. + +
    + +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// Lỗi khi import sirius, nó không được cài đặt 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
    + +Nếu bạn huỷ kích hoạt môi trường ảo hiện tại và kích hoạt môi trường ảo mới cho `prisoner-of-azkaban`, khi bạn chạy `python`, nó sẽ sử dụng Python từ môi trường ảo trong `prisoner-of-azkaban`. + +
    + +```console +$ cd ~/code/prisoner-of-azkaban + +// Bạn không cần phải ở trong thư mục trước để huỷ kích hoạt, bạn có thể làm điều đó ở bất kỳ đâu, ngay cả sau khi đi đến dự án khác 😎 +$ deactivate + +// Kích hoạt môi trường ảo trong prisoner-of-azkaban/.venv 🚀 +$ source .venv/bin/activate + +// Bây giờ khi bạn chạy python, nó sẽ tìm thấy gói sirius được cài đặt trong môi trường ảo này ✨ +$ python main.py + +I solemnly swear 🐺 + +(Tôi long trọng thề 🐺 - câu này được lấy từ Harry Potter, chú thích của người dịch) +``` + +
    + +## Các cách làm tương tự + +Đây là một hướng dẫn đơn giản để bạn có thể bắt đầu và hiểu cách mọi thứ hoạt động **bên trong**. + +Có nhiều **cách khác nhau** để quản lí các môi trường ảo, các gói phụ thuộc (requirements), và các dự án. + +Một khi bạn đã sẵn sàng và muốn sử dụng một công cụ để **quản lí cả dự án**, các gói phụ thuộc, các môi trường ảo, v.v. Tôi sẽ khuyên bạn nên thử uv. + +`uv` có thể làm nhiều thứ, chẳng hạn: + +* **Cài đặt Python** cho bạn, bao gồm nhiều phiên bản khác nhau +* Quản lí **các môi trường ảo** cho các dự án của bạn +* Cài đặt **các gói (packages)** +* Quản lí **các thành phần phụ thuộc và phiên bản** của các gói cho dự án của bạn +* Đảm bảo rằng bạn có một **tập hợp chính xác** các gói và phiên bản để cài đặt, bao gồm các thành phần phụ thuộc của chúng, để bạn có thể đảm bảo rằng bạn có thể chạy dự án của bạn trong sản xuất chính xác như trong máy tính của bạn trong khi phát triển, điều này được gọi là **locking** +* Và còn nhiều thứ khác nữa + +## Kết luận + +Nếu bạn đã đọc và hiểu hết những điều này, khá chắc là bây giờ bạn đã **biết nhiều hơn** về môi trường ảo so với kha khá lập trình viên khác đấy. 🤓 + +Những hiểu biết chi tiết này có thể sẽ hữu ích với bạn trong tương lai khi mà bạn cần gỡ lỗi một vài thứ phức tạp, và bạn đã có những hiểu biết về **ngọn ngành gốc rễ cách nó hoạt động**. 😎 From 8cde8dc2a9e02dd70746a11dd906909449749b44 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 7 Feb 2025 22:22:35 +0000 Subject: [PATCH 786/932] =?UTF-8?q?=E2=AC=86=20Bump=20pillow=20from=2011.0?= =?UTF-8?q?.0=20to=2011.1.0=20(#13300)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pillow](https://github.com/python-pillow/Pillow) from 11.0.0 to 11.1.0. - [Release notes](https://github.com/python-pillow/Pillow/releases) - [Changelog](https://github.com/python-pillow/Pillow/blob/main/CHANGES.rst) - [Commits](https://github.com/python-pillow/Pillow/compare/11.0.0...11.1.0) --- updated-dependencies: - dependency-name: pillow dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs.txt b/requirements-docs.txt index 6f391675a..9af2a85d9 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -8,7 +8,7 @@ pyyaml >=5.3.1,<7.0.0 # For Material for MkDocs, Chinese search jieba==0.42.1 # For image processing by Material for MkDocs -pillow==11.0.0 +pillow==11.1.0 # For image processing by Material for MkDocs cairosvg==2.7.1 mkdocstrings[python]==0.26.1 From 83332ff9b272d5df8e6e979e1cbd3e72ee5b2e84 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 7 Feb 2025 22:22:54 +0000 Subject: [PATCH 787/932] =?UTF-8?q?=E2=AC=86=20Bump=20mkdocs-material=20fr?= =?UTF-8?q?om=209.5.18=20to=209.6.1=20(#13301)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [mkdocs-material](https://github.com/squidfunk/mkdocs-material) from 9.5.18 to 9.6.1. - [Release notes](https://github.com/squidfunk/mkdocs-material/releases) - [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/CHANGELOG) - [Commits](https://github.com/squidfunk/mkdocs-material/compare/9.5.18...9.6.1) --- updated-dependencies: - dependency-name: mkdocs-material dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs.txt b/requirements-docs.txt index 9af2a85d9..cd2e4e58e 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -1,6 +1,6 @@ -e . -r requirements-docs-tests.txt -mkdocs-material==9.5.18 +mkdocs-material==9.6.1 mdx-include >=1.4.1,<2.0.0 mkdocs-redirects>=1.2.1,<1.3.0 typer == 0.12.5 From 42a3b1526e771d81d0b90c7bccce2d097a7a7b2c Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 7 Feb 2025 22:23:11 +0000 Subject: [PATCH 788/932] =?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 [skip ci] --- 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 c52fb0f63..a6c7b24e8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Vietnamese translation for `docs/vi/docs/environment-variables.md`. PR [#13287](https://github.com/fastapi/fastapi/pull/13287) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Vietnamese translation for `docs/vi/docs/fastapi-cli.md`. PR [#13294](https://github.com/fastapi/fastapi/pull/13294) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Ukrainian translation for `docs/uk/docs/features.md`. PR [#13308](https://github.com/fastapi/fastapi/pull/13308) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/learn/index.md`. PR [#13306](https://github.com/fastapi/fastapi/pull/13306) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). From 49b18c87a0b98f36abc6962fc55a3b7bc151e51e Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 7 Feb 2025 22:24:04 +0000 Subject: [PATCH 789/932] =?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 [skip ci] --- 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 a6c7b24e8..b2020cb25 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/static-files.md`. PR [#13285](https://github.com/fastapi/fastapi/pull/13285) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Vietnamese translation for `docs/vi/docs/environment-variables.md`. PR [#13287](https://github.com/fastapi/fastapi/pull/13287) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Vietnamese translation for `docs/vi/docs/fastapi-cli.md`. PR [#13294](https://github.com/fastapi/fastapi/pull/13294) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Ukrainian translation for `docs/uk/docs/features.md`. PR [#13308](https://github.com/fastapi/fastapi/pull/13308) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). From 4740ccdcceb23ef825803421a64adbf36d5a84f3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 7 Feb 2025 22:25:02 +0000 Subject: [PATCH 790/932] =?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 [skip ci] --- 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 b2020cb25..dd53a3ba1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Vietnamese translation for `docs/vi/docs/virtual-environments.md`. PR [#13282](https://github.com/fastapi/fastapi/pull/13282) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/static-files.md`. PR [#13285](https://github.com/fastapi/fastapi/pull/13285) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Vietnamese translation for `docs/vi/docs/environment-variables.md`. PR [#13287](https://github.com/fastapi/fastapi/pull/13287) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Vietnamese translation for `docs/vi/docs/fastapi-cli.md`. PR [#13294](https://github.com/fastapi/fastapi/pull/13294) by [@ptt3199](https://github.com/ptt3199). From 828079cb6ea89a27c2aabf8f66ec9af94f496322 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 7 Feb 2025 22:25:56 +0000 Subject: [PATCH 791/932] =?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 [skip ci] --- 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 dd53a3ba1..633c29661 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -21,6 +21,7 @@ hide: ### Internal +* ⬆ Bump pillow from 11.0.0 to 11.1.0. PR [#13300](https://github.com/fastapi/fastapi/pull/13300) by [@dependabot[bot]](https://github.com/apps/dependabot). * 👥 Update FastAPI People - Sponsors. PR [#13295](https://github.com/fastapi/fastapi/pull/13295) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI People - Experts. PR [#13303](https://github.com/fastapi/fastapi/pull/13303) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI GitHub topic repositories. PR [#13302](https://github.com/fastapi/fastapi/pull/13302) by [@tiangolo](https://github.com/tiangolo). From c6c45ae488aea220450e2b9223075f1eb621172b Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 7 Feb 2025 22:27:05 +0000 Subject: [PATCH 792/932] =?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 [skip ci] --- 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 633c29661..449b880dc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -21,6 +21,7 @@ hide: ### Internal +* ⬆ Bump mkdocs-material from 9.5.18 to 9.6.1. PR [#13301](https://github.com/fastapi/fastapi/pull/13301) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pillow from 11.0.0 to 11.1.0. PR [#13300](https://github.com/fastapi/fastapi/pull/13300) by [@dependabot[bot]](https://github.com/apps/dependabot). * 👥 Update FastAPI People - Sponsors. PR [#13295](https://github.com/fastapi/fastapi/pull/13295) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI People - Experts. PR [#13303](https://github.com/fastapi/fastapi/pull/13303) by [@tiangolo](https://github.com/tiangolo). From ad33193f2c3d7732e804d0d5abdd08ab2ad4796d Mon Sep 17 00:00:00 2001 From: 11kkw <11kkw17@gmail.com> Date: Sun, 9 Feb 2025 23:54:09 +0900 Subject: [PATCH 793/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/tutorial/dependencies/dependencies-wit?= =?UTF-8?q?h-yield.md`=20(#13257)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependencies/dependencies-with-yield.md | 275 ++++++++++++++++++ 1 file changed, 275 insertions(+) create mode 100644 docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 000000000..ff174937d --- /dev/null +++ b/docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,275 @@ +# yield를 사용하는 의존성 + +FastAPI는 작업 완료 후 추가 단계를 수행하는 의존성을 지원합니다. + +이를 구현하려면 `return` 대신 `yield`를 사용하고, 추가로 실행할 단계 (코드)를 그 뒤에 작성하세요. + +/// tip | 팁 + +각 의존성마다 `yield`는 한 번만 사용해야 합니다. + +/// + +/// note | 기술 세부사항 + +다음과 함께 사용할 수 있는 모든 함수: + +* `@contextlib.contextmanager` 또는 +* `@contextlib.asynccontextmanager` + +는 **FastAPI**의 의존성으로 사용할 수 있습니다. + +사실, FastAPI는 내부적으로 이 두 데코레이터를 사용합니다. + +/// + +## `yield`를 사용하는 데이터베이스 의존성 + +예를 들어, 이 기능을 사용하면 데이터베이스 세션을 생성하고 작업이 끝난 후에 세션을 종료할 수 있습니다. + +응답을 생성하기 전에는 `yield`문을 포함하여 그 이전의 코드만이 실행됩니다: + +{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *} + +yield된 값은 *경로 작업* 및 다른 의존성들에 주입되는 값 입니다: + +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} + +`yield`문 다음의 코드는 응답을 생성한 후 보내기 전에 실행됩니다: + +{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *} + +/// tip | 팁 + +`async` 함수와 일반 함수 모두 사용할 수 있습니다. + +**FastAPI**는 일반 의존성과 마찬가지로 각각의 함수를 올바르게 처리할 것입니다. + +/// + +## `yield`와 `try`를 사용하는 의존성 + +`yield`를 사용하는 의존성에서 `try` 블록을 사용한다면, 의존성을 사용하는 도중 발생한 모든 예외를 받을 수 있습니다. + +예를 들어, 다른 의존성이나 *경로 작업*의 중간에 데이터베이스 트랜잭션 "롤백"이 발생하거나 다른 오류가 발생한다면, 해당 예외를 의존성에서 받을 수 있습니다. + +따라서, 의존성 내에서 `except SomeException`을 사용하여 특정 예외를 처리할 수 있습니다. + +마찬가지로, `finally`를 사용하여 예외 발생 여부와 관계 없이 종료 단계까 실행되도록 할 수 있습니다. + +{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *} + +## `yield`를 사용하는 하위 의존성 + +모든 크기와 형태의 하위 의존성과 하위 의존성의 "트리"도 가질 수 있으며, 이들 모두가 `yield`를 사용할 수 있습니다. + +**FastAPI**는 `yield`를 사용하는 각 의존성의 "종료 코드"가 올바른 순서로 실행되도록 보장합니다. + +예를 들어, `dependency_c`는 `dependency_b`에 의존할 수 있고, `dependency_b`는 `dependency_a`에 의존할 수 있습니다. + +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *} + +이들 모두는 `yield`를 사용할 수 있습니다. + +이 경우 `dependency_c`는 종료 코드를 실행하기 위해, `dependency_b`의 값 (여기서는 `dep_b`로 명명)이 여전히 사용 가능해야 합니다. + +그리고, `dependency_b`는 종료 코드를 위해 `dependency_a`의 값 (여기서는 `dep_a`로 명명) 이 사용 가능해야 합니다. + +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *} + +같은 방식으로, `yield`를 사용하는 의존성과 `return`을 사용하는 의존성을 함께 사용할 수 있으며, 이들 중 일부가 다른 것들에 의존할 수 있습니다. + +그리고 `yield`를 사용하는 다른 여러 의존성을 필요로 하는 단일 의존성을 가질 수도 있습니다. + +원하는 의존성을 원하는 대로 조합할 수 있습니다. + +**FastAPI**는 모든 것이 올바른 순서로 실행되도록 보장합니다. + +/// note | 기술 세부사항 + +파이썬의 Context Managers 덕분에 이 기능이 작동합니다. + +**FastAPI**는 이를 내부적으로 컨텍스트 관리자를 사용하여 구현합니다. + +/// + +## `yield`와 `HTTPException`를 사용하는 의존성 + +`yield`와 `try` 블록이 있는 의존성을 사용하여 예외를 처리할 수 있다는 것을 알게 되었습니다. + +같은 방식으로, `yield` 이후의 종료 코드에서 `HTTPException`이나 유사한 예외를 발생시킬 수 있습니다. + +/// tip | 팁 + +이는 다소 고급 기술이며, 대부분의 경우 경로 연산 함수 등 나머지 애플리케이션 코드 내부에서 예외 (`HTTPException` 포함)를 발생시킬 수 있으므로 실제로는 필요하지 않을 것입니다. + +하지만 필요한 경우 사용할 수 있습니다. 🤓 + +/// + +{* ../../docs_src/dependencies/tutorial008b_an_py39.py hl[18:22,31] *} + +예외를 처리하고(또는 추가로 다른 `HTTPException`을 발생시키기 위해) 사용할 수 있는 또 다른 방법은 [사용자 정의 예외 처리기](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}를 생성하는 것 입니다. + +## `yield`와 `except`를 사용하는 의존성 + +`yield`를 사용하는 의존성에서 `except`를 사용하여 예외를 포착하고 예외를 다시 발생시키지 않거나 (또는 새 예외를 발생시키지 않으면), FastAPI는 해당 예외가 발생했는지 알 수 없습니다. 이는 일반적인 Python 방식과 동일합니다: + +{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *} + +이 경우, `HTTPException`이나 유사한 예외를 발생시키지 않기 때문에 클라이언트는 HTTP 500 Internal Server Error 응답을 보게 되지만, 서버는 어떤 오류가 발생했는지에 대한 **로그**나 다른 표시를 전혀 가지지 않게 됩니다. 😱 + +### `yield`와 `except`를 사용하는 의존성에서 항상 `raise` 하기 + +`yield`가 있는 의존성에서 예외를 잡았을 때는 `HTTPException`이나 유사한 예외를 새로 발생시키지 않는 한, 반드시 원래의 예외를 다시 발생시켜야 합니다. + +`raise`를 사용하여 동일한 예외를 다시 발생시킬 수 있습니다: + +{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *} + +이제 클라이언트는 동일한 *HTTP 500 Internal Server Error* 오류 응답을 받게 되지만, 서버 로그에는 사용자 정의 예외인 `InternalError"가 기록됩니다. 😎 + +## `yield`를 사용하는 의존성의 실행 순서 + +실행 순서는 아래 다이어그램과 거의 비슷합니다. 시간은 위에서 아래로 흐릅니다. 그리고 각 열은 상호 작용하거나 코드를 실행하는 부분 중 하나입니다. + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exception handler +participant dep as Dep with yield +participant operation as Path Operation +participant tasks as Background tasks + + Note over client,operation: Can raise exceptions, including HTTPException + client ->> dep: Start request + Note over dep: Run code up to yield + opt raise Exception + dep -->> handler: Raise Exception + handler -->> client: HTTP error response + end + dep ->> operation: Run dependency, e.g. DB session + opt raise + operation -->> dep: Raise Exception (e.g. HTTPException) + opt handle + dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception + end + handler -->> client: HTTP error response + end + + operation ->> client: Return response to client + Note over client,operation: Response is already sent, can't change it anymore + opt Tasks + operation -->> tasks: Send background tasks + end + opt Raise other exception + tasks -->> tasks: Handle exceptions in the background task code + end +``` + +/// info | 정보 + +클라이언트에 **하나의 응답** 만 전송됩니다. 이는 오류 응답 중 하나일 수도 있고,*경로 작업*에서 생성된 응답일 수도 있습니다. + +이러한 응답 중 하나가 전송된 후에는 다른 응답을 보낼 수 없습니다. + +/// + +/// tip | 팁 + +이 다이어그램은 `HTTPException`을 보여주지만, `yield`를 사용하는 의존성에서 처리한 예외나 [사용자 정의 예외처리기](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.를 사용하여 처리한 다른 예외도 발생시킬 수 있습니다. + +어떤 예외가 발생하든, `HTTPException`을 포함하여 yield를 사용하는 의존성으로 전달됩니다. 대부분의 경우 예외를 다시 발생시키거나 새로운 예외를 발생시켜야 합니다. + +/// + +## `yield`, `HTTPException`, `except` 및 백그라운드 작업을 사용하는 의존성 + +/// warning | 경고 + +이러한 기술적 세부 사항은 대부분 필요하지 않으므로 이 섹션을 건너뛰고 아래에서 계속 진행해도 됩니다. + +이러한 세부 정보는 주로 FastAPI 0.106.0 이전 버전에서 `yield`가 있는 의존성의 리소스를 백그라운드 작업에서 사용했던 경우메 유용합니다. + +/// + +### `yield`와 `except`를 사용하는 의존성, 기술 세부사항 + +FastAPI 0.110.0 이전에는 `yield`가 포함된 의존성을 사용한 후 해당 의존성에서 `except`가 포함된 예외를 캡처하고 다시 예외를 발생시키지 않으면 예외가 자동으로 예외 핸들러 또는 내부 서버 오류 핸들러로 발생/전달되었습니다. + +이는 처리기 없이 전달된 예외(내부 서버 오류)에서 처리되지 않은 메모리 소비를 수정하고 일반 파이썬 코드의 동작과 일치하도록 하기 위해 0.110.0 버전에서 변경되었습니다. + +### 백그라운드 작업과 `yield`를 사용하는 의존성, 기술 세부사항 + +FastAPI 0.106.0 이전에는 `yield` 이후에 예외를 발생시키는 것이 불가능했습니다. `yield`가 있는 의존성 종료 코드는 응답이 전송된 이후에 실행되었기 때문에, [예외 처리기](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}가 이미 실행된 상태였습니다. + +이는 주로 백그라운드 작업 내에서 의존성에서 "yield된" 동일한 객체를 사용할 수 있도록 하기 위해 이런 방식으로 설계되었습니다. 종료 코드는 백그라운드 작업이 완료된 후에 실행되었기 때문입니다 + +하지만 이렇게 하면 리소스를 불필요하게 양보한 의존성(예: 데이터베이스 연결)에서 보유하면서 응답이 네트워크를 통해 이동할 때까지 기다리는 것을 의미하기 때문에 FastAPI 0.106.0에서 변경되었습니다. + +/// tip | 팁 + +또한 백그라운드 작업은 일반적으로 자체 리소스(예: 자체 데이터베이스 연결)를 사용하여 별도로 처리해야 하는 독립적인 로직 집합입니다. + +따라서 이렇게 하면 코드가 더 깔끔해집니다. + +/// + +만약 이전에 이러한 동작에 의존했다면, 이제는 백그라운드 작업 내부에서 백그라운드 작업을 위한 리소스를 생성하고, `yield`가 있는 의존성의 리소스에 의존하지 않는 데이터만 내부적으로 사용해야합니다. + +예를 들어, 동일한 데이터베이스 세션을 사용하는 대신, 백그라운드 작업 내부에서 새로운 데이터베이스 세션을 생성하고 이 새로운 세션을 사용하여 데이터베이스에서 객체를 가져와야 합니다. 그리고 데이터베이스 객체를 백그라운드 작업 함수의 매개변수로 직접 전달하는 대신, 해당 객체의 ID를 전달한 다음 백그라운드 작업 함수 내부에서 객체를 다시 가져와야 합니다 + +## 컨텍스트 관리자 + +### "컨텍스트 관리자"란? + +"컨텍스트 관리자"는 Python에서 `with` 문에서 사용할 수 있는 모든 객체를 의미합니다. + +예를 들어, `with`를 사용하여 파일을 읽을 수 있습니다: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +내부적으로 `open("./somefile.txt")` 는 "컨텍스트 관리자(Context Manager)"라고 불리는 객체를 생성합니다. + +`with` 블록이 끝나면, 예외가 발생했더라도 파일을 닫도록 보장합니다. + +`yield`가 있는 의존성을 생성하면 **FastAPI**는 내부적으로 이를 위한 컨텍스트 매니저를 생성하고 다른 관련 도구들과 결합합니다. + +### `yield`를 사용하는 의존성에서 컨텍스트 관리자 사용하기 + +/// warning | 경고 + +이것은 어느 정도 "고급" 개념입니다. + +**FastAPI**를 처음 시작하는 경우 지금은 이 부분을 건너뛰어도 좋습니다. + +/// + +Python에서는 다음을 통해 컨텍스트 관리자를 생성할 수 있습니다. 두 가지 메서드가 있는 클래스를 생성합니다: `__enter__()` and `__exit__()`. + +**FastAPI**의 `yield`가 있는 의존성 내에서 +`with` 또는 `async with`문을 사용하여 이들을 활용할 수 있습니다: + +{* ../../docs_src/dependencies/tutorial010.py hl[1:9,13] *} + +/// tip | 팁 + +컨텍스트 관리자를 생성하는 또 다른 방법은 다음과 같습니다: + +* `@contextlib.contextmanager` 또는 +* `@contextlib.asynccontextmanager` + +이들은 단일 `yield`가 있는 함수를 꾸미는 데 사용합니다. + +이것이 **FastAPI**가 `yield`가 있는 의존성을 위해 내부적으로 사용하는 방식입니다. + +하지만 FastAPI 의존성에는 이러한 데코레이터를 사용할 필요가 없습니다(그리고 사용해서도 안됩니다). + +FastAPI가 내부적으로 이를 처리해 줄 것입니다. + +/// From 57a9a64435351717ca5a29304cd7736de755c9b0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 9 Feb 2025 14:54:33 +0000 Subject: [PATCH 794/932] =?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 [skip ci] --- 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 449b880dc..cda5e9626 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#13257](https://github.com/fastapi/fastapi/pull/13257) by [@11kkw](https://github.com/11kkw). * 🌐 Add Vietnamese translation for `docs/vi/docs/virtual-environments.md`. PR [#13282](https://github.com/fastapi/fastapi/pull/13282) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/static-files.md`. PR [#13285](https://github.com/fastapi/fastapi/pull/13285) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Vietnamese translation for `docs/vi/docs/environment-variables.md`. PR [#13287](https://github.com/fastapi/fastapi/pull/13287) by [@ptt3199](https://github.com/ptt3199). From 126a9b33c92113748de4398c0bcb65600024b03c Mon Sep 17 00:00:00 2001 From: Emil Sadek Date: Mon, 10 Feb 2025 03:18:47 -0800 Subject: [PATCH 795/932] =?UTF-8?q?=F0=9F=93=9D=20Fix=20test=20badge=20(#1?= =?UTF-8?q?3313)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix test badge * Fix test badge in docs --------- Co-authored-by: Emil Sadek Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- README.md | 2 +- docs/en/docs/index.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f6da22b21..d5d5ced52 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@

    - Test + Test Coverage diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index cbe71c87d..4a2777f25 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -12,7 +12,7 @@

    - Test + Test Coverage From eea196f4a505c2584fafda691f2a0033c4db6622 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 10 Feb 2025 11:19:36 +0000 Subject: [PATCH 796/932] =?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 [skip ci] --- 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 cda5e9626..013cbfc7c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Fix test badge. PR [#13313](https://github.com/fastapi/fastapi/pull/13313) by [@esadek](https://github.com/esadek). + ### Translations * 🌐 Add Korean translation for `docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#13257](https://github.com/fastapi/fastapi/pull/13257) by [@11kkw](https://github.com/11kkw). From 5cbb81cc2686c50e1fe6da48986fac0498a157dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=C6=B0=C6=A1ng=20T=E1=BA=A5n=20Th=C3=A0nh?= <51350651+ptt3199@users.noreply.github.com> Date: Sat, 15 Feb 2025 18:08:22 +0700 Subject: [PATCH 797/932] =?UTF-8?q?=F0=9F=8C=90=20=20Add=20Vietnamese=20tr?= =?UTF-8?q?anslation=20for=20`docs/vi/docs/tutorial/static-files.md`=20(#1?= =?UTF-8?q?1291)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/vi/docs/tutorial/static-files.md | 40 +++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 docs/vi/docs/tutorial/static-files.md diff --git a/docs/vi/docs/tutorial/static-files.md b/docs/vi/docs/tutorial/static-files.md new file mode 100644 index 000000000..ecf8c2485 --- /dev/null +++ b/docs/vi/docs/tutorial/static-files.md @@ -0,0 +1,40 @@ +# Tệp tĩnh (Static Files) + +Bạn có thể triển khai tệp tĩnh tự động từ một thư mục bằng cách sử dụng StaticFiles. + +## Sử dụng `Tệp tĩnh` + +- Nhập `StaticFiles`. +- "Mount" a `StaticFiles()` instance in a specific path. + +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} + +/// note | Chi tiết kỹ thuật + +Bạn cũng có thể sử dụng `from starlette.staticfiles import StaticFiles`. + +**FastAPI** cung cấp cùng `starlette.staticfiles` như `fastapi.staticfiles` giúp đơn giản hóa việc sử dụng, nhưng nó thực sự đến từ Starlette. + +/// + +### "Mounting" là gì + +"Mounting" có nghĩa là thêm một ứng dụng "độc lập" hoàn chỉnh vào một đường dẫn cụ thể, sau đó ứng dụng đó sẽ chịu trách nhiệm xử lý tất cả các đường dẫn con. + +Điều này khác với việc sử dụng `APIRouter` vì một ứng dụng được gắn kết là hoàn toàn độc lập. OpenAPI và tài liệu từ ứng dụng chính của bạn sẽ không bao gồm bất kỳ thứ gì từ ứng dụng được gắn kết, v.v. + +Bạn có thể đọc thêm về điều này trong [Hướng dẫn Người dùng Nâng cao](../advanced/index.md){.internal-link target=\_blank}. + +## Chi tiết + +Đường dẫn đầu tiên `"/static"` là đường dẫn con mà "ứng dụng con" này sẽ được "gắn" vào. Vì vậy, bất kỳ đường dẫn nào bắt đầu bằng `"/static"` sẽ được xử lý bởi nó. + +Đường dẫn `directory="static"` là tên của thư mục chứa tệp tĩnh của bạn. + +Tham số `name="static"` đặt tên cho nó để có thể được sử dụng bên trong **FastAPI**. + +Tất cả các tham số này có thể khác với `static`, điều chỉnh chúng với phù hợp với ứng dụng của bạn. + +## Thông tin thêm + +Để biết thêm chi tiết và tùy chọn, hãy xem Starlette's docs about Static Files. From 3aeaa0a6a826466669d9faf13762524ee795e8b2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 15 Feb 2025 11:08:48 +0000 Subject: [PATCH 798/932] =?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 [skip ci] --- 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 013cbfc7c..7e8f57054 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Vietnamese translation for `docs/vi/docs/tutorial/static-files.md`. PR [#11291](https://github.com/fastapi/fastapi/pull/11291) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#13257](https://github.com/fastapi/fastapi/pull/13257) by [@11kkw](https://github.com/11kkw). * 🌐 Add Vietnamese translation for `docs/vi/docs/virtual-environments.md`. PR [#13282](https://github.com/fastapi/fastapi/pull/13282) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/static-files.md`. PR [#13285](https://github.com/fastapi/fastapi/pull/13285) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). From 03b24b5a524dc6b27e10a58dac9538b737f0defa Mon Sep 17 00:00:00 2001 From: ScrollDude <93028356+Stepakinoyan@users.noreply.github.com> Date: Sat, 15 Feb 2025 20:15:23 +0900 Subject: [PATCH 799/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/advanced/response-cookies.md`=20(#133?= =?UTF-8?q?27)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/advanced/response-cookies.md | 48 +++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 docs/ru/docs/advanced/response-cookies.md diff --git a/docs/ru/docs/advanced/response-cookies.md b/docs/ru/docs/advanced/response-cookies.md new file mode 100644 index 000000000..e04ff577c --- /dev/null +++ b/docs/ru/docs/advanced/response-cookies.md @@ -0,0 +1,48 @@ + +# Cookies в ответе + +## Использование параметра `Response` + +Вы можете объявить параметр типа `Response` в вашей функции эндпоинта. + +Затем установить cookies в этом временном объекте ответа. + +{* ../../docs_src/response_cookies/tutorial002.py hl[1, 8:9] *} + +После этого можно вернуть любой объект, как и раньше (например, `dict`, объект модели базы данных и так далее). + +Если вы указали `response_model`, он всё равно будет использоваться для фильтрации и преобразования возвращаемого объекта. + +**FastAPI** извлечет cookies (а также заголовки и коды состояния) из временного ответа и включит их в окончательный ответ, содержащий ваше возвращаемое значение, отфильтрованное через `response_model`. + +Вы также можете объявить параметр типа Response в зависимостях и устанавливать cookies (и заголовки) там. + +## Возвращение `Response` напрямую + +Вы также можете установить cookies, если возвращаете `Response` напрямую в вашем коде. + +Для этого создайте объект `Response`, как описано в разделе [Возвращение ответа напрямую](response-directly.md){.target=_blank}. + +Затем установите cookies и верните этот объект: + +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} + +/// tip | Примечание +Имейте в виду, что если вы возвращаете ответ напрямую, вместо использования параметра `Response`, **FastAPI** отправит его без дополнительной обработки. + +Убедитесь, что ваши данные имеют корректный тип. Например, они должны быть совместимы с JSON, если вы используете `JSONResponse`. + +Также убедитесь, что вы не отправляете данные, которые должны были быть отфильтрованы через `response_model`. +/// + +### Дополнительная информация + +/// note | Технические детали +Вы также можете использовать `from starlette.responses import Response` или `from starlette.responses import JSONResponse`. + +**FastAPI** предоставляет `fastapi.responses`, которые являются теми же объектами, что и `starlette.responses`, просто для удобства. Однако большинство доступных типов ответов поступает непосредственно из **Starlette**. + +Для установки заголовков и cookies `Response` используется часто, поэтому **FastAPI** также предоставляет его через `fastapi.responses`. +/// + +Чтобы увидеть все доступные параметры и настройки, ознакомьтесь с документацией Starlette. From 15afe2e301d06a64a356181a4e7216818316e731 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 15 Feb 2025 11:15:45 +0000 Subject: [PATCH 800/932] =?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 [skip ci] --- 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 7e8f57054..0166e6cc5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Russian translation for `docs/ru/docs/advanced/response-cookies.md`. PR [#13327](https://github.com/fastapi/fastapi/pull/13327) by [@Stepakinoyan](https://github.com/Stepakinoyan). * 🌐 Add Vietnamese translation for `docs/vi/docs/tutorial/static-files.md`. PR [#11291](https://github.com/fastapi/fastapi/pull/11291) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#13257](https://github.com/fastapi/fastapi/pull/13257) by [@11kkw](https://github.com/11kkw). * 🌐 Add Vietnamese translation for `docs/vi/docs/virtual-environments.md`. PR [#13282](https://github.com/fastapi/fastapi/pull/13282) by [@ptt3199](https://github.com/ptt3199). From 39b4692525acfffdfba8e12ee674d9590b02b19f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lee=20Yesong=20=28=EC=9D=B4=EC=98=88=EC=86=A1=29?= Date: Sat, 15 Feb 2025 20:19:12 +0900 Subject: [PATCH 801/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Korean=20transl?= =?UTF-8?q?ation=20for=20`docs/ko/docs/tutorial/security/simple-oauth2.md`?= =?UTF-8?q?=20(#13335)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ko/docs/tutorial/security/simple-oauth2.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/ko/docs/tutorial/security/simple-oauth2.md b/docs/ko/docs/tutorial/security/simple-oauth2.md index ddc7430af..f10c4f588 100644 --- a/docs/ko/docs/tutorial/security/simple-oauth2.md +++ b/docs/ko/docs/tutorial/security/simple-oauth2.md @@ -32,7 +32,7 @@ OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할 * `instagram_basic`은 페이스북/인스타그램에서 사용합니다. * `https://www.googleapis.com/auth/drive`는 Google에서 사용합니다. -/// 정보 +/// info | 정보 OAuth2에서 "범위"는 필요한 특정 권한을 선언하는 문자열입니다. @@ -61,7 +61,7 @@ OAuth2의 경우 문자열일 뿐입니다. * `scope`는 선택적인 필드로 공백으로 구분된 문자열로 구성된 큰 문자열입니다. * `grant_type`(선택적으로 사용). -/// 팁 +/// tip | 팁 OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 필드를 *요구*하지만 `OAuth2PasswordRequestForm`은 이를 강요하지 않습니다. @@ -72,7 +72,7 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` * `client_id`(선택적으로 사용) (예제에서는 필요하지 않습니다). * `client_secret`(선택적으로 사용) (예제에서는 필요하지 않습니다). -/// 정보 +/// info | 정보 `OAuth2PasswordRequestForm`은 `OAuth2PasswordBearer`와 같이 **FastAPI**에 대한 특수 클래스가 아닙니다. @@ -86,7 +86,7 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` ### 폼 데이터 사용하기 -/// 팁 +/// tip | 팁 종속성 클래스 `OAuth2PasswordRequestForm`의 인스턴스에는 공백으로 구분된 긴 문자열이 있는 `scope` 속성이 없고 대신 전송된 각 범위에 대한 실제 문자열 목록이 있는 `scopes` 속성이 있습니다. @@ -126,7 +126,7 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 따라서 해커는 다른 시스템에서 동일한 암호를 사용하려고 시도할 수 없습니다(많은 사용자가 모든 곳에서 동일한 암호를 사용하므로 이는 위험할 수 있습니다). -//// tab | P파이썬 3.7 이상 +//// tab | 파이썬 3.7 이상 {* ../../docs_src/security/tutorial003.py hl[80:83] *} @@ -150,7 +150,7 @@ UserInDB( ) ``` -/// 정보 +/// info | 정보 `**user_dict`에 대한 자세한 설명은 [**추가 모델** 문서](../extra-models.md#about-user_indict){.internal-link target=_blank}를 다시 읽어봅시다. @@ -166,7 +166,7 @@ UserInDB( 이 간단한 예제에서는 완전히 안전하지 않고, 동일한 `username`을 토큰으로 반환합니다. -/// 팁 +/// tip | 팁 다음 장에서는 패스워드 해싱 및 JWT 토큰을 사용하여 실제 보안 구현을 볼 수 있습니다. @@ -176,7 +176,7 @@ UserInDB( {* ../../docs_src/security/tutorial003.py hl[85] *} -/// 팁 +/// tip | 팁 사양에 따라 이 예제와 동일하게 `access_token` 및 `token_type`이 포함된 JSON을 반환해야 합니다. @@ -202,7 +202,7 @@ UserInDB( {* ../../docs_src/security/tutorial003.py hl[58:66,69:72,90] *} -/// 정보 +/// info | 정보 여기서 반환하는 값이 `Bearer`인 추가 헤더 `WWW-Authenticate`도 사양의 일부입니다. From fc94d904c969ba1b85aa9d9a966ad8dee27e7652 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 15 Feb 2025 11:19:48 +0000 Subject: [PATCH 802/932] =?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 [skip ci] --- 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 0166e6cc5..8fcf68e5f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Update Korean translation for `docs/ko/docs/tutorial/security/simple-oauth2.md`. PR [#13335](https://github.com/fastapi/fastapi/pull/13335) by [@yes0ng](https://github.com/yes0ng). * 🌐 Add Russian translation for `docs/ru/docs/advanced/response-cookies.md`. PR [#13327](https://github.com/fastapi/fastapi/pull/13327) by [@Stepakinoyan](https://github.com/Stepakinoyan). * 🌐 Add Vietnamese translation for `docs/vi/docs/tutorial/static-files.md`. PR [#11291](https://github.com/fastapi/fastapi/pull/11291) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#13257](https://github.com/fastapi/fastapi/pull/13257) by [@11kkw](https://github.com/11kkw). From 030012bf4c225a2b5dbb3c6b3443bd2051e614f8 Mon Sep 17 00:00:00 2001 From: 11kkw <11kkw17@gmail.com> Date: Sat, 15 Feb 2025 20:21:20 +0900 Subject: [PATCH 803/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/advanced/custom-response.md`=20(#13265?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/advanced/custom-response.md | 313 +++++++++++++++++++++++ 1 file changed, 313 insertions(+) create mode 100644 docs/ko/docs/advanced/custom-response.md diff --git a/docs/ko/docs/advanced/custom-response.md b/docs/ko/docs/advanced/custom-response.md new file mode 100644 index 000000000..2001956fa --- /dev/null +++ b/docs/ko/docs/advanced/custom-response.md @@ -0,0 +1,313 @@ +# 사용자 정의 응답 - HTML, Stream, 파일, 기타 + +기본적으로, **FastAPI** 응답을 `JSONResponse`를 사용하여 반환합니다. + +이를 재정의 하려면 [응답을 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 본 것처럼 `Response`를 직접 반환하면 됩니다. + +그러나 `Response` (또는 `JSONResponse`와 같은 하위 클래스)를 직접 반환하면, 데이터가 자동으로 변환되지 않으며 (심지어 `response_model`을 선언했더라도), 문서화가 자동으로 생성되지 않습니다(예를 들어, 생성된 OpenAPI의 일부로 HTTP 헤더 `Content-Type`에 특정 "미디어 타입"을 포함하는 경우). + +하지만 *경로 작업 데코레이터*에서 `response_class` 매개변수를 사용하여 원하는 `Response`(예: 모든 `Response` 하위 클래스)를 선언할 수도 있습니다. + +*경로 작업 함수*에서 반환하는 내용은 해당 `Response`안에 포함됩니다. + +그리고 만약 그 `Response`가 `JSONResponse`와 `UJSONResponse`의 경우 처럼 JSON 미디어 타입(`application/json`)을 가지고 있다면, *경로 작업 데코레이터*에서 선언한 Pydantic의 `response_model`을 사용해 자동으로 변환(및 필터링) 됩니다. + +/// note | 참고 + +미디어 타입이 없는 응답 클래스를 사용하는 경우, FastAPI는 응답에 내용이 없을 것으로 예상하므로 생성된 OpenAPI 문서에서 응답 형식을 문서화하지 않습니다. + +/// + +## `ORJSONResponse` 사용하기 + +예를 들어, 성능을 극대화하려는 경우, orjson을 설치하여 사용하고 응답을 `ORJSONResponse`로 설정할 수 있습니다. + +사용하고자 하는 `Response` 클래스(하위 클래스)를 임포트한 후, **경로 작업 데코레이터*에서 선언하세요. + +대규모 응답의 경우, 딕셔너리를 반환하는 것보다 `Response`를 반환하는 것이 훨씬 빠릅니다. + +이유는 기본적으로, FastAPI가 내부의 모든 항목을 검사하고 JSON으로 직렬화할 수 있는지 확인하기 때문입니다. 이는 사용자 안내서에서 설명된 [JSON 호환 가능 인코더](../tutorial/encoder.md){.internal-link target=_blank}를 사용하는 방식과 동일합니다. 이를 통해 데이터베이스 모델과 같은 **임의의 객체**를 반환할 수 있습니다. + +하지만 반환하는 내용이 **JSON으로 직렬화 가능**하다고 확신하는 경우, 해당 내용을 응답 클래스에 직접 전달할 수 있으며, FastAPI가 반환 내용을 `jsonable_encoder`를 통해 처리한 뒤 응답 클래스에 전달하는 오버헤드를 피할 수 있습니다. + +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} + +/// info | 정보 + +`response_class` 매개변수는 응답의 "미디어 타입"을 정의하는 데에도 사용됩니다. + +이 경우, HTTP 헤더 `Content-Type`은 `application/json`으로 설정됩니다. + +그리고 이는 OpenAPI에 그대로 문서화됩니다. + +/// + +/// tip | 팁 + +`ORJSONResponse`는 FastAPI에서만 사용할 수 있고 Starlette에서는 사용할 수 없습니다. + +/// + +## HTML 응답 + +**FastAPI**에서 HTML 응답을 직접 반환하려면 `HTMLResponse`를 사용하세요. + +* `HTMLResponse`를 임포트 합니다. +* *경로 작업 데코레이터*의 `response_class` 매개변수로 `HTMLResponse`를 전달합니다. + +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} + +/// info | 정보 + +`response_class` 매개변수는 응답의 "미디어 타입"을 정의하는 데에도 사용됩니다. + +이 경우, HTTP 헤더 `Content-Type`은 `text/html`로 설정됩니다. + +그리고 이는 OpenAPI에 그대로 문서화 됩니다. + +/// + +### `Response` 반환하기 + +[응답을 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 본 것 처럼, *경로 작업*에서 응답을 직접 반환하여 재정의할 수도 있습니다. + +위의 예제와 동일하게 `HTMLResponse`를 반환하는 코드는 다음과 같을 수 있습니다: + +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} + +/// warning | 경고 + +*경로 작업 함수*에서 직접 반환된 `Response`는 OpenAPI에 문서화되지 않습니다(예를들어, `Content-Type`이 문서화되지 않음) 자동 대화형 문서에서도 표시되지 않습니다. + +/// + +/// info | 정보 + +물론 실제 `Content-Type` 헤더, 상태 코드 등은 반환된 `Response` 객체에서 가져옵니다. + +/// + +### OpenAPI에 문서화하고 `Response` 재정의 하기 + +함수 내부에서 응답을 재정의하면서 동시에 OpenAPI에서 "미디어 타입"을 문서화하고 싶다면, `response_class` 매게변수를 사용하면서 `Response` 객체를 반환할 수 있습니다. + +이 경우 `response_class`는 OpenAPI *경로 작업*을 문서화하는 데만 사용되고, 실제로는 여러분이 반환한 `Response`가 그대로 사용됩니다. + +### `HTMLResponse`직접 반환하기 + +예를 들어, 다음과 같이 작성할 수 있습니다: + +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} + +이 예제에서, `generate_html_response()` 함수는 HTML을 `str`로 반환하는 대신 이미 `Response`를 생성하고 반환합니다. + +`generate_html_response()`를 호출한 결과를 반환함으로써, 기본적인 **FastAPI** 기본 동작을 재정의 하는 `Response`를 이미 반환하고 있습니다. + +하지만 `response_class`에 `HTMLResponse`를 함께 전달했기 때문에, FastAPI는 이를 OpenAPI 및 대화형 문서에서 `text/html`로 HTML을 문서화 하는 방법을 알 수 있습니다. + + + +## 사용 가능한 응답들 + +다음은 사용할 수 있는 몇가지 응답들 입니다. + +`Response`를 사용하여 다른 어떤 것도 반환 할수 있으며, 직접 하위 클래스를 만들 수도 있습니다. + +/// note | 기술 세부사항 + +`from starlette.responses import HTMLResponse`를 사용할 수도 있습니다. + +**FastAPI**는 개발자인 여러분의 편의를 위해 `starlette.responses`를 `fastapi.responses`로 제공 하지만, 대부분의 사용 가능한 응답은 Starlette에서 직접 가져옵니다. + +/// + +### `Response` + +기본 `Response` 클래스는 다른 모든 응답 클래스의 부모 클래스 입니다. + +이 클래스를 직접 반환할 수 있습니다. + +다음 매개변수를 받을 수 있습니다: + +* `content` - `str` 또는 `bytes`. +* `status_code` - HTTP 상태코드를 나타내는 `int`. +* `headers` - 문자열로 이루어진 `dict`. +* `media_type` - 미디어 타입을 나타내는 `str` 예: `"text/html"`. + +FastAPI (실제로는 Starlette)가 자동으로 `Content-Length` 헤더를 포함시킵니다. 또한 `media_type`에 기반하여 `Content-Type` 헤더를 포함하며, 텍스트 타입의 경우 문자 집합을 추가 합니다. + +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} + +### `HTMLResponse` + +텍스트 또는 바이트를 받아 HTML 응답을 반환합니다. 위에서 설명한 내용과 같습니다. + +### `PlainTextResponse` + +텍스트 또는 바이트를 받아 일반 텍스트 응답을 반환합니다. + +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} + +### `JSONResponse` + +데이터를 받아 `application/json`으로 인코딩된 응답을 반환합니다. + +이는 위에서 설명했듯이 **FastAPI**에서 기본적으로 사용되는 응답 형식입니다. + +### `ORJSONResponse` + + `orjson`을 사용하여 빠른 JSON 응답을 제공하는 대안입니다. 위에서 설명한 내용과 같습니다. + +/// info | 정보 + +이를 사용하려면 `orjson`을 설치해야합니다. 예: `pip install orjson`. + +/// + +### `UJSONResponse` + +`ujson`을 사용한 또 다른 JSON 응답 형식입니다. + +/// info | 정보 + +이 응답을 사용하려면 `ujson`을 설치해야합니다. 예: 'pip install ujson`. + +/// + +/// warning | 경고 + +`ujson` 은 일부 예외 경우를 처리하는 데 있어 Python 내장 구현보다 덜 엄격합니다. + +/// + +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} + +/// tip | 팁 + +`ORJSONResponse`가 더 빠른 대안일 가능성이 있습니다. + +/// + +### `RedirectResponse` + +HTTP 리디렉션 응답을 반환합니다. 기본적으로 상태 코드는 307(임시 리디렉션)으로 설정됩니다. + +`RedirectResponse`를 직접 반환할 수 있습니다. + +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} + +--- + +또는 `response_class` 매개변수에서 사용할 수도 있습니다: + + +{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *} + +이 경우, *경로 작업* 함수에서 URL을 직접 반환할 수 있습니다. + +이 경우, 사용되는 `status_code`는 `RedirectResponse`의 기본값인 `307` 입니다. + +--- + +`status_code` 매개변수를 `response_class` 매개변수와 함께 사용할 수도 있습니다: + +{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *} + +### `StreamingResponse` + +비동기 제너레이터 또는 일반 제너레이터/이터레이터를 받아 응답 본문을 스트리밍 합니다. + +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} + +#### 파일과 같은 객체를 사용한 `StreamingResponse` + +파일과 같은 객체(예: `open()`으로 반환된 객체)가 있는 경우, 해당 파일과 같은 객체를 반복(iterate)하는 제너레이터 함수를 만들 수 있습니다. + +이 방식으로, 파일 전체를 메모리에 먼저 읽어들일 필요 없이, 제너레이터 함수를 `StreamingResponse`에 전달하여 반환할 수 있습니다. + +이 방식은 클라우드 스토리지, 비디오 처리 등의 다양한 라이브러리와 함께 사용할 수 있습니다. + +{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *} + +1. 이것이 제너레이터 함수입니다. `yield` 문을 포함하고 있으므로 "제너레이터 함수"입니다. +2. `with` 블록을 사용함으로써, 제너레이터 함수가 완료된 후 파일과 같은 객체가 닫히도록 합니다. 즉, 응답 전송이 끝난 후 닫힙니다. +3. 이 `yield from`은 함수가 `file_like`라는 객체를 반복(iterate)하도록 합니다. 반복된 각 부분은 이 제너레이터 함수(`iterfile`)에서 생성된 것처럼 `yield` 됩니다. + + 이렇게 하면 "생성(generating)" 작업을 내부적으로 다른 무언가에 위임하는 제너레이터 함수가 됩니다. + + 이 방식을 사용하면 `with` 블록 안에서 파일을 열 수 있어, 작업이 완료된 후 파일과 같은 객체가 닫히는 것을 보장할 수 있습니다. + +/// tip | 팁 + +여기서 표준 `open()`을 사용하고 있기 때문에 `async`와 `await`를 지원하지 않습니다. 따라서 경로 작업은 일반 `def`로 선언합니다. + +/// + +### `FileResponse` + +파일을 비동기로 스트리밍하여 응답합니다. + +다른 응답 유형과는 다른 인수를 사용하여 객체를 생성합니다: + +* `path` - 스트리밍할 파일의 경로. +* `headers` - 딕셔너리 형식의 사용자 정의 헤더. +* `media_type` - 미디어 타입을 나타내는 문자열. 설정되지 않은 경우 파일 이름이나 경로를 사용하여 추론합니다. +* `filename` - 설정된 경우 응답의 `Content-Disposition`에 포함됩니다. + +파일 응답에는 적절한 `Content-Length`, `Last-Modified`, 및 `ETag` 헤더가 포함됩니다. + +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} + +또한 `response_class` 매개변수를 사용할 수도 있습니다: + +{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *} + +이 경우, 경로 작업 함수에서 파일 경로를 직접 반환할 수 있습니다. + +## 사용자 정의 응답 클래스 + +`Response`를 상속받아 사용자 정의 응답 클래스를 생성하고 사용할 수 있습니다. + +예를 들어, 포함된 `ORJSONResponse` 클래스에서 사용되지 않는 설정으로 orjson을 사용하고 싶다고 가정해봅시다. + +만약 들여쓰기 및 포맷된 JSON을 반환하고 싶다면, `orjson.OPT_INDENT_2` 옵션을 사용할 수 있습니다. + +`CustomORJSONResponse`를 생성할 수 있습니다. 여기서 핵심은 `Response.render(content)` 메서드를 생성하여 내용을 `bytes`로 반환하는 것입니다: + +{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *} + +이제 다음 대신: + +```json +{"message": "Hello World"} +``` + +이 응답은 이렇게 반환됩니다: + +```json +{ + "message": "Hello World" +} +``` + +물론 JSON 포맷팅보다 더 유용하게 활용할 방법을 찾을 수 있을 것입니다. 😉 + +## 기본 응답 클래스 + +**FastAPI** 클래스 객체 또는 `APIRouter`를 생성할 때 기본적으로 사용할 응답 클래스를 지정할 수 있습니다. + +이를 정의하는 매개변수는 `default_response_class`입니다. + +아래 예제에서 **FastAPI**는 모든 경로 작업에서 기본적으로 `JSONResponse` 대신 `ORJSONResponse`를 사용합니다. + +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} + +/// tip | 팁 + +여전히 이전처럼 *경로 작업*에서 `response_class`를 재정의할 수 있습니다. + +/// + +## 추가 문서화 + +OpenAPI에서 `responses`를 사용하여 미디어 타입 및 기타 세부 정보를 선언할 수도 있습니다: [OpenAPI에서 추가 응답](additional-responses.md){.internal-link target=_blank}. From d51936754d9ab943181472edadc869c317d8a5b0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 15 Feb 2025 11:21:51 +0000 Subject: [PATCH 804/932] =?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 [skip ci] --- 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 8fcf68e5f..ffb5224c1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/advanced/custom-response.md`. PR [#13265](https://github.com/fastapi/fastapi/pull/13265) by [@11kkw](https://github.com/11kkw). * 🌐 Update Korean translation for `docs/ko/docs/tutorial/security/simple-oauth2.md`. PR [#13335](https://github.com/fastapi/fastapi/pull/13335) by [@yes0ng](https://github.com/yes0ng). * 🌐 Add Russian translation for `docs/ru/docs/advanced/response-cookies.md`. PR [#13327](https://github.com/fastapi/fastapi/pull/13327) by [@Stepakinoyan](https://github.com/Stepakinoyan). * 🌐 Add Vietnamese translation for `docs/vi/docs/tutorial/static-files.md`. PR [#11291](https://github.com/fastapi/fastapi/pull/11291) by [@ptt3199](https://github.com/ptt3199). From 10a13d05c4d31978e0255f76baf54b394430c89c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 15 Feb 2025 11:22:43 +0000 Subject: [PATCH 805/932] =?UTF-8?q?=E2=AC=86=20Bump=20cloudflare/wrangler-?= =?UTF-8?q?action=20from=203.13=20to=203.14=20(#13350)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [cloudflare/wrangler-action](https://github.com/cloudflare/wrangler-action) from 3.13 to 3.14. - [Release notes](https://github.com/cloudflare/wrangler-action/releases) - [Changelog](https://github.com/cloudflare/wrangler-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/cloudflare/wrangler-action/compare/v3.13...v3.14) --- updated-dependencies: - dependency-name: cloudflare/wrangler-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/deploy-docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index d9ed61910..0b3096143 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -64,7 +64,7 @@ jobs: BRANCH: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} # TODO: Use v3 when it's fixed, probably in v3.11 # https://github.com/cloudflare/wrangler-action/issues/307 - uses: cloudflare/wrangler-action@v3.13 + uses: cloudflare/wrangler-action@v3.14 # uses: cloudflare/wrangler-action@v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} From b81d29fc0060cb97f5fffb70344c640f3f98a9ad Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 15 Feb 2025 11:23:13 +0000 Subject: [PATCH 806/932] =?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 [skip ci] --- 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 ffb5224c1..c69b20e66 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -30,6 +30,7 @@ hide: ### Internal +* ⬆ Bump cloudflare/wrangler-action from 3.13 to 3.14. PR [#13350](https://github.com/fastapi/fastapi/pull/13350) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump mkdocs-material from 9.5.18 to 9.6.1. PR [#13301](https://github.com/fastapi/fastapi/pull/13301) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pillow from 11.0.0 to 11.1.0. PR [#13300](https://github.com/fastapi/fastapi/pull/13300) by [@dependabot[bot]](https://github.com/apps/dependabot). * 👥 Update FastAPI People - Sponsors. PR [#13295](https://github.com/fastapi/fastapi/pull/13295) by [@tiangolo](https://github.com/tiangolo). From ac893a4446c3157fdf0ac4bbabcda08031676ea2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hyogeun=20Oh=20=28=EC=98=A4=ED=9A=A8=EA=B7=BC=29?= Date: Sat, 15 Feb 2025 20:37:58 +0900 Subject: [PATCH 807/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Korean=20transl?= =?UTF-8?q?ation=20for=20`docs/ko/docs/help-fastapi.md`=20(#13262)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/help-fastapi.md | 287 ++++++++++++++++++++++++----------- 1 file changed, 197 insertions(+), 90 deletions(-) diff --git a/docs/ko/docs/help-fastapi.md b/docs/ko/docs/help-fastapi.md index 932952b4a..06435d4bb 100644 --- a/docs/ko/docs/help-fastapi.md +++ b/docs/ko/docs/help-fastapi.md @@ -1,162 +1,269 @@ -* # FastAPI 지원 - 도움말 받기 +# FastAPI 지원 - 도움 받기 - **FastAPI** 가 마음에 드시나요? +**FastAPI** 가 마음에 드시나요? - FastAPI, 다른 사용자, 개발자를 응원하고 싶으신가요? +FastAPI, 다른 사용자, 개발자를 응원하고 싶으신가요? - 혹은 **FastAPI** 에 대해 도움이 필요하신가요? +혹은 **FastAPI** 에 대해 도움이 필요하신가요? - 아주 간단하게 응원할 수 있습니다 (몇 번의 클릭만으로). +아주 간단하게 응원할 수 있습니다 (몇 번의 클릭만으로). - 또한 도움을 받을 수 있는 방법도 몇 가지 있습니다. +또한 도움을 받을 수 있는 방법도 몇 가지 있습니다. - ## 뉴스레터 구독 +## 뉴스레터 구독 - [**FastAPI와 친구** 뉴스레터](https://github.com/fastapi/fastapi/blob/master/newsletter)를 구독하여 최신 정보를 유지할 수 있습니다{.internal-link target=_blank}: +[**FastAPI and friends** 뉴스레터](newsletter.md){.internal-link target=\_blank}를 구독하여 최신 정보를 유지할 수 있습니다: - - FastAPI 와 그 친구들에 대한 뉴스 🚀 - - 가이드 📝 - - 특징 ✨ - - 획기적인 변화 🚨 - - 팁과 요령 ✅ +* FastAPI and friends에 대한 뉴스 🚀 +* 가이드 📝 +* 기능 ✨ +* 획기적인 변화 🚨 +* 팁과 요령 ✅ - ## 트위터에서 FastAPI 팔로우하기 +## 트위터에서 FastAPI 팔로우하기 - [Follow @fastapi on **Twitter**](https://twitter.com/fastapi) 를 팔로우하여 **FastAPI** 에 대한 최신 뉴스를 얻을 수 있습니다. 🐦 +**Twitter**의 @fastapi를 팔로우하여 **FastAPI** 에 대한 최신 뉴스를 얻을 수 있습니다. 🐦 - ## Star **FastAPI** in GitHub +## Star **FastAPI** in GitHub - GitHub에서 FastAPI에 "star"를 붙일 수 있습니다(오른쪽 상단의 star 버튼을 클릭): https://github.com/fastapi/fastapi. ⭐️ +GitHub에서 FastAPI에 "star"를 붙일 수 있습니다 (오른쪽 상단의 star 버튼을 클릭): https://github.com/fastapi/fastapi. ⭐️ - 스타를 늘림으로써, 다른 사용자들이 좀 더 쉽게 찾을 수 있고, 많은 사람들에게 유용한 것임을 나타낼 수 있습니다. +스타를 늘림으로써, 다른 사용자들이 좀 더 쉽게 찾을 수 있고, 많은 사람들에게 유용한 것임을 나타낼 수 있습니다. - ## GitHub 저장소에서 릴리즈 확인 +## GitHub 저장소에서 릴리즈 확인 - GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀 +GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀 - 여기서 "Releases only"을 선택할 수 있습니다. +여기서 "Releases only"을 선택할 수 있습니다. - 이렇게하면, **FastAPI** 의 버그 수정 및 새로운 기능의 구현 등의 새로운 자료 (최신 버전)이 있을 때마다 (이메일) 통지를 받을 수 있습니다. +이렇게하면, **FastAPI** 의 버그 수정 및 새로운 기능의 구현 등의 새로운 자료 (최신 버전)이 있을 때마다 (이메일) 통지를 받을 수 있습니다. - ## 개발자와의 연결 +## 개발자와의 연결 - 개발자인 [me (Sebastián Ramírez / `tiangolo`)](https://tiangolo.com/) 와 연락을 취할 수 있습니다. +개발자(Sebastián Ramírez / `tiangolo`)와 연락을 취할 수 있습니다. - 여러분은 할 수 있습니다: +여러분은 할 수 있습니다: - - [**GitHub**에서 팔로우하기](https://github.com/tiangolo). - - 당신에게 도움이 될 저의 다른 오픈소스 프로젝트를 확인하십시오. - - 새로운 오픈소스 프로젝트를 만들었을 때 확인하려면 팔로우 하십시오. +* **GitHub**에서 팔로우하기.. + * 당신에게 도움이 될 저의 다른 오픈소스 프로젝트를 확인하십시오. + * 새로운 오픈소스 프로젝트를 만들었을 때 확인하려면 팔로우 하십시오. +* **Twitter** 또는 Mastodon에서 팔로우하기. + * FastAPI의 사용 용도를 알려주세요 (그것을 듣는 것을 좋아합니다). + * 발표나 새로운 툴 출시 소식을 받아보십시오. + * **Twitter**의 @fastapi를 팔로우 (별도 계정에서) 할 수 있습니다. +* **LinkedIn**에서 팔로우하기.. + * 새로운 툴의 발표나 출시 소식을 받아보십시오. (단, Twitter를 더 자주 사용합니다 🤷‍♂). +* **Dev.to** 또는 **Medium**에서 제가 작성한 내용을 읽어 보십시오 (또는 팔로우). + * 다른 기사나 아이디어들을 읽고, 제가 만들어왔던 툴에 대해서도 읽으십시오. + * 새로운 기사를 읽기 위해 팔로우 하십시오. - - [**Twitter**에서 팔로우하기](https://twitter.com/tiangolo). - - FastAPI의 사용 용도를 알려주세요 (그것을 듣는 것을 좋아합니다). - - 발표 또는 새로운 툴 출시할 때 들으십시오. - - [follow @fastapi on Twitter](https://twitter.com/fastapi) (별도 계정에서) 할 수 있습니다. +## **FastAPI**에 대한 트윗 - - [**Linkedin**에서의 연결](https://www.linkedin.com/in/tiangolo/). - - 새로운 툴의 발표나 릴리스를 들을 수 있습니다 (단, Twitter를 더 자주 사용합니다 🤷‍♂). +**FastAPI**에 대해 트윗 하고 FastAPI가 마음에 드는 이유를 알려주세요. 🎉 - - [**Dev.to**](https://dev.to/tiangolo) 또는 [**Medium**](https://medium.com/@tiangolo)에서 제가 작성한 내용을 읽어 보십시오(또는 팔로우). - - 다른 기사나 아이디어들을 읽고, 제가 만들어왔던 툴에 대해서도 읽으십시오. - - 새로운 기사를 읽기 위해 팔로우 하십시오. +**FastAPI**가 어떻게 사용되고 있는지, 어떤 점이 마음에 들었는지, 어떤 프로젝트/회사에서 사용하고 있는지 등에 대해 듣고 싶습니다. - ## **FastAPI**에 대한 트윗 +## FastAPI에 투표하기 - [**FastAPI**에 대해 트윗](https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/fastapi/fastapi) 하고 FastAPI가 마음에 드는 이유를 알려주세요. 🎉 +* Slant에서 **FastAPI** 에 대해 투표하십시오. +* AlternativeTo에서 **FastAPI** 에 대해 투표하십시오. +* StackShare에서 **FastAPI** 에 대해 투표하십시오. - **FastAPI**가 어떻게 사용되고 있는지, 어떤 점이 마음에 들었는지, 어떤 프로젝트/회사에서 사용하고 있는지 등에 대해 듣고 싶습니다. +## GitHub의 이슈로 다른사람 돕기 - ## FastAPI에 투표하기 +다른 사람들의 질문에 도움을 줄 수 있습니다: - - [Slant에서 **FastAPI** 에 대해 투표하십시오](https://www.slant.co/options/34241/~fastapi-review). - - [AlternativeTo**FastAPI** 에 대해 투표하십시오](https://alternativeto.net/software/fastapi/). +* GitHub 디스커션 +* GitHub 이슈 - ## GitHub의 이슈로 다른사람 돕기 +많은 경우, 여러분은 이미 그 질문에 대한 답을 알고 있을 수도 있습니다. 🤓 - [존재하는 이슈](https://github.com/fastapi/fastapi/issues)를 확인하고 그것을 시도하고 도와줄 수 있습니다. 대부분의 경우 이미 답을 알고 있는 질문입니다. 🤓 +만약 많은 사람들의 문제를 도와준다면, 공식적인 [FastAPI 전문가](fastapi-people.md#fastapi-experts){.internal-link target=\_blank} 가 될 것입니다. 🎉 - 많은 사람들의 문제를 도와준다면, 공식적인 [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 가 될 수 있습니다{.internal-link target=_blank}. 🎉 +가장 중요한 점은: 친절하려고 노력하는 것입니다. 사람들은 좌절감을 안고 오며, 많은 경우 최선의 방식으로 질문하지 않을 수도 있습니다. 하지만 최대한 친절하게 대하려고 노력하세요. 🤗 - ## GitHub 저장소 보기 +**FastAPI** 커뮤니티의 목표는 친절하고 환영하는 것입니다. 동시에, 괴롭힘이나 무례한 행동을 받아들이지 마세요. 우리는 서로를 돌봐야 합니다. - GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀 +--- - "Releases only" 대신 "Watching"을 선택하면 다른 사용자가 새로운 issue를 생성할 때 알림이 수신됩니다. +다른 사람들의 질문 (디스커션 또는 이슈에서) 해결을 도울 수 있는 방법은 다음과 같습니다. - 그런 다음 이런 issues를 해결 할 수 있도록 도움을 줄 수 있습니다. +### 질문 이해하기 - ## 이슈 생성하기 +* 질문하는 사람이 가진 **목적**과 사용 사례를 이해할 수 있는지 확인하세요. - GitHub 저장소에 [새로운 이슈 생성](https://github.com/fastapi/fastapi/issues/new/choose) 을 할 수 있습니다, 예를들면 다음과 같습니다: +* 질문 (대부분은 질문입니다)이 **명확**한지 확인하세요. - - **질문**을 하거나 **문제**에 대해 질문합니다. - - 새로운 **기능**을 제안 합니다. +* 많은 경우, 사용자가 가정한 해결책에 대한 질문을 하지만, 더 **좋은** 해결책이 있을 수 있습니다. 문제와 사용 사례를 더 잘 이해하면 더 나은 **대안적인 해결책**을 제안할 수 있습니다. - **참고**: 만약 이슈를 생성한다면, 저는 여러분에게 다른 사람들을 도와달라고 부탁할 것입니다. 😉 +* 질문을 이해할 수 없다면, 더 **자세한 정보**를 요청하세요. - ## Pull Request를 만드십시오 +### 문제 재현하기 - Pull Requests를 이용하여 소스코드에 [컨트리뷰트](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/contributing.md){.internal-link target=_blank} 할 수 있습니다. 예를 들면 다음과 같습니다: +대부분의 경우, 질문은 질문자의 **원본 코드**와 관련이 있습니다. - - 문서에서 찾은 오타를 수정할 때. +많은 경우, 코드의 일부만 복사해서 올리지만, 그것만으로는 **문제를 재현**하기에 충분하지 않습니다. - - FastAPI를 [편집하여](https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml) 작성했거나 찾은 문서, 비디오 또는 팟캐스트를 공유할 때. +* 질문자에게 최소한의 재현 가능한 예제를 제공해달라고 요청하세요. 이렇게 하면 코드를 **복사-붙여넣기**하여 직접 실행하고, 동일한 오류나 동작을 확인하거나 사용 사례를 더 잘 이해할 수 있습니다. - - 해당 섹션의 시작 부분에 링크를 추가했는지 확인하십시오. +* 너그러운 마음이 든다면, 문제 설명만을 기반으로 직접 **예제를 만들어**볼 수도 있습니다. 하지만, 이는 시간이 많이 걸릴 수 있으므로, 먼저 질문을 명확히 해달라고 요청하는 것이 좋습니다. - - 당신의 언어로 [문서 번역하는데](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/contributing.md#translations){.internal-link target=_blank} 기여할 때. +### 해결책 제안하기 - - 또한 다른 사용자가 만든 번역을 검토하는데 도움을 줄 수도 있습니다. +* 질문을 충분히 이해한 후에는 가능한 **답변**을 제공할 수 있습니다. - - 새로운 문서의 섹션을 제안할 때. +* 많은 경우, 질문자의 **근본적인 문제나 사용 사례**를 이해하는 것이 중요합니다. 그들이 시도하는 방법보다 더 나은 해결책이 있을 수 있기 때문입니다. - - 기존 문제/버그를 수정할 때. +### 해결 요청하기 - - 새로운 feature를 추가할 때. +질문자가 답변을 확인하고 나면, 당신이 문제를 해결했을 가능성이 높습니다. 축하합니다, **당신은 영웅입니다**! 🦸 - ## 채팅에 참여하십시오 +* 이제 문제를 해결했다면, 질문자에게 다음을 요청할 수 있습니다. - 👥 [디스코드 채팅 서버](https://discord.gg/VQjSZaeJmf) 👥 에 가입하고 FastAPI 커뮤니티에서 다른 사람들과 어울리세요. + * GitHub 디스커션에서: 댓글을 **답변**으로 표시하도록 요청하세요. + * GitHub 이슈에서: 이슈를 **닫아달라고** 요청하세요. - /// tip +## GitHub 저장소 보기 - 질문이 있는 경우, [GitHub 이슈 ](https://github.com/fastapi/fastapi/issues/new/choose) 에서 질문하십시오, [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 의 도움을 받을 가능성이 높습니다{.internal-link target=_blank} . +GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀 - /// +"Releases only" 대신 "Watching"을 선택하면, 새로운 이슈나 질문이 생성될 때 알림을 받을 수 있습니다. 또한, 특정하게 새로운 이슈, 디스커션, PR 등만 알림 받도록 설정할 수도 있습니다. - ``` - 다른 일반적인 대화에서만 채팅을 사용하십시오. - ``` +그런 다음 이런 이슈들을 해결 할 수 있도록 도움을 줄 수 있습니다. - 기존 [지터 채팅](https://gitter.im/fastapi/fastapi) 이 있지만 채널과 고급기능이 없어서 대화를 하기가 조금 어렵기 때문에 지금은 디스코드가 권장되는 시스템입니다. +## 이슈 생성하기 - ### 질문을 위해 채팅을 사용하지 마십시오 +GitHub 저장소에 새로운 이슈 생성을 할 수 있습니다, 예를들면 다음과 같습니다: - 채팅은 더 많은 "자유로운 대화"를 허용하기 때문에, 너무 일반적인 질문이나 대답하기 어려운 질문을 쉽게 질문을 할 수 있으므로, 답변을 받지 못할 수 있습니다. +* **질문**을 하거나 **문제**에 대해 질문합니다. +* 새로운 **기능**을 제안 합니다. - GitHub 이슈에서의 템플릿은 올바른 질문을 작성하도록 안내하여 더 쉽게 좋은 답변을 얻거나 질문하기 전에 스스로 문제를 해결할 수도 있습니다. 그리고 GitHub에서는 시간이 조금 걸리더라도 항상 모든 것에 답할 수 있습니다. 채팅 시스템에서는 개인적으로 그렇게 할 수 없습니다. 😅 +**참고**: 만약 이슈를 생성한다면, 저는 여러분에게 다른 사람들을 도와달라고 부탁할 것입니다. 😉 - 채팅 시스템에서의 대화 또한 GitHub에서 처럼 쉽게 검색할 수 없기 때문에 대화 중에 질문과 답변이 손실될 수 있습니다. 그리고 GitHub 이슈에 있는 것만 [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts)가 되는 것으로 간주되므로{.internal-link target=_blank} , GitHub 이슈에서 더 많은 관심을 받을 것입니다. +## Pull Requests 리뷰하기 - 반면, 채팅 시스템에는 수천 명의 사용자가 있기 때문에, 거의 항상 대화 상대를 찾을 가능성이 높습니다. 😄 +다른 사람들의 pull request를 리뷰하는 데 도움을 줄 수 있습니다. - ## 개발자 스폰서가 되십시오 +다시 한번 말하지만, 최대한 친절하게 리뷰해 주세요. 🤗 - [GitHub 스폰서](https://github.com/sponsors/tiangolo) 를 통해 개발자를 경제적으로 지원할 수 있습니다. +--- - 감사하다는 말로 커피를 ☕️ 한잔 사줄 수 있습니다. 😄 +Pull Rrquest를 리뷰할 때 고려해야 할 사항과 방법은 다음과 같습니다: - 또한 FastAPI의 실버 또는 골드 스폰서가 될 수 있습니다. 🏅🎉 +### 문제 이해하기 - ## FastAPI를 강화하는 도구의 스폰서가 되십시오 +* 먼저, 해당 pull request가 해결하려는 **문제를 이해하는지** 확인하세요. GitHub 디스커션 또는 이슈에서 더 긴 논의가 있었을 수도 있습니다. - 문서에서 보았듯이, FastAPI는 Starlette과 Pydantic 라는 거인의 어깨에 타고 있습니다. +* Pull request가 필요하지 않을 가능성도 있습니다. **다른 방식**으로 문제를 해결할 수 있다면, 그 방법을 제안하거나 질문할 수 있습니다. - 다음의 스폰서가 될 수 있습니다 +### 스타일에 너무 신경 쓰지 않기 - - [Samuel Colvin (Pydantic)](https://github.com/sponsors/samuelcolvin) - - [Encode (Starlette, Uvicorn)](https://github.com/sponsors/encode) +* 커밋 메시지 스타일 같은 것에 너무 신경 쓰지 않아도 됩니다. 저는 직접 커밋을 수정하여 squash and merge를 수행할 것입니다. - ------ +* 코드 스타일 규칙도 걱정할 필요 없습니다. 이미 자동화된 도구들이 이를 검사하고 있습니다. - 감사합니다! 🚀 +스타일이나 일관성 관련 요청이 필요한 경우, 제가 직접 요청하거나 필요한 변경 사항을 추가 커밋으로 수정할 것입니다. + +### 코드 확인하기 + +* 코드를 읽고, **논리적으로 타당**한지 확인한 후 로컬에서 실행하여 문제가 해결되는지 확인하세요. + +* 그런 다음, 확인했다고 **댓글**을 남겨 주세요. 그래야 제가 검토했음을 알 수 있습니다. + +/// info + +불행히도, 제가 단순히 여러 개의 승인만으로 PR을 신뢰할 수는 없습니다. + +3개, 5개 이상의 승인이 달린 PR이 실제로는 깨져 있거나, 버그가 있거나, 주장하는 문제를 해결하지 못하는 경우가 여러 번 있었습니다. 😅 + +따라서, 정말로 코드를 읽고 실행한 뒤, 댓글로 확인 내용을 남겨 주는 것이 매우 중요합니다. 🤓 + +/// + +* PR을 더 단순하게 만들 수 있다면 그렇게 요청할 수 있지만, 너무 까다로울 필요는 없습니다. 주관적인 견해가 많이 있을 수 있기 때문입니다 (그리고 저도 제 견해가 있을 거예요 🙈). 따라서 핵심적인 부분에 집중하는 것이 좋습니다. + +### 테스트 + +* PR에 **테스트**가 포함되어 있는지 확인하는 데 도움을 주세요. + +* PR을 적용하기 전에 테스트가 **실패**하는지 확인하세요. 🚨 + +* PR을 적용한 후 테스트가 **통과**하는지 확인하세요. ✅ + +* 많은 PR에는 테스트가 없습니다. 테스트를 추가하도록 **상기**시켜줄 수도 있고, 직접 테스트를 **제안**할 수도 있습니다. 이는 시간이 많이 소요되는 부분 중 하나이며, 그 부분을 많이 도와줄 수 있습니다. + +* 그리고 시도한 내용을 댓글로 남겨주세요. 그러면 제가 확인했다는 걸 알 수 있습니다. 🤓 + +## Pull Request를 만드십시오 + +Pull Requests를 이용하여 소스코드에 [컨트리뷰트](contributing.md){.internal-link target=\_blank} 할 수 있습니다. 예를 들면 다음과 같습니다: + +* 문서에서 발견한 오타를 수정할 때. +* FastAPI 관련 문서, 비디오 또는 팟캐스트를 작성했거나 발견하여 이 파일을 편집하여 공유할 때. + * 해당 섹션의 시작 부분에 링크를 추가해야 합니다. +* 당신의 언어로 [문서 번역하는데](contributing.md#translations){.internal-link target=\_blank} 기여할 때. + * 다른 사람이 작성한 번역을 검토하는 것도 도울 수 있습니다. +* 새로운 문서의 섹션을 제안할 때. +* 기존 문제/버그를 수정할 때. + * 테스트를 반드시 추가해야 합니다. +* 새로운 feature를 추가할 때. + * 테스트를 반드시 추가해야 합니다. + * 관련 문서가 필요하다면 반드시 추가해야 합니다. + +## FastAPI 유지 관리에 도움 주기 + +**FastAPI**의 유지 관리를 도와주세요! 🤓 + +할 일이 많고, 그 중 대부분은 **여러분**이 할 수 있습니다. + +지금 할 수 있는 주요 작업은: + +* [GitHub에서 다른 사람들의 질문에 도움 주기](#github_1){.internal-link target=_blank} (위의 섹션을 참조하세요). +* [Pull Request 리뷰하기](#pull-requests){.internal-link target=_blank} (위의 섹션을 참조하세요). + +이 두 작업이 **가장 많은 시간을 소모**하는 일입니다. 그것이 FastAPI 유지 관리의 주요 작업입니다. + +이 작업을 도와주신다면, **FastAPI 유지 관리에 도움을 주는 것**이며 그것이 **더 빠르고 더 잘 발전하는 것**을 보장하는 것입니다. 🚀 + +## 채팅에 참여하십시오 + +👥 디스코드 채팅 서버 👥 에 가입하고 FastAPI 커뮤니티에서 다른 사람들과 어울리세요. + +/// tip + +질문이 있는 경우, GitHub 디스커션 에서 질문하십시오, [FastAPI Experts](fastapi-people.md#fastapi-experts){.internal-link target=_blank} 의 도움을 받을 가능성이 높습니다. + +다른 일반적인 대화에서만 채팅을 사용하십시오. + +/// + +### 질문을 위해 채팅을 사용하지 마십시오 + +채팅은 더 많은 "자유로운 대화"를 허용하기 때문에, 너무 일반적인 질문이나 대답하기 어려운 질문을 쉽게 질문을 할 수 있으므로, 답변을 받지 못할 수 있습니다. + +GitHub 이슈에서의 템플릿은 올바른 질문을 작성하도록 안내하여 더 쉽게 좋은 답변을 얻거나 질문하기 전에 스스로 문제를 해결할 수도 있습니다. 그리고 GitHub에서는 시간이 조금 걸리더라도 항상 모든 것에 답할 수 있습니다. 채팅 시스템에서는 개인적으로 그렇게 할 수 없습니다. 😅 + +채팅 시스템에서의 대화 또한 GitHub에서 처럼 쉽게 검색할 수 없기 때문에 대화 중에 질문과 답변이 손실될 수 있습니다. 그리고 GitHub 이슈에 있는 것만 [FastAPI Expert](fastapi-people.md#fastapi-experts){.internal-link target=_blank}가 되는 것으로 간주되므로, GitHub 이슈에서 더 많은 관심을 받을 것입니다. + +반면, 채팅 시스템에는 수천 명의 사용자가 있기 때문에, 거의 항상 대화 상대를 찾을 가능성이 높습니다. 😄 + +## 개발자 스폰서가 되십시오 + +GitHub 스폰서 를 통해 개발자를 경제적으로 지원할 수 있습니다. + +감사하다는 말로 커피를 ☕️ 한잔 사줄 수 있습니다. 😄 + +또한 FastAPI의 실버 또는 골드 스폰서가 될 수 있습니다. 🏅🎉 + +## FastAPI를 강화하는 도구의 스폰서가 되십시오 + +문서에서 보았듯이, FastAPI는 Starlette과 Pydantic 라는 거인의 어깨에 타고 있습니다. + +다음의 스폰서가 될 수 있습니다 + +* Samuel Colvin (Pydantic) +* Encode (Starlette, Uvicorn) + +--- + +감사합니다! 🚀 From db554ca09426dfa7031a1b07a8b016b48c82c222 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 15 Feb 2025 11:38:21 +0000 Subject: [PATCH 808/932] =?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 [skip ci] --- 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 c69b20e66..88bff8dbc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Update Korean translation for `docs/ko/docs/help-fastapi.md`. PR [#13262](https://github.com/fastapi/fastapi/pull/13262) by [@Zerohertz](https://github.com/Zerohertz). * 🌐 Add Korean translation for `docs/ko/docs/advanced/custom-response.md`. PR [#13265](https://github.com/fastapi/fastapi/pull/13265) by [@11kkw](https://github.com/11kkw). * 🌐 Update Korean translation for `docs/ko/docs/tutorial/security/simple-oauth2.md`. PR [#13335](https://github.com/fastapi/fastapi/pull/13335) by [@yes0ng](https://github.com/yes0ng). * 🌐 Add Russian translation for `docs/ru/docs/advanced/response-cookies.md`. PR [#13327](https://github.com/fastapi/fastapi/pull/13327) by [@Stepakinoyan](https://github.com/Stepakinoyan). From 261bc2d3875ad95ec570a2cb15df6a54af39207f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Haoyu=20=28Daniel=29=20YANG=20=E6=9D=A8=E6=B5=A9=E5=AE=87?= Date: Sat, 15 Feb 2025 12:42:54 +0100 Subject: [PATCH 809/932] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Remove=20duplicate?= =?UTF-8?q?=20title=20in=20docs=20`body-multiple-params`=20(#13345)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/body-multiple-params.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md index 9fced9652..71b308bb4 100644 --- a/docs/en/docs/tutorial/body-multiple-params.md +++ b/docs/en/docs/tutorial/body-multiple-params.md @@ -10,8 +10,6 @@ And you can also declare body parameters as optional, by setting the default to {* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} -## Multiple body parameters - /// note Notice that, in this case, the `item` that would be taken from the body is optional. As it has a `None` default value. From 540d8ff398ececd31c5299d0f6823523efb69c5d Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 15 Feb 2025 11:43:16 +0000 Subject: [PATCH 810/932] =?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 [skip ci] --- 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 88bff8dbc..d5440404b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏️ Remove duplicate title in docs `body-multiple-params`. PR [#13345](https://github.com/fastapi/fastapi/pull/13345) by [@DanielYang59](https://github.com/DanielYang59). * 📝 Fix test badge. PR [#13313](https://github.com/fastapi/fastapi/pull/13313) by [@esadek](https://github.com/esadek). ### Translations From 1e6d95ce6d9ab5bc13796d2d068540e9c765e4c1 Mon Sep 17 00:00:00 2001 From: alv2017 Date: Sat, 15 Feb 2025 16:37:48 +0200 Subject: [PATCH 811/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20`d?= =?UTF-8?q?ependency=5Ftesting`=20(#13223)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- .../test_tutorial001.py | 53 +++++++++---- .../test_tutorial001_an.py | 56 -------------- .../test_tutorial001_an_py310.py | 75 ------------------- .../test_tutorial001_an_py39.py | 75 ------------------- .../test_tutorial001_py310.py | 75 ------------------- 5 files changed, 40 insertions(+), 294 deletions(-) delete mode 100644 tests/test_tutorial/test_testing_dependencies/test_tutorial001_an.py delete mode 100644 tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py310.py delete mode 100644 tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py39.py delete mode 100644 tests/test_tutorial/test_testing_dependencies/test_tutorial001_py310.py diff --git a/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py b/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py index af26307f5..00ee6ab1e 100644 --- a/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py +++ b/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py @@ -1,25 +1,48 @@ -from docs_src.dependency_testing.tutorial001 import ( - app, - client, - test_override_in_items, - test_override_in_items_with_params, - test_override_in_items_with_q, +import importlib +from types import ModuleType + +import pytest + +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="test_module", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], ) +def get_test_module(request: pytest.FixtureRequest) -> ModuleType: + mod: ModuleType = importlib.import_module( + f"docs_src.dependency_testing.{request.param}" + ) + return mod -def test_override_in_items_run(): +def test_override_in_items_run(test_module: ModuleType): + test_override_in_items = test_module.test_override_in_items + test_override_in_items() -def test_override_in_items_with_q_run(): +def test_override_in_items_with_q_run(test_module: ModuleType): + test_override_in_items_with_q = test_module.test_override_in_items_with_q + test_override_in_items_with_q() -def test_override_in_items_with_params_run(): +def test_override_in_items_with_params_run(test_module: ModuleType): + test_override_in_items_with_params = test_module.test_override_in_items_with_params + test_override_in_items_with_params() -def test_override_in_users(): +def test_override_in_users(test_module: ModuleType): + client = test_module.client response = client.get("/users/") assert response.status_code == 200, response.text assert response.json() == { @@ -28,7 +51,8 @@ def test_override_in_users(): } -def test_override_in_users_with_q(): +def test_override_in_users_with_q(test_module: ModuleType): + client = test_module.client response = client.get("/users/?q=foo") assert response.status_code == 200, response.text assert response.json() == { @@ -37,7 +61,8 @@ def test_override_in_users_with_q(): } -def test_override_in_users_with_params(): +def test_override_in_users_with_params(test_module: ModuleType): + client = test_module.client response = client.get("/users/?q=foo&skip=100&limit=200") assert response.status_code == 200, response.text assert response.json() == { @@ -46,7 +71,9 @@ def test_override_in_users_with_params(): } -def test_normal_app(): +def test_normal_app(test_module: ModuleType): + app = test_module.app + client = test_module.client app.dependency_overrides = None response = client.get("/items/?q=foo&skip=100&limit=200") assert response.status_code == 200, response.text diff --git a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an.py b/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an.py deleted file mode 100644 index fc1f9149a..000000000 --- a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an.py +++ /dev/null @@ -1,56 +0,0 @@ -from docs_src.dependency_testing.tutorial001_an import ( - app, - client, - test_override_in_items, - test_override_in_items_with_params, - test_override_in_items_with_q, -) - - -def test_override_in_items_run(): - test_override_in_items() - - -def test_override_in_items_with_q_run(): - test_override_in_items_with_q() - - -def test_override_in_items_with_params_run(): - test_override_in_items_with_params() - - -def test_override_in_users(): - response = client.get("/users/") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": None, "skip": 5, "limit": 10}, - } - - -def test_override_in_users_with_q(): - response = client.get("/users/?q=foo") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -def test_override_in_users_with_params(): - response = client.get("/users/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -def test_normal_app(): - app.dependency_overrides = None - response = client.get("/items/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Items!", - "params": {"q": "foo", "skip": 100, "limit": 200}, - } diff --git a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py310.py b/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py310.py deleted file mode 100644 index a3d27f47f..000000000 --- a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py310.py +++ /dev/null @@ -1,75 +0,0 @@ -from ...utils import needs_py310 - - -@needs_py310 -def test_override_in_items_run(): - from docs_src.dependency_testing.tutorial001_an_py310 import test_override_in_items - - test_override_in_items() - - -@needs_py310 -def test_override_in_items_with_q_run(): - from docs_src.dependency_testing.tutorial001_an_py310 import ( - test_override_in_items_with_q, - ) - - test_override_in_items_with_q() - - -@needs_py310 -def test_override_in_items_with_params_run(): - from docs_src.dependency_testing.tutorial001_an_py310 import ( - test_override_in_items_with_params, - ) - - test_override_in_items_with_params() - - -@needs_py310 -def test_override_in_users(): - from docs_src.dependency_testing.tutorial001_an_py310 import client - - response = client.get("/users/") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": None, "skip": 5, "limit": 10}, - } - - -@needs_py310 -def test_override_in_users_with_q(): - from docs_src.dependency_testing.tutorial001_an_py310 import client - - response = client.get("/users/?q=foo") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -@needs_py310 -def test_override_in_users_with_params(): - from docs_src.dependency_testing.tutorial001_an_py310 import client - - response = client.get("/users/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -@needs_py310 -def test_normal_app(): - from docs_src.dependency_testing.tutorial001_an_py310 import app, client - - app.dependency_overrides = None - response = client.get("/items/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Items!", - "params": {"q": "foo", "skip": 100, "limit": 200}, - } diff --git a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py39.py b/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py39.py deleted file mode 100644 index f03ed5e07..000000000 --- a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py39.py +++ /dev/null @@ -1,75 +0,0 @@ -from ...utils import needs_py39 - - -@needs_py39 -def test_override_in_items_run(): - from docs_src.dependency_testing.tutorial001_an_py39 import test_override_in_items - - test_override_in_items() - - -@needs_py39 -def test_override_in_items_with_q_run(): - from docs_src.dependency_testing.tutorial001_an_py39 import ( - test_override_in_items_with_q, - ) - - test_override_in_items_with_q() - - -@needs_py39 -def test_override_in_items_with_params_run(): - from docs_src.dependency_testing.tutorial001_an_py39 import ( - test_override_in_items_with_params, - ) - - test_override_in_items_with_params() - - -@needs_py39 -def test_override_in_users(): - from docs_src.dependency_testing.tutorial001_an_py39 import client - - response = client.get("/users/") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": None, "skip": 5, "limit": 10}, - } - - -@needs_py39 -def test_override_in_users_with_q(): - from docs_src.dependency_testing.tutorial001_an_py39 import client - - response = client.get("/users/?q=foo") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -@needs_py39 -def test_override_in_users_with_params(): - from docs_src.dependency_testing.tutorial001_an_py39 import client - - response = client.get("/users/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -@needs_py39 -def test_normal_app(): - from docs_src.dependency_testing.tutorial001_an_py39 import app, client - - app.dependency_overrides = None - response = client.get("/items/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Items!", - "params": {"q": "foo", "skip": 100, "limit": 200}, - } diff --git a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_py310.py b/tests/test_tutorial/test_testing_dependencies/test_tutorial001_py310.py deleted file mode 100644 index 776b916ff..000000000 --- a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_py310.py +++ /dev/null @@ -1,75 +0,0 @@ -from ...utils import needs_py310 - - -@needs_py310 -def test_override_in_items_run(): - from docs_src.dependency_testing.tutorial001_py310 import test_override_in_items - - test_override_in_items() - - -@needs_py310 -def test_override_in_items_with_q_run(): - from docs_src.dependency_testing.tutorial001_py310 import ( - test_override_in_items_with_q, - ) - - test_override_in_items_with_q() - - -@needs_py310 -def test_override_in_items_with_params_run(): - from docs_src.dependency_testing.tutorial001_py310 import ( - test_override_in_items_with_params, - ) - - test_override_in_items_with_params() - - -@needs_py310 -def test_override_in_users(): - from docs_src.dependency_testing.tutorial001_py310 import client - - response = client.get("/users/") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": None, "skip": 5, "limit": 10}, - } - - -@needs_py310 -def test_override_in_users_with_q(): - from docs_src.dependency_testing.tutorial001_py310 import client - - response = client.get("/users/?q=foo") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -@needs_py310 -def test_override_in_users_with_params(): - from docs_src.dependency_testing.tutorial001_py310 import client - - response = client.get("/users/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -@needs_py310 -def test_normal_app(): - from docs_src.dependency_testing.tutorial001_py310 import app, client - - app.dependency_overrides = None - response = client.get("/items/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Items!", - "params": {"q": "foo", "skip": 100, "limit": 200}, - } From cbd7b986e7108ea5cb79eb653e37e0073bd22645 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 15 Feb 2025 14:38:14 +0000 Subject: [PATCH 812/932] =?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 [skip ci] --- 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 d5440404b..28821455a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Refactors + +* ✅ Simplify tests for `dependency_testing`. PR [#13223](https://github.com/fastapi/fastapi/pull/13223) by [@alv2017](https://github.com/alv2017). + ### Docs * ✏️ Remove duplicate title in docs `body-multiple-params`. PR [#13345](https://github.com/fastapi/fastapi/pull/13345) by [@DanielYang59](https://github.com/DanielYang59). From f6872dd29849a07a8cfd475c7c56dfa3f3ea5808 Mon Sep 17 00:00:00 2001 From: alv2017 Date: Sat, 15 Feb 2025 16:42:41 +0200 Subject: [PATCH 813/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20`a?= =?UTF-8?q?pp=5Ftesting`=20(#13220)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- .../test_tutorial/test_testing/test_main_b.py | 25 +++++++++++++++++-- .../test_testing/test_main_b_an.py | 10 -------- .../test_testing/test_main_b_an_py310.py | 13 ---------- .../test_testing/test_main_b_an_py39.py | 13 ---------- .../test_testing/test_main_b_py310.py | 13 ---------- 5 files changed, 23 insertions(+), 51 deletions(-) delete mode 100644 tests/test_tutorial/test_testing/test_main_b_an.py delete mode 100644 tests/test_tutorial/test_testing/test_main_b_an_py310.py delete mode 100644 tests/test_tutorial/test_testing/test_main_b_an_py39.py delete mode 100644 tests/test_tutorial/test_testing/test_main_b_py310.py diff --git a/tests/test_tutorial/test_testing/test_main_b.py b/tests/test_tutorial/test_testing/test_main_b.py index 1e1836f5b..aa7f969c6 100644 --- a/tests/test_tutorial/test_testing/test_main_b.py +++ b/tests/test_tutorial/test_testing/test_main_b.py @@ -1,7 +1,28 @@ -from docs_src.app_testing.app_b import test_main +import importlib +from types import ModuleType +import pytest -def test_app(): +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="test_module", + params=[ + "app_b.test_main", + pytest.param("app_b_py310.test_main", marks=needs_py310), + "app_b_an.test_main", + pytest.param("app_b_an_py39.test_main", marks=needs_py39), + pytest.param("app_b_an_py310.test_main", marks=needs_py310), + ], +) +def get_test_module(request: pytest.FixtureRequest) -> ModuleType: + mod: ModuleType = importlib.import_module(f"docs_src.app_testing.{request.param}") + return mod + + +def test_app(test_module: ModuleType): + test_main = test_module test_main.test_create_existing_item() test_main.test_create_item() test_main.test_create_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_an.py b/tests/test_tutorial/test_testing/test_main_b_an.py deleted file mode 100644 index e53fc3224..000000000 --- a/tests/test_tutorial/test_testing/test_main_b_an.py +++ /dev/null @@ -1,10 +0,0 @@ -from docs_src.app_testing.app_b_an import test_main - - -def test_app(): - test_main.test_create_existing_item() - test_main.test_create_item() - test_main.test_create_item_bad_token() - test_main.test_read_nonexistent_item() - test_main.test_read_item() - test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_an_py310.py b/tests/test_tutorial/test_testing/test_main_b_an_py310.py deleted file mode 100644 index c974e5dc1..000000000 --- a/tests/test_tutorial/test_testing/test_main_b_an_py310.py +++ /dev/null @@ -1,13 +0,0 @@ -from ...utils import needs_py310 - - -@needs_py310 -def test_app(): - from docs_src.app_testing.app_b_an_py310 import test_main - - test_main.test_create_existing_item() - test_main.test_create_item() - test_main.test_create_item_bad_token() - test_main.test_read_nonexistent_item() - test_main.test_read_item() - test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_an_py39.py b/tests/test_tutorial/test_testing/test_main_b_an_py39.py deleted file mode 100644 index 71f99726c..000000000 --- a/tests/test_tutorial/test_testing/test_main_b_an_py39.py +++ /dev/null @@ -1,13 +0,0 @@ -from ...utils import needs_py39 - - -@needs_py39 -def test_app(): - from docs_src.app_testing.app_b_an_py39 import test_main - - test_main.test_create_existing_item() - test_main.test_create_item() - test_main.test_create_item_bad_token() - test_main.test_read_nonexistent_item() - test_main.test_read_item() - test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_py310.py b/tests/test_tutorial/test_testing/test_main_b_py310.py deleted file mode 100644 index e30cdc073..000000000 --- a/tests/test_tutorial/test_testing/test_main_b_py310.py +++ /dev/null @@ -1,13 +0,0 @@ -from ...utils import needs_py310 - - -@needs_py310 -def test_app(): - from docs_src.app_testing.app_b_py310 import test_main - - test_main.test_create_existing_item() - test_main.test_create_item() - test_main.test_create_item_bad_token() - test_main.test_read_nonexistent_item() - test_main.test_read_item() - test_main.test_read_item_bad_token() From 2c937aabefe45b109edde6bc929721c2343804eb Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 15 Feb 2025 14:43:05 +0000 Subject: [PATCH 814/932] =?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 [skip ci] --- 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 28821455a..9eacfea86 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for `app_testing`. PR [#13220](https://github.com/fastapi/fastapi/pull/13220) by [@alv2017](https://github.com/alv2017). * ✅ Simplify tests for `dependency_testing`. PR [#13223](https://github.com/fastapi/fastapi/pull/13223) by [@alv2017](https://github.com/alv2017). ### Docs From 9ec452a154e15e4af0f57f51a4fe1fee58879c4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 15 Feb 2025 17:23:59 +0100 Subject: [PATCH 815/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20docs=20for=20Qu?= =?UTF-8?q?ery=20Params=20and=20String=20Validations,=20remove=20obsolete?= =?UTF-8?q?=20Ellipsis=20docs=20(`...`)=20(#13377)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tutorial/query-params-str-validations.md | 16 --- .../tutorial/query-params-str-validations.md | 28 ----- .../tutorial/query-params-str-validations.md | 117 +++--------------- .../tutorial/query-params-str-validations.md | 16 --- .../tutorial/query-params-str-validations.md | 28 ----- .../tutorial/query-params-str-validations.md | 27 ---- .../tutorial006b.py | 11 -- .../tutorial006b_an.py | 12 -- .../tutorial006b_an_py39.py | 13 -- .../tutorial006c.py | 2 +- .../tutorial006c_an.py | 2 +- .../tutorial006c_an_py310.py | 2 +- .../tutorial006c_an_py39.py | 2 +- .../tutorial006c_py310.py | 2 +- .../tutorial006d.py | 11 -- .../tutorial006d_an.py | 12 -- .../tutorial006d_an_py39.py | 13 -- 17 files changed, 20 insertions(+), 294 deletions(-) delete mode 100644 docs_src/query_params_str_validations/tutorial006b.py delete mode 100644 docs_src/query_params_str_validations/tutorial006b_an.py delete mode 100644 docs_src/query_params_str_validations/tutorial006b_an_py39.py delete mode 100644 docs_src/query_params_str_validations/tutorial006d.py delete mode 100644 docs_src/query_params_str_validations/tutorial006d_an.py delete mode 100644 docs_src/query_params_str_validations/tutorial006d_an_py39.py diff --git a/docs/de/docs/tutorial/query-params-str-validations.md b/docs/de/docs/tutorial/query-params-str-validations.md index f181d501c..de8879ce8 100644 --- a/docs/de/docs/tutorial/query-params-str-validations.md +++ b/docs/de/docs/tutorial/query-params-str-validations.md @@ -315,22 +315,6 @@ Wenn Sie einen Parameter erforderlich machen wollen, während Sie `Query` verwen {* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} -### Erforderlich mit Ellipse (`...`) - -Es gibt eine Alternative, die explizit deklariert, dass ein Wert erforderlich ist. Sie können als Default das Literal `...` setzen: - -{* ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py hl[9] *} - -/// info - -Falls Sie das `...` bisher noch nicht gesehen haben: Es ist ein spezieller einzelner Wert, Teil von Python und wird „Ellipsis“ genannt (Deutsch: Ellipse). - -Es wird von Pydantic und FastAPI verwendet, um explizit zu deklarieren, dass ein Wert erforderlich ist. - -/// - -Dies wird **FastAPI** wissen lassen, dass dieser Parameter erforderlich ist. - ### Erforderlich, kann `None` sein Sie können deklarieren, dass ein Parameter `None` akzeptiert, aber dennoch erforderlich ist. Das zwingt Clients, den Wert zu senden, selbst wenn er `None` ist. diff --git a/docs/em/docs/tutorial/query-params-str-validations.md b/docs/em/docs/tutorial/query-params-str-validations.md index dbaab5735..fd077bf8f 100644 --- a/docs/em/docs/tutorial/query-params-str-validations.md +++ b/docs/em/docs/tutorial/query-params-str-validations.md @@ -148,22 +148,6 @@ q: Union[str, None] = Query(default=None, min_length=3) {* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} -### ✔ ⏮️ ❕ (`...`) - -📤 🎛 🌌 🎯 📣 👈 💲 ✔. 👆 💪 ⚒ `default` 🔢 🔑 💲 `...`: - -{* ../../docs_src/query_params_str_validations/tutorial006b.py hl[7] *} - -/// info - -🚥 👆 🚫 👀 👈 `...` ⏭: ⚫️ 🎁 👁 💲, ⚫️ 🍕 🐍 & 🤙 "❕". - -⚫️ ⚙️ Pydantic & FastAPI 🎯 📣 👈 💲 ✔. - -/// - -👉 🔜 ➡️ **FastAPI** 💭 👈 👉 🔢 ✔. - ### ✔ ⏮️ `None` 👆 💪 📣 👈 🔢 💪 🚫 `None`, ✋️ 👈 ⚫️ ✔. 👉 🔜 ⚡ 👩‍💻 📨 💲, 🚥 💲 `None`. @@ -178,18 +162,6 @@ Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ /// -### ⚙️ Pydantic `Required` ↩️ ❕ (`...`) - -🚥 👆 💭 😬 ⚙️ `...`, 👆 💪 🗄 & ⚙️ `Required` ⚪️➡️ Pydantic: - -{* ../../docs_src/query_params_str_validations/tutorial006d.py hl[2,8] *} - -/// tip - -💭 👈 🌅 💼, 🕐❔ 🕳 🚚, 👆 💪 🎯 🚫 `default` 🔢, 👆 🛎 🚫 ✔️ ⚙️ `...` 🚫 `Required`. - -/// - ## 🔢 🔢 📇 / 💗 💲 🕐❔ 👆 🔬 🔢 🔢 🎯 ⏮️ `Query` 👆 💪 📣 ⚫️ 📨 📇 💲, ⚖️ 🙆‍♀ 🎏 🌌, 📨 💗 💲. diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index 1bf16334d..511099186 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -6,13 +6,13 @@ Let's take this application as example: {* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *} -The query parameter `q` is of type `Union[str, None]` (or `str | None` in Python 3.10), that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required. +The query parameter `q` is of type `str | None`, that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required. /// note FastAPI will know that the value of `q` is not required because of the default value `= None`. -The `Union` in `Union[str, None]` will allow your editor to give you better support and detect errors. +Having `str | None` will allow your editor to give you better support and detect errors. /// @@ -25,29 +25,9 @@ We are going to enforce that even though `q` is optional, whenever it is provide To achieve that, first import: * `Query` from `fastapi` -* `Annotated` from `typing` (or from `typing_extensions` in Python below 3.9) +* `Annotated` from `typing` -//// tab | Python 3.10+ - -In Python 3.9 or above, `Annotated` is part of the standard library, so you can import it from `typing`. - -```Python hl_lines="1 3" -{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -In versions of Python below Python 3.9 you import `Annotated` from `typing_extensions`. - -It will already be installed with FastAPI. - -```Python hl_lines="3-4" -{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[1,3] *} /// info @@ -145,54 +125,23 @@ As in this case (without using `Annotated`) we have to replace the default value So: -```Python -q: Union[str, None] = Query(default=None) -``` - -...makes the parameter optional, with a default value of `None`, the same as: - -```Python -q: Union[str, None] = None -``` - -And in Python 3.10 and above: - ```Python q: str | None = Query(default=None) ``` ...makes the parameter optional, with a default value of `None`, the same as: -```Python -q: str | None = None -``` - -But the `Query` versions declare it explicitly as being a query parameter. - -/// info - -Keep in mind that the most important part to make a parameter optional is the part: ```Python -= None -``` - -or the: - -```Python -= Query(default=None) +q: str | None = None ``` -as it will use that `None` as the default value, and that way make the parameter **not required**. - -The `Union[str, None]` part allows your editor to provide better support, but it is not what tells FastAPI that this parameter is not required. - -/// +But the `Query` version declares it explicitly as being a query parameter. Then, we can pass more parameters to `Query`. In this case, the `max_length` parameter that applies to strings: ```Python -q: Union[str, None] = Query(default=None, max_length=50) +q: str | None = Query(default=None, max_length=50) ``` This will validate the data, show a clear error when the data is not valid, and document the parameter in the OpenAPI schema *path operation*. @@ -201,7 +150,7 @@ This will validate the data, show a clear error when the data is not valid, and Keep in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`. -Instead use the actual default value of the function parameter. Otherwise, it would be inconsistent. +Instead, use the actual default value of the function parameter. Otherwise, it would be inconsistent. For example, this is not allowed: @@ -255,7 +204,7 @@ This specific regular expression pattern checks that the received parameter valu If you feel lost with all these **"regular expression"** ideas, don't worry. They are a hard topic for many people. You can still do a lot of stuff without needing regular expressions yet. -But whenever you need them and go and learn them, know that you can already use them directly in **FastAPI**. +Now you know that whenever you need them you can use them in **FastAPI**. ### Pydantic v1 `regex` instead of `pattern` @@ -296,7 +245,7 @@ q: str instead of: ```Python -q: Union[str, None] = None +q: str | None = None ``` But we are now declaring it with `Query`, for example like: @@ -304,15 +253,7 @@ But we are now declaring it with `Query`, for example like: //// tab | Annotated ```Python -q: Annotated[Union[str, None], Query(min_length=3)] = None -``` - -//// - -//// tab | non-Annotated - -```Python -q: Union[str, None] = Query(default=None, min_length=3) +q: Annotated[str | None, Query(min_length=3)] = None ``` //// @@ -321,42 +262,14 @@ So, when you need to declare a value as required while using `Query`, you can si {* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} -### Required with Ellipsis (`...`) - -There's an alternative way to explicitly declare that a value is required. You can set the default to the literal value `...`: - -{* ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py hl[9] *} - -/// info - -If you hadn't seen that `...` before: it is a special single value, it is part of Python and is called "Ellipsis". - -It is used by Pydantic and FastAPI to explicitly declare that a value is required. - -/// - -This will let **FastAPI** know that this parameter is required. - ### Required, can be `None` You can declare that a parameter can accept `None`, but that it's still required. This would force clients to send a value, even if the value is `None`. -To do that, you can declare that `None` is a valid type but still use `...` as the default: +To do that, you can declare that `None` is a valid type but simply do not declare a default value: {* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} -/// tip - -Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required fields. - -/// - -/// tip - -Remember that in most of the cases, when something is required, you can simply omit the default, so you normally don't have to use `...`. - -/// - ## Query parameter list / multiple values When you define a query parameter explicitly with `Query` you can also declare it to receive a list of values, or said in another way, to receive multiple values. @@ -396,7 +309,7 @@ The interactive API docs will update accordingly, to allow multiple values: ### Query parameter list / multiple values with defaults -And you can also define a default `list` of values if none are provided: +You can also define a default `list` of values if none are provided: {* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *} @@ -419,7 +332,7 @@ the default of `q` will be: `["foo", "bar"]` and your response will be: #### Using just `list` -You can also use `list` directly instead of `List[str]` (or `list[str]` in Python 3.9+): +You can also use `list` directly instead of `list[str]`: {* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *} @@ -427,7 +340,7 @@ You can also use `list` directly instead of `List[str]` (or `list[str]` in Pytho Keep in mind that in this case, FastAPI won't check the contents of the list. -For example, `List[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't. +For example, `list[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't. /// diff --git a/docs/es/docs/tutorial/query-params-str-validations.md b/docs/es/docs/tutorial/query-params-str-validations.md index f378b9dce..9cb76156f 100644 --- a/docs/es/docs/tutorial/query-params-str-validations.md +++ b/docs/es/docs/tutorial/query-params-str-validations.md @@ -321,22 +321,6 @@ Así que, cuando necesites declarar un valor como requerido mientras usas `Query {* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} -### Requerido con Puntos suspensivos (`...`) - -Hay una manera alternativa de declarar explícitamente que un valor es requerido. Puedes establecer el valor por defecto al valor literal `...`: - -{* ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py hl[9] *} - -/// info | Información - -Si no habías visto eso `...` antes: es un valor especial único, es parte de Python y se llama "Ellipsis". - -Se usa por Pydantic y FastAPI para declarar explícitamente que un valor es requerido. - -/// - -Esto le permitirá a **FastAPI** saber que este parámetro es requerido. - ### Requerido, puede ser `None` Puedes declarar que un parámetro puede aceptar `None`, pero que aún así es requerido. Esto obligaría a los clientes a enviar un valor, incluso si el valor es `None`. diff --git a/docs/ru/docs/tutorial/query-params-str-validations.md b/docs/ru/docs/tutorial/query-params-str-validations.md index 32a98ff22..13b7015db 100644 --- a/docs/ru/docs/tutorial/query-params-str-validations.md +++ b/docs/ru/docs/tutorial/query-params-str-validations.md @@ -291,22 +291,6 @@ q: Union[str, None] = Query(default=None, min_length=3) {* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} -### Обязательный параметр с Ellipsis (`...`) - -Альтернативный способ указать обязательность параметра запроса - это указать параметр `default` через многоточие `...`: - -{* ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py hl[9] *} - -/// info | Дополнительная информация - -Если вы ранее не сталкивались с `...`: это специальное значение, часть языка Python и называется "Ellipsis". - -Используется в Pydantic и FastAPI для определения, что значение требуется обязательно. - -/// - -Таким образом, **FastAPI** определяет, что параметр является обязательным. - ### Обязательный параметр с `None` Вы можете определить, что параметр может принимать `None`, но всё ещё является обязательным. Это может потребоваться для того, чтобы пользователи явно указали параметр, даже если его значение будет `None`. @@ -321,18 +305,6 @@ Pydantic, мощь которого используется в FastAPI для /// -### Использование Pydantic's `Required` вместо Ellipsis (`...`) - -Если вас смущает `...`, вы можете использовать `Required` из Pydantic: - -{* ../../docs_src/query_params_str_validations/tutorial006d_an_py39.py hl[4,10] *} - -/// tip | Подсказка - -Запомните, когда вам необходимо объявить query-параметр обязательным, вы можете просто не указывать параметр `default`. Таким образом, вам редко придётся использовать `...` или `Required`. - -/// - ## Множество значений для query-параметра Для query-параметра `Query` можно указать, что он принимает список значений (множество значений). diff --git a/docs/zh/docs/tutorial/query-params-str-validations.md b/docs/zh/docs/tutorial/query-params-str-validations.md index 2fba671f7..c2f9a7e9f 100644 --- a/docs/zh/docs/tutorial/query-params-str-validations.md +++ b/docs/zh/docs/tutorial/query-params-str-validations.md @@ -108,21 +108,6 @@ q: Union[str, None] = Query(default=None, min_length=3) {* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} -### 使用省略号(`...`)声明必需参数 - -有另一种方法可以显式的声明一个值是必需的,即将默认参数的默认值设为 `...` : - -{* ../../docs_src/query_params_str_validations/tutorial006b.py hl[7] *} - -/// info - -如果你之前没见过 `...` 这种用法:它是一个特殊的单独值,它是 Python 的一部分并且被称为“Ellipsis”(意为省略号 —— 译者注)。 -Pydantic 和 FastAPI 使用它来显式的声明需要一个值。 - -/// - -这将使 **FastAPI** 知道此查询参数是必需的。 - ### 使用`None`声明必需参数 你可以声明一个参数可以接收`None`值,但它仍然是必需的。这将强制客户端发送一个值,即使该值是`None`。 @@ -137,18 +122,6 @@ Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没 /// -### 使用Pydantic中的`Required`代替省略号(`...`) - -如果你觉得使用 `...` 不舒服,你也可以从 Pydantic 导入并使用 `Required`: - -{* ../../docs_src/query_params_str_validations/tutorial006d.py hl[2,8] *} - -/// tip - -请记住,在大多数情况下,当你需要某些东西时,可以简单地省略 `default` 参数,因此你通常不必使用 `...` 或 `Required` - -/// - ## 查询参数列表 / 多个值 当你使用 `Query` 显式地定义查询参数时,你还可以声明它去接收一组值,或换句话来说,接收多个值。 diff --git a/docs_src/query_params_str_validations/tutorial006b.py b/docs_src/query_params_str_validations/tutorial006b.py deleted file mode 100644 index a8d69c889..000000000 --- a/docs_src/query_params_str_validations/tutorial006b.py +++ /dev/null @@ -1,11 +0,0 @@ -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: str = Query(default=..., min_length=3)): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006b_an.py b/docs_src/query_params_str_validations/tutorial006b_an.py deleted file mode 100644 index ea3b02583..000000000 --- a/docs_src/query_params_str_validations/tutorial006b_an.py +++ /dev/null @@ -1,12 +0,0 @@ -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = ...): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006b_an_py39.py b/docs_src/query_params_str_validations/tutorial006b_an_py39.py deleted file mode 100644 index 687a9f544..000000000 --- a/docs_src/query_params_str_validations/tutorial006b_an_py39.py +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Annotated - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = ...): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006c.py b/docs_src/query_params_str_validations/tutorial006c.py index 2ac148c94..0a0e820da 100644 --- a/docs_src/query_params_str_validations/tutorial006c.py +++ b/docs_src/query_params_str_validations/tutorial006c.py @@ -6,7 +6,7 @@ app = FastAPI() @app.get("/items/") -async def read_items(q: Union[str, None] = Query(default=..., min_length=3)): +async def read_items(q: Union[str, None] = Query(min_length=3)): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006c_an.py b/docs_src/query_params_str_validations/tutorial006c_an.py index 10bf26a57..55c4f4adc 100644 --- a/docs_src/query_params_str_validations/tutorial006c_an.py +++ b/docs_src/query_params_str_validations/tutorial006c_an.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") -async def read_items(q: Annotated[Union[str, None], Query(min_length=3)] = ...): +async def read_items(q: Annotated[Union[str, None], Query(min_length=3)]): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006c_an_py310.py b/docs_src/query_params_str_validations/tutorial006c_an_py310.py index 1ab0a7d53..2995d9c97 100644 --- a/docs_src/query_params_str_validations/tutorial006c_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial006c_an_py310.py @@ -6,7 +6,7 @@ app = FastAPI() @app.get("/items/") -async def read_items(q: Annotated[str | None, Query(min_length=3)] = ...): +async def read_items(q: Annotated[str | None, Query(min_length=3)]): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006c_an_py39.py b/docs_src/query_params_str_validations/tutorial006c_an_py39.py index ac1273331..76a1cd49a 100644 --- a/docs_src/query_params_str_validations/tutorial006c_an_py39.py +++ b/docs_src/query_params_str_validations/tutorial006c_an_py39.py @@ -6,7 +6,7 @@ app = FastAPI() @app.get("/items/") -async def read_items(q: Annotated[Union[str, None], Query(min_length=3)] = ...): +async def read_items(q: Annotated[Union[str, None], Query(min_length=3)]): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006c_py310.py b/docs_src/query_params_str_validations/tutorial006c_py310.py index 82dd9e5d7..88b499c7a 100644 --- a/docs_src/query_params_str_validations/tutorial006c_py310.py +++ b/docs_src/query_params_str_validations/tutorial006c_py310.py @@ -4,7 +4,7 @@ app = FastAPI() @app.get("/items/") -async def read_items(q: str | None = Query(default=..., min_length=3)): +async def read_items(q: str | None = Query(min_length=3)): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006d.py b/docs_src/query_params_str_validations/tutorial006d.py deleted file mode 100644 index a8d69c889..000000000 --- a/docs_src/query_params_str_validations/tutorial006d.py +++ /dev/null @@ -1,11 +0,0 @@ -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: str = Query(default=..., min_length=3)): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006d_an.py b/docs_src/query_params_str_validations/tutorial006d_an.py deleted file mode 100644 index ea3b02583..000000000 --- a/docs_src/query_params_str_validations/tutorial006d_an.py +++ /dev/null @@ -1,12 +0,0 @@ -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = ...): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006d_an_py39.py b/docs_src/query_params_str_validations/tutorial006d_an_py39.py deleted file mode 100644 index 687a9f544..000000000 --- a/docs_src/query_params_str_validations/tutorial006d_an_py39.py +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Annotated - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = ...): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results From 2e788bbbdce346ab53f972cc87ecceeba2299bbe Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 15 Feb 2025 16:24:24 +0000 Subject: [PATCH 816/932] =?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 [skip ci] --- 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 9eacfea86..6a3ec5b73 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Docs +* 📝 Update docs for Query Params and String Validations, remove obsolete Ellipsis docs (`...`). PR [#13377](https://github.com/fastapi/fastapi/pull/13377) by [@tiangolo](https://github.com/tiangolo). * ✏️ Remove duplicate title in docs `body-multiple-params`. PR [#13345](https://github.com/fastapi/fastapi/pull/13345) by [@DanielYang59](https://github.com/DanielYang59). * 📝 Fix test badge. PR [#13313](https://github.com/fastapi/fastapi/pull/13313) by [@esadek](https://github.com/esadek). From 08b817a84294a7e606f8437d11ee75fd3ef207a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 15 Feb 2025 17:28:09 +0100 Subject: [PATCH 817/932] =?UTF-8?q?=F0=9F=94=A5=20Remove=20manual=20type?= =?UTF-8?q?=20annotations=20in=20JWT=20tutorial=20to=20avoid=20typing=20ex?= =?UTF-8?q?pectations=20(JWT=20doesn't=20provide=20more=20types)=20(#13378?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs_src/security/tutorial004.py | 2 +- docs_src/security/tutorial004_an.py | 2 +- docs_src/security/tutorial004_an_py310.py | 2 +- docs_src/security/tutorial004_an_py39.py | 2 +- docs_src/security/tutorial004_py310.py | 2 +- docs_src/security/tutorial005_an.py | 2 +- docs_src/security/tutorial005_an_py310.py | 2 +- docs_src/security/tutorial005_an_py39.py | 6 +++--- 8 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs_src/security/tutorial004.py b/docs_src/security/tutorial004.py index 91d161b8a..222589618 100644 --- a/docs_src/security/tutorial004.py +++ b/docs_src/security/tutorial004.py @@ -95,7 +95,7 @@ async def get_current_user(token: str = Depends(oauth2_scheme)): ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) diff --git a/docs_src/security/tutorial004_an.py b/docs_src/security/tutorial004_an.py index df50754af..e2221cd39 100644 --- a/docs_src/security/tutorial004_an.py +++ b/docs_src/security/tutorial004_an.py @@ -96,7 +96,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) diff --git a/docs_src/security/tutorial004_an_py310.py b/docs_src/security/tutorial004_an_py310.py index eff54ef01..a3f74fc0e 100644 --- a/docs_src/security/tutorial004_an_py310.py +++ b/docs_src/security/tutorial004_an_py310.py @@ -95,7 +95,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) diff --git a/docs_src/security/tutorial004_an_py39.py b/docs_src/security/tutorial004_an_py39.py index 0455b500c..b33d677ed 100644 --- a/docs_src/security/tutorial004_an_py39.py +++ b/docs_src/security/tutorial004_an_py39.py @@ -95,7 +95,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) diff --git a/docs_src/security/tutorial004_py310.py b/docs_src/security/tutorial004_py310.py index 78bee22a3..d46ce26bf 100644 --- a/docs_src/security/tutorial004_py310.py +++ b/docs_src/security/tutorial004_py310.py @@ -94,7 +94,7 @@ async def get_current_user(token: str = Depends(oauth2_scheme)): ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) diff --git a/docs_src/security/tutorial005_an.py b/docs_src/security/tutorial005_an.py index 5b67cb145..2e8bb3bdb 100644 --- a/docs_src/security/tutorial005_an.py +++ b/docs_src/security/tutorial005_an.py @@ -117,7 +117,7 @@ async def get_current_user( ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_scopes = payload.get("scopes", []) diff --git a/docs_src/security/tutorial005_an_py310.py b/docs_src/security/tutorial005_an_py310.py index 297193e35..90781587f 100644 --- a/docs_src/security/tutorial005_an_py310.py +++ b/docs_src/security/tutorial005_an_py310.py @@ -116,7 +116,7 @@ async def get_current_user( ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_scopes = payload.get("scopes", []) diff --git a/docs_src/security/tutorial005_an_py39.py b/docs_src/security/tutorial005_an_py39.py index 1acf47bdc..a5192d8d6 100644 --- a/docs_src/security/tutorial005_an_py39.py +++ b/docs_src/security/tutorial005_an_py39.py @@ -1,5 +1,5 @@ from datetime import datetime, timedelta, timezone -from typing import Annotated, List, Union +from typing import Annotated, Union import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status @@ -44,7 +44,7 @@ class Token(BaseModel): class TokenData(BaseModel): username: Union[str, None] = None - scopes: List[str] = [] + scopes: list[str] = [] class User(BaseModel): @@ -116,7 +116,7 @@ async def get_current_user( ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_scopes = payload.get("scopes", []) From 2b3b4161220da0ed854f0d556aa497a8e3e574db Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 15 Feb 2025 16:28:29 +0000 Subject: [PATCH 818/932] =?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 [skip ci] --- 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 6a3ec5b73..7d8ca5ba0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Docs +* 🔥 Remove manual type annotations in JWT tutorial to avoid typing expectations (JWT doesn't provide more types). PR [#13378](https://github.com/fastapi/fastapi/pull/13378) by [@tiangolo](https://github.com/tiangolo). * 📝 Update docs for Query Params and String Validations, remove obsolete Ellipsis docs (`...`). PR [#13377](https://github.com/fastapi/fastapi/pull/13377) by [@tiangolo](https://github.com/tiangolo). * ✏️ Remove duplicate title in docs `body-multiple-params`. PR [#13345](https://github.com/fastapi/fastapi/pull/13345) by [@DanielYang59](https://github.com/DanielYang59). * 📝 Fix test badge. PR [#13313](https://github.com/fastapi/fastapi/pull/13313) by [@esadek](https://github.com/esadek). From 5451d05bc84fc8888dfc9cd8a9f3b2c3987c751e Mon Sep 17 00:00:00 2001 From: alv2017 Date: Sat, 15 Feb 2025 18:31:57 +0200 Subject: [PATCH 819/932] =?UTF-8?q?=E2=9C=85=20Simplify=20tests=20for=20`q?= =?UTF-8?q?uery=5Fparams=5Fstr=5Fvalidations`=20(#13218)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- .../test_tutorial010.py | 23 ++- .../test_tutorial010_an.py | 168 ----------------- .../test_tutorial010_an_py310.py | 175 ------------------ .../test_tutorial010_an_py39.py | 175 ------------------ .../test_tutorial010_py310.py | 175 ------------------ .../test_tutorial011.py | 31 +++- .../test_tutorial011_an.py | 108 ----------- .../test_tutorial011_an_py310.py | 118 ------------ .../test_tutorial011_an_py39.py | 118 ------------ .../test_tutorial011_py310.py | 118 ------------ .../test_tutorial011_py39.py | 118 ------------ .../test_tutorial012.py | 29 ++- .../test_tutorial012_an.py | 96 ---------- .../test_tutorial012_an_py39.py | 106 ----------- .../test_tutorial012_py39.py | 106 ----------- .../test_tutorial013.py | 28 ++- .../test_tutorial013_an.py | 96 ---------- .../test_tutorial013_an_py39.py | 106 ----------- .../test_tutorial014.py | 30 ++- .../test_tutorial014_an.py | 81 -------- .../test_tutorial014_an_py310.py | 91 --------- .../test_tutorial014_an_py39.py | 91 --------- .../test_tutorial014_py310.py | 91 --------- 23 files changed, 117 insertions(+), 2161 deletions(-) delete mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py delete mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py delete mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py delete mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py delete mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an.py delete mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py310.py delete mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py39.py delete mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py310.py delete mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py39.py delete mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an.py delete mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an_py39.py delete mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial012_py39.py delete mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an.py delete mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an_py39.py delete mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an.py delete mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py310.py delete mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py39.py delete mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial014_py310.py diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py index 4f52d6ff7..e08e16963 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py @@ -1,14 +1,29 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi._compat import PYDANTIC_VERSION_MINOR_TUPLE from fastapi.testclient import TestClient +from ...utils import needs_py39, needs_py310 + -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial010 import app +@pytest.fixture( + name="client", + params=[ + "tutorial010", + pytest.param("tutorial010_py310", marks=needs_py310), + "tutorial010_an", + pytest.param("tutorial010_an_py39", marks=needs_py39), + pytest.param("tutorial010_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.query_params_str_validations.{request.param}" + ) - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py deleted file mode 100644 index 5daca1e70..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py +++ /dev/null @@ -1,168 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi._compat import PYDANTIC_VERSION_MINOR_TUPLE -from fastapi.testclient import TestClient - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial010_an import app - - client = TestClient(app) - return client - - -def test_query_params_str_validations_no_query(client: TestClient): - response = client.get("/items/") - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -def test_query_params_str_validations_item_query_fixedquery(client: TestClient): - response = client.get("/items/", params={"item-query": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == { - "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], - "q": "fixedquery", - } - - -def test_query_params_str_validations_q_fixedquery(client: TestClient): - response = client.get("/items/", params={"q": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -def test_query_params_str_validations_item_query_nonregexquery(client: TestClient): - response = client.get("/items/", params={"item-query": "nonregexquery"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "string_pattern_mismatch", - "loc": ["query", "item-query"], - "msg": "String should match pattern '^fixedquery$'", - "input": "nonregexquery", - "ctx": {"pattern": "^fixedquery$"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"pattern": "^fixedquery$"}, - "loc": ["query", "item-query"], - "msg": 'string does not match regex "^fixedquery$"', - "type": "value_error.str.regex", - } - ] - } - ) - - -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "description": "Query string for the items to search in the database that have a good match", - "required": False, - "deprecated": True, - "schema": IsDict( - { - "anyOf": [ - { - "type": "string", - "minLength": 3, - "maxLength": 50, - "pattern": "^fixedquery$", - }, - {"type": "null"}, - ], - "title": "Query string", - "description": "Query string for the items to search in the database that have a good match", - # See https://github.com/pydantic/pydantic/blob/80353c29a824c55dea4667b328ba8f329879ac9f/tests/test_fastapi.sh#L25-L34. - **( - {"deprecated": True} - if PYDANTIC_VERSION_MINOR_TUPLE >= (2, 10) - else {} - ), - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Query string", - "maxLength": 50, - "minLength": 3, - "pattern": "^fixedquery$", - "type": "string", - "description": "Query string for the items to search in the database that have a good match", - } - ), - "name": "item-query", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py deleted file mode 100644 index 89da4d82e..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py +++ /dev/null @@ -1,175 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi._compat import PYDANTIC_VERSION_MINOR_TUPLE -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial010_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_query_params_str_validations_no_query(client: TestClient): - response = client.get("/items/") - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -@needs_py310 -def test_query_params_str_validations_item_query_fixedquery(client: TestClient): - response = client.get("/items/", params={"item-query": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == { - "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], - "q": "fixedquery", - } - - -@needs_py310 -def test_query_params_str_validations_q_fixedquery(client: TestClient): - response = client.get("/items/", params={"q": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -@needs_py310 -def test_query_params_str_validations_item_query_nonregexquery(client: TestClient): - response = client.get("/items/", params={"item-query": "nonregexquery"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "string_pattern_mismatch", - "loc": ["query", "item-query"], - "msg": "String should match pattern '^fixedquery$'", - "input": "nonregexquery", - "ctx": {"pattern": "^fixedquery$"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"pattern": "^fixedquery$"}, - "loc": ["query", "item-query"], - "msg": 'string does not match regex "^fixedquery$"', - "type": "value_error.str.regex", - } - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "description": "Query string for the items to search in the database that have a good match", - "required": False, - "deprecated": True, - "schema": IsDict( - { - "anyOf": [ - { - "type": "string", - "minLength": 3, - "maxLength": 50, - "pattern": "^fixedquery$", - }, - {"type": "null"}, - ], - "title": "Query string", - "description": "Query string for the items to search in the database that have a good match", - # See https://github.com/pydantic/pydantic/blob/80353c29a824c55dea4667b328ba8f329879ac9f/tests/test_fastapi.sh#L25-L34. - **( - {"deprecated": True} - if PYDANTIC_VERSION_MINOR_TUPLE >= (2, 10) - else {} - ), - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Query string", - "maxLength": 50, - "minLength": 3, - "pattern": "^fixedquery$", - "type": "string", - "description": "Query string for the items to search in the database that have a good match", - } - ), - "name": "item-query", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py deleted file mode 100644 index f5f692b06..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py +++ /dev/null @@ -1,175 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi._compat import PYDANTIC_VERSION_MINOR_TUPLE -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial010_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_query_params_str_validations_no_query(client: TestClient): - response = client.get("/items/") - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -@needs_py39 -def test_query_params_str_validations_item_query_fixedquery(client: TestClient): - response = client.get("/items/", params={"item-query": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == { - "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], - "q": "fixedquery", - } - - -@needs_py39 -def test_query_params_str_validations_q_fixedquery(client: TestClient): - response = client.get("/items/", params={"q": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -@needs_py39 -def test_query_params_str_validations_item_query_nonregexquery(client: TestClient): - response = client.get("/items/", params={"item-query": "nonregexquery"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "string_pattern_mismatch", - "loc": ["query", "item-query"], - "msg": "String should match pattern '^fixedquery$'", - "input": "nonregexquery", - "ctx": {"pattern": "^fixedquery$"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"pattern": "^fixedquery$"}, - "loc": ["query", "item-query"], - "msg": 'string does not match regex "^fixedquery$"', - "type": "value_error.str.regex", - } - ] - } - ) - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "description": "Query string for the items to search in the database that have a good match", - "required": False, - "deprecated": True, - "schema": IsDict( - { - "anyOf": [ - { - "type": "string", - "minLength": 3, - "maxLength": 50, - "pattern": "^fixedquery$", - }, - {"type": "null"}, - ], - "title": "Query string", - "description": "Query string for the items to search in the database that have a good match", - # See https://github.com/pydantic/pydantic/blob/80353c29a824c55dea4667b328ba8f329879ac9f/tests/test_fastapi.sh#L25-L34. - **( - {"deprecated": True} - if PYDANTIC_VERSION_MINOR_TUPLE >= (2, 10) - else {} - ), - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Query string", - "maxLength": 50, - "minLength": 3, - "pattern": "^fixedquery$", - "type": "string", - "description": "Query string for the items to search in the database that have a good match", - } - ), - "name": "item-query", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py deleted file mode 100644 index 5b62c969f..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py +++ /dev/null @@ -1,175 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi._compat import PYDANTIC_VERSION_MINOR_TUPLE -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial010_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_query_params_str_validations_no_query(client: TestClient): - response = client.get("/items/") - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -@needs_py310 -def test_query_params_str_validations_item_query_fixedquery(client: TestClient): - response = client.get("/items/", params={"item-query": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == { - "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], - "q": "fixedquery", - } - - -@needs_py310 -def test_query_params_str_validations_q_fixedquery(client: TestClient): - response = client.get("/items/", params={"q": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -@needs_py310 -def test_query_params_str_validations_item_query_nonregexquery(client: TestClient): - response = client.get("/items/", params={"item-query": "nonregexquery"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "string_pattern_mismatch", - "loc": ["query", "item-query"], - "msg": "String should match pattern '^fixedquery$'", - "input": "nonregexquery", - "ctx": {"pattern": "^fixedquery$"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"pattern": "^fixedquery$"}, - "loc": ["query", "item-query"], - "msg": 'string does not match regex "^fixedquery$"', - "type": "value_error.str.regex", - } - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "description": "Query string for the items to search in the database that have a good match", - "required": False, - "deprecated": True, - "schema": IsDict( - { - "anyOf": [ - { - "type": "string", - "minLength": 3, - "maxLength": 50, - "pattern": "^fixedquery$", - }, - {"type": "null"}, - ], - "title": "Query string", - "description": "Query string for the items to search in the database that have a good match", - # See https://github.com/pydantic/pydantic/blob/80353c29a824c55dea4667b328ba8f329879ac9f/tests/test_fastapi.sh#L25-L34. - **( - {"deprecated": True} - if PYDANTIC_VERSION_MINOR_TUPLE >= (2, 10) - else {} - ), - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Query string", - "maxLength": 50, - "minLength": 3, - "pattern": "^fixedquery$", - "type": "string", - "description": "Query string for the items to search in the database that have a good match", - } - ), - "name": "item-query", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py index 5ba39b05d..f4da25752 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py @@ -1,26 +1,47 @@ +import importlib + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.query_params_str_validations.tutorial011 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial011", + pytest.param("tutorial011_py39", marks=needs_py310), + pytest.param("tutorial011_py310", marks=needs_py310), + "tutorial011_an", + pytest.param("tutorial011_an_py39", marks=needs_py39), + pytest.param("tutorial011_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.query_params_str_validations.{request.param}" + ) -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_multi_query_values(): +def test_multi_query_values(client: TestClient): url = "/items/?q=foo&q=bar" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": ["foo", "bar"]} -def test_query_no_values(): +def test_query_no_values(client: TestClient): url = "/items/" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": None} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an.py deleted file mode 100644 index 3942ea77a..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an.py +++ /dev/null @@ -1,108 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.query_params_str_validations.tutorial011_an import app - -client = TestClient(app) - - -def test_multi_query_values(): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -def test_query_no_values(): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": None} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py310.py deleted file mode 100644 index f2ec38c95..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py310.py +++ /dev/null @@ -1,118 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial011_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_multi_query_values(client: TestClient): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py310 -def test_query_no_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": None} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py39.py deleted file mode 100644 index cd7b15679..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py39.py +++ /dev/null @@ -1,118 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial011_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_multi_query_values(client: TestClient): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py39 -def test_query_no_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": None} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py310.py deleted file mode 100644 index bdc729516..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py310.py +++ /dev/null @@ -1,118 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial011_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_multi_query_values(client: TestClient): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py310 -def test_query_no_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": None} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py39.py deleted file mode 100644 index 26ac56b2f..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py39.py +++ /dev/null @@ -1,118 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial011_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_multi_query_values(client: TestClient): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py39 -def test_query_no_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": None} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py index 1436db384..549a90519 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py @@ -1,25 +1,44 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.query_params_str_validations.tutorial012 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial012", + pytest.param("tutorial012_py39", marks=needs_py39), + "tutorial012_an", + pytest.param("tutorial012_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.query_params_str_validations.{request.param}" + ) -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_default_query_values(): +def test_default_query_values(client: TestClient): url = "/items/" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": ["foo", "bar"]} -def test_multi_query_values(): +def test_multi_query_values(client: TestClient): url = "/items/?q=baz&q=foobar" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": ["baz", "foobar"]} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an.py deleted file mode 100644 index 270763f1d..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an.py +++ /dev/null @@ -1,96 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.query_params_str_validations.tutorial012_an import app - -client = TestClient(app) - - -def test_default_query_values(): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -def test_multi_query_values(): - url = "/items/?q=baz&q=foobar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["baz", "foobar"]} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - "default": ["foo", "bar"], - }, - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an_py39.py deleted file mode 100644 index 548391683..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an_py39.py +++ /dev/null @@ -1,106 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial012_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_default_query_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py39 -def test_multi_query_values(client: TestClient): - url = "/items/?q=baz&q=foobar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["baz", "foobar"]} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - "default": ["foo", "bar"], - }, - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_py39.py deleted file mode 100644 index e7d745154..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_py39.py +++ /dev/null @@ -1,106 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial012_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_default_query_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py39 -def test_multi_query_values(client: TestClient): - url = "/items/?q=baz&q=foobar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["baz", "foobar"]} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - "default": ["foo", "bar"], - }, - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py index 1ba1fdf61..f2f5f7a85 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py @@ -1,25 +1,43 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.query_params_str_validations.tutorial013 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial013", + "tutorial013_an", + pytest.param("tutorial013_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.query_params_str_validations.{request.param}" + ) -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_multi_query_values(): +def test_multi_query_values(client: TestClient): url = "/items/?q=foo&q=bar" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": ["foo", "bar"]} -def test_query_no_values(): +def test_query_no_values(client: TestClient): url = "/items/" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": []} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an.py deleted file mode 100644 index 343261748..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an.py +++ /dev/null @@ -1,96 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.query_params_str_validations.tutorial013_an import app - -client = TestClient(app) - - -def test_multi_query_values(): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -def test_query_no_values(): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": []} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {}, - "default": [], - }, - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an_py39.py deleted file mode 100644 index 537d6325b..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an_py39.py +++ /dev/null @@ -1,106 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial013_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_multi_query_values(client: TestClient): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py39 -def test_query_no_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": []} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {}, - "default": [], - }, - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py index 7bce7590c..edd40bb1a 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py @@ -1,23 +1,43 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.query_params_str_validations.tutorial014 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial014", + pytest.param("tutorial014_py310", marks=needs_py310), + "tutorial014_an", + pytest.param("tutorial014_an_py39", marks=needs_py39), + pytest.param("tutorial014_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.query_params_str_validations.{request.param}" + ) -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_hidden_query(): +def test_hidden_query(client: TestClient): response = client.get("/items?hidden_query=somevalue") assert response.status_code == 200, response.text assert response.json() == {"hidden_query": "somevalue"} -def test_no_hidden_query(): +def test_no_hidden_query(client: TestClient): response = client.get("/items") assert response.status_code == 200, response.text assert response.json() == {"hidden_query": "Not found"} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an.py deleted file mode 100644 index 2182e87b7..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an.py +++ /dev/null @@ -1,81 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.query_params_str_validations.tutorial014_an import app - -client = TestClient(app) - - -def test_hidden_query(): - response = client.get("/items?hidden_query=somevalue") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "somevalue"} - - -def test_no_hidden_query(): - response = client.get("/items") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "Not found"} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py310.py deleted file mode 100644 index 344004d01..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py310.py +++ /dev/null @@ -1,91 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial014_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_hidden_query(client: TestClient): - response = client.get("/items?hidden_query=somevalue") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "somevalue"} - - -@needs_py310 -def test_no_hidden_query(client: TestClient): - response = client.get("/items") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "Not found"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py39.py deleted file mode 100644 index 5d4f6df3d..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py39.py +++ /dev/null @@ -1,91 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial014_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_hidden_query(client: TestClient): - response = client.get("/items?hidden_query=somevalue") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "somevalue"} - - -@needs_py310 -def test_no_hidden_query(client: TestClient): - response = client.get("/items") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "Not found"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_py310.py deleted file mode 100644 index dad49fb12..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_py310.py +++ /dev/null @@ -1,91 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial014_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_hidden_query(client: TestClient): - response = client.get("/items?hidden_query=somevalue") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "somevalue"} - - -@needs_py310 -def test_no_hidden_query(client: TestClient): - response = client.get("/items") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "Not found"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } From e24a5002929245ceb0b5fa8e72f684ad6421b3a8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 15 Feb 2025 16:32:36 +0000 Subject: [PATCH 820/932] =?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 [skip ci] --- 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 7d8ca5ba0..01665ac54 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ✅ Simplify tests for `query_params_str_validations`. PR [#13218](https://github.com/fastapi/fastapi/pull/13218) by [@alv2017](https://github.com/alv2017). * ✅ Simplify tests for `app_testing`. PR [#13220](https://github.com/fastapi/fastapi/pull/13220) by [@alv2017](https://github.com/alv2017). * ✅ Simplify tests for `dependency_testing`. PR [#13223](https://github.com/fastapi/fastapi/pull/13223) by [@alv2017](https://github.com/alv2017). From e24299b2ffb027967c4cedb25dade42121edc17f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Haoyu=20=28Daniel=29=20YANG=20=E6=9D=A8=E6=B5=A9=E5=AE=87?= Date: Sat, 15 Feb 2025 17:33:33 +0100 Subject: [PATCH 821/932] =?UTF-8?q?=F0=9F=93=9D=20Add=20more=20precise=20d?= =?UTF-8?q?escription=20of=20HTTP=20status=20code=20range=20in=20docs=20(#?= =?UTF-8?q?13347)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/response-status-code.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/en/docs/tutorial/response-status-code.md b/docs/en/docs/tutorial/response-status-code.md index 711042a46..41bf02a8f 100644 --- a/docs/en/docs/tutorial/response-status-code.md +++ b/docs/en/docs/tutorial/response-status-code.md @@ -53,16 +53,16 @@ These status codes have a name associated to recognize them, but the important p In short: -* `100` and above are for "Information". You rarely use them directly. Responses with these status codes cannot have a body. -* **`200`** and above are for "Successful" responses. These are the ones you would use the most. +* `100 - 199` are for "Information". You rarely use them directly. Responses with these status codes cannot have a body. +* **`200 - 299`** are for "Successful" responses. These are the ones you would use the most. * `200` is the default status code, which means everything was "OK". * Another example would be `201`, "Created". It is commonly used after creating a new record in the database. * A special case is `204`, "No Content". This response is used when there is no content to return to the client, and so the response must not have a body. -* **`300`** and above are for "Redirection". Responses with these status codes may or may not have a body, except for `304`, "Not Modified", which must not have one. -* **`400`** and above are for "Client error" responses. These are the second type you would probably use the most. +* **`300 - 399`** are for "Redirection". Responses with these status codes may or may not have a body, except for `304`, "Not Modified", which must not have one. +* **`400 - 499`** are for "Client error" responses. These are the second type you would probably use the most. * An example is `404`, for a "Not Found" response. * For generic errors from the client, you can just use `400`. -* `500` and above are for server errors. You almost never use them directly. When something goes wrong at some part in your application code, or server, it will automatically return one of these status codes. +* `500 - 599` are for server errors. You almost never use them directly. When something goes wrong at some part in your application code, or server, it will automatically return one of these status codes. /// tip From 7e67a91b08c0076ea09c69f9c52fac630c5cad7b Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 15 Feb 2025 16:33:58 +0000 Subject: [PATCH 822/932] =?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 [skip ci] --- 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 01665ac54..fa1ff20f5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Docs +* 📝 Add more precise description of HTTP status code range in docs. PR [#13347](https://github.com/fastapi/fastapi/pull/13347) by [@DanielYang59](https://github.com/DanielYang59). * 🔥 Remove manual type annotations in JWT tutorial to avoid typing expectations (JWT doesn't provide more types). PR [#13378](https://github.com/fastapi/fastapi/pull/13378) by [@tiangolo](https://github.com/tiangolo). * 📝 Update docs for Query Params and String Validations, remove obsolete Ellipsis docs (`...`). PR [#13377](https://github.com/fastapi/fastapi/pull/13377) by [@tiangolo](https://github.com/tiangolo). * ✏️ Remove duplicate title in docs `body-multiple-params`. PR [#13345](https://github.com/fastapi/fastapi/pull/13345) by [@DanielYang59](https://github.com/DanielYang59). From c868581ce7a108bfbef7c3fb4b42fa663dfdea97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 18 Feb 2025 16:18:14 +0100 Subject: [PATCH 823/932] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors:=20Add?= =?UTF-8?q?=20LambdaTest=20(#13389)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/sponsors.yml | 3 +++ docs/en/docs/img/sponsors/lambdatest.png | Bin 0 -> 6320 bytes 2 files changed, 3 insertions(+) create mode 100644 docs/en/docs/img/sponsors/lambdatest.png diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index f9bf33ae9..91b23937c 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -58,3 +58,6 @@ bronze: - url: https://testdriven.io/courses/tdd-fastapi/ title: Learn to build high-quality web apps with best practices img: https://fastapi.tiangolo.com/img/sponsors/testdriven.svg + - url: https://lambdatest.com/?utm_source=fastapi&utm_medium=partner&utm_campaign=sponsor&utm_term=opensource&utm_content=webpage + title: LambdaTest, AI-Powered Cloud-based Test Orchestration Platform + img: https://fastapi.tiangolo.com/img/sponsors/lambdatest.png diff --git a/docs/en/docs/img/sponsors/lambdatest.png b/docs/en/docs/img/sponsors/lambdatest.png new file mode 100644 index 0000000000000000000000000000000000000000..674cbcb893dfec5a29dc72452215734603dcede6 GIT binary patch literal 6320 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 aNn)J05mscJEx>;p5Rc`b$`#9)2K^5%?KE=$ literal 0 HcmV?d00001 From 235300c1d2a7d8a011685adc1c9aa2c195c0368f Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 18 Feb 2025 15:18:42 +0000 Subject: [PATCH 824/932] =?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 [skip ci] --- 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 fa1ff20f5..c61e9d7e5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -41,6 +41,7 @@ hide: ### Internal +* 🔧 Update sponsors: Add LambdaTest. PR [#13389](https://github.com/fastapi/fastapi/pull/13389) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump cloudflare/wrangler-action from 3.13 to 3.14. PR [#13350](https://github.com/fastapi/fastapi/pull/13350) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump mkdocs-material from 9.5.18 to 9.6.1. PR [#13301](https://github.com/fastapi/fastapi/pull/13301) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pillow from 11.0.0 to 11.1.0. PR [#13300](https://github.com/fastapi/fastapi/pull/13300) by [@dependabot[bot]](https://github.com/apps/dependabot). From e157cf4b9625b2ccdd6a3214ba552bcde9452912 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hyogeun=20Oh=20=28=EC=98=A4=ED=9A=A8=EA=B7=BC=29?= Date: Wed, 19 Feb 2025 01:52:15 +0900 Subject: [PATCH 825/932] =?UTF-8?q?=F0=9F=90=9B=20Fix=20issue=20with=20Swa?= =?UTF-8?q?gger=20theme=20change=20example=20in=20the=20official=20tutoria?= =?UTF-8?q?l=20(#13289)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs_src/configure_swagger_ui/tutorial002.py | 2 +- .../test_tutorial/test_configure_swagger_ui/test_tutorial002.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs_src/configure_swagger_ui/tutorial002.py b/docs_src/configure_swagger_ui/tutorial002.py index cc569ce45..cc75c2196 100644 --- a/docs_src/configure_swagger_ui/tutorial002.py +++ b/docs_src/configure_swagger_ui/tutorial002.py @@ -1,6 +1,6 @@ from fastapi import FastAPI -app = FastAPI(swagger_ui_parameters={"syntaxHighlight.theme": "obsidian"}) +app = FastAPI(swagger_ui_parameters={"syntaxHighlight": {"theme": "obsidian"}}) @app.get("/users/{username}") diff --git a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py index 166901188..d06a385b5 100644 --- a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py +++ b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py @@ -12,7 +12,7 @@ def test_swagger_ui(): '"syntaxHighlight": false' not in response.text ), "not used parameters should not be included" assert ( - '"syntaxHighlight.theme": "obsidian"' in response.text + '"syntaxHighlight": {"theme": "obsidian"}' in response.text ), "parameters with middle dots should be included in a JSON compatible way" assert ( '"dom_id": "#swagger-ui"' in response.text From 286fd694eaf006481c9fdc59a8324e4405fd0683 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 18 Feb 2025 16:52:41 +0000 Subject: [PATCH 826/932] =?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 [skip ci] --- 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 c61e9d7e5..5f3d98e5c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Docs +* 🐛 Fix issue with Swagger theme change example in the official tutorial. PR [#13289](https://github.com/fastapi/fastapi/pull/13289) by [@Zerohertz](https://github.com/Zerohertz). * 📝 Add more precise description of HTTP status code range in docs. PR [#13347](https://github.com/fastapi/fastapi/pull/13347) by [@DanielYang59](https://github.com/DanielYang59). * 🔥 Remove manual type annotations in JWT tutorial to avoid typing expectations (JWT doesn't provide more types). PR [#13378](https://github.com/fastapi/fastapi/pull/13378) by [@tiangolo](https://github.com/tiangolo). * 📝 Update docs for Query Params and String Validations, remove obsolete Ellipsis docs (`...`). PR [#13377](https://github.com/fastapi/fastapi/pull/13377) by [@tiangolo](https://github.com/tiangolo). From 70137c0f7d9534b30ef4ec39f3cea471ade9e567 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 18 Feb 2025 19:44:00 +0100 Subject: [PATCH 827/932] =?UTF-8?q?=F0=9F=94=A7=20Update=20team:=20Add=20L?= =?UTF-8?q?udovico=20(#13390)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/members.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/en/data/members.yml b/docs/en/data/members.yml index cf016eae1..7ec16e917 100644 --- a/docs/en/data/members.yml +++ b/docs/en/data/members.yml @@ -17,3 +17,6 @@ members: - login: patrick91 avatar_url: https://avatars.githubusercontent.com/u/667029 url: https://github.com/patrick91 +- login: luzzodev + avatar_url: https://avatars.githubusercontent.com/u/27291415 + url: https://github.com/luzzodev From 8c9c536c0a277125ca95c0d9ef19e2c6a39d1db8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 18 Feb 2025 18:44:23 +0000 Subject: [PATCH 828/932] =?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 [skip ci] --- 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 5f3d98e5c..58e6ca6be 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -42,6 +42,7 @@ hide: ### Internal +* 🔧 Update team: Add Ludovico. PR [#13390](https://github.com/fastapi/fastapi/pull/13390) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors: Add LambdaTest. PR [#13389](https://github.com/fastapi/fastapi/pull/13389) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump cloudflare/wrangler-action from 3.13 to 3.14. PR [#13350](https://github.com/fastapi/fastapi/pull/13350) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump mkdocs-material from 9.5.18 to 9.6.1. PR [#13301](https://github.com/fastapi/fastapi/pull/13301) by [@dependabot[bot]](https://github.com/apps/dependabot). From 001473ab66dfae4f56365c61d50432dad5bbb2fe Mon Sep 17 00:00:00 2001 From: Aman Kumar <62641343+bullet-ant@users.noreply.github.com> Date: Thu, 20 Feb 2025 19:39:14 +0530 Subject: [PATCH 829/932] =?UTF-8?q?=F0=9F=93=9D=20Fix=20typos=20in=20virtu?= =?UTF-8?q?al=20environments=20documentation=20(#13396)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/virtual-environments.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/docs/virtual-environments.md b/docs/en/docs/virtual-environments.md index b75be18c3..4f65b3b80 100644 --- a/docs/en/docs/virtual-environments.md +++ b/docs/en/docs/virtual-environments.md @@ -668,7 +668,7 @@ After activating the virtual environment, the `PATH` variable would look somethi /home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin ``` -That means that the system will now start looking first look for programs in: +That means that the system will now start looking first for programs in: ```plaintext /home/user/code/awesome-project/.venv/bin @@ -692,7 +692,7 @@ and use that one. C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 ``` -That means that the system will now start looking first look for programs in: +That means that the system will now start looking first for programs in: ```plaintext C:\Users\user\code\awesome-project\.venv\Scripts From 3aee64b94f008c141cc8205ef3ccebf3978588dd Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 20 Feb 2025 14:09:37 +0000 Subject: [PATCH 830/932] =?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 [skip ci] --- 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 58e6ca6be..c196a5197 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Docs +* 📝 Fix typos in virtual environments documentation. PR [#13396](https://github.com/fastapi/fastapi/pull/13396) by [@bullet-ant](https://github.com/bullet-ant). * 🐛 Fix issue with Swagger theme change example in the official tutorial. PR [#13289](https://github.com/fastapi/fastapi/pull/13289) by [@Zerohertz](https://github.com/Zerohertz). * 📝 Add more precise description of HTTP status code range in docs. PR [#13347](https://github.com/fastapi/fastapi/pull/13347) by [@DanielYang59](https://github.com/DanielYang59). * 🔥 Remove manual type annotations in JWT tutorial to avoid typing expectations (JWT doesn't provide more types). PR [#13378](https://github.com/fastapi/fastapi/pull/13378) by [@tiangolo](https://github.com/tiangolo). From 6ebe7539080531008a9752e8e050b099eef23885 Mon Sep 17 00:00:00 2001 From: Valentyn Date: Thu, 20 Feb 2025 09:13:44 -0500 Subject: [PATCH 831/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/tutorial/request-forms-and-files.md?= =?UTF-8?q?`=20(#13386)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../docs/tutorial/request-forms-and-files.md | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 docs/uk/docs/tutorial/request-forms-and-files.md diff --git a/docs/uk/docs/tutorial/request-forms-and-files.md b/docs/uk/docs/tutorial/request-forms-and-files.md new file mode 100644 index 000000000..a089ef945 --- /dev/null +++ b/docs/uk/docs/tutorial/request-forms-and-files.md @@ -0,0 +1,41 @@ +# Запити з формами та файлами + +У FastAPI Ви можете одночасно отримувати файли та поля форми, використовуючи `File` і `Form`. + +/// info | Інформація + +Щоб отримувати завантажені файли та/або дані форми, спочатку встановіть python-multipart. + +Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили бібліотеку, наприклад: + +```console +$ pip install python-multipart +``` + +/// + +## Імпорт `File` та `Form` + +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *} + +## Оголошення параметрів `File` та `Form` + +Створіть параметри файлів та форми так само як і для `Body` або `Query`: + +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *} + +Файли та поля форми будуть завантажені як формові дані, і Ви отримаєте як файли, так і введені користувачем поля. + +Ви також можете оголосити деякі файли як `bytes`, а деякі як `UploadFile`. + +/// warning | Увага + +Ви можете оголосити кілька параметрів `File` і `Form` в операції *шляху*, але не можете одночасно оголошувати `Body`-поля, які очікуєте отримати у форматі JSON, оскільки запит матиме тіло, закодоване за допомогою `multipart/form-data`, а не `application/json`. + +Це не обмеження **FastAPI**, а частина протоколу HTTP. + +/// + +## Підсумок + +Використовуйте `File` та `Form` разом, коли вам потрібно отримувати дані форми та файли в одному запиті. From 498ba94bfc11f7bb91844162b34fa4ccb4d9f07b Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 20 Feb 2025 14:14:07 +0000 Subject: [PATCH 832/932] =?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 [skip ci] --- 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 c196a5197..baf0b015f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -25,6 +25,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-forms-and-files.md`. PR [#13386](https://github.com/fastapi/fastapi/pull/13386) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Update Korean translation for `docs/ko/docs/help-fastapi.md`. PR [#13262](https://github.com/fastapi/fastapi/pull/13262) by [@Zerohertz](https://github.com/Zerohertz). * 🌐 Add Korean translation for `docs/ko/docs/advanced/custom-response.md`. PR [#13265](https://github.com/fastapi/fastapi/pull/13265) by [@11kkw](https://github.com/11kkw). * 🌐 Update Korean translation for `docs/ko/docs/tutorial/security/simple-oauth2.md`. PR [#13335](https://github.com/fastapi/fastapi/pull/13335) by [@yes0ng](https://github.com/yes0ng). From b397ad9e52a8606e4ea1233f6f66bfd221c0e79b Mon Sep 17 00:00:00 2001 From: Valentyn Date: Thu, 20 Feb 2025 09:16:09 -0500 Subject: [PATCH 833/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/tutorial/request-form-models.md`=20?= =?UTF-8?q?(#13384)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/uk/docs/tutorial/request-form-models.md | 78 ++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 docs/uk/docs/tutorial/request-form-models.md diff --git a/docs/uk/docs/tutorial/request-form-models.md b/docs/uk/docs/tutorial/request-form-models.md new file mode 100644 index 000000000..7f5759e79 --- /dev/null +++ b/docs/uk/docs/tutorial/request-form-models.md @@ -0,0 +1,78 @@ +# Моделі форм (Form Models) + +У FastAPI Ви можете використовувати **Pydantic-моделі** для оголошення **полів форми**. + +/// info | Інформація + +Щоб використовувати форми, спочатку встановіть python-multipart. + +Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили бібліотеку, наприклад: + +```console +$ pip install python-multipart +``` + +/// + +/// note | Підказка + +Ця функція підтримується, починаючи з FastAPI версії `0.113.0`. 🤓 + +/// + +## Використання Pydantic-моделей для форм + +Вам просто потрібно оголосити **Pydantic-модель** з полями, які Ви хочете отримати як **поля форми**, а потім оголосити параметр як `Form`: + +{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *} + +**FastAPI** **витягне** дані для **кожного поля** з **формових даних** у запиті та надасть вам Pydantic-модель, яку Ви визначили. + +## Перевірка документації + +Ви можете перевірити це в UI документації за `/docs`: + +

    + +
    + +## Заборона додаткових полів форми + +У деяких особливих випадках (ймовірно, рідко) Ви можете **обмежити** форму лише тими полями, які були оголошені в Pydantic-моделі, і **заборонити** будь-які **додаткові** поля. + +/// note | Підказка + +Ця функція підтримується, починаючи з FastAPI версії `0.114.0`. 🤓 + +/// + +Ви можете використати конфігурацію Pydantic-моделі, щоб заборонити `forbid` будь-які додаткові `extra` поля: + +{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *} + +Якщо клієнт спробує надіслати додаткові дані, він отримає **відповідь з помилкою**. + +Наприклад, якщо клієнт спробує надіслати наступні поля форми: + +* `username`: `Rick` +* `password`: `Portal Gun` +* `extra`: `Mr. Poopybutthole` + +Він отримає відповідь із помилкою, яка повідомляє, що поле `extra` не дозволено: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "Mr. Poopybutthole" + } + ] +} +``` + +## Підсумок + +Ви можете використовувати Pydantic-моделі для оголошення полів форми у FastAPI. 😎 From 920110276a551ca20fb6a9a8a190d242b28a5151 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 20 Feb 2025 14:16:32 +0000 Subject: [PATCH 834/932] =?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 [skip ci] --- 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 baf0b015f..59501b554 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -25,6 +25,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-form-models.md`. PR [#13384](https://github.com/fastapi/fastapi/pull/13384) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-forms-and-files.md`. PR [#13386](https://github.com/fastapi/fastapi/pull/13386) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Update Korean translation for `docs/ko/docs/help-fastapi.md`. PR [#13262](https://github.com/fastapi/fastapi/pull/13262) by [@Zerohertz](https://github.com/Zerohertz). * 🌐 Add Korean translation for `docs/ko/docs/advanced/custom-response.md`. PR [#13265](https://github.com/fastapi/fastapi/pull/13265) by [@11kkw](https://github.com/11kkw). From 987d2f9a92bcb8f453a41d7e3230e00cb9a8d8db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 20 Feb 2025 18:49:13 +0100 Subject: [PATCH 835/932] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors:=20add?= =?UTF-8?q?=20CodeRabbit=20(#13402)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + docs/en/data/sponsors.yml | 3 +++ docs/en/docs/img/sponsors/coderabbit-banner.png | Bin 0 -> 9522 bytes docs/en/docs/img/sponsors/coderabbit.png | Bin 0 -> 20695 bytes docs/en/overrides/main.html | 6 ++++++ 5 files changed, 10 insertions(+) create mode 100644 docs/en/docs/img/sponsors/coderabbit-banner.png create mode 100644 docs/en/docs/img/sponsors/coderabbit.png diff --git a/README.md b/README.md index d5d5ced52..9a1260b90 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ The key features are: + diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 91b23937c..b994e533a 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -32,6 +32,9 @@ gold: - url: https://docs.render.com/deploy-fastapi?utm_source=deploydoc&utm_medium=referral&utm_campaign=fastapi title: Deploy & scale any full-stack web app on Render. Focus on building apps, not infra. img: https://fastapi.tiangolo.com/img/sponsors/render.svg + - url: https://www.coderabbit.ai/?utm_source=fastapi&utm_medium=badge&utm_campaign=fastapi + title: Cut Code Review Time & Bugs in Half with CodeRabbit + img: https://fastapi.tiangolo.com/img/sponsors/coderabbit.png silver: - url: https://github.com/deepset-ai/haystack/ title: Build powerful search from composable, open source building blocks diff --git a/docs/en/docs/img/sponsors/coderabbit-banner.png b/docs/en/docs/img/sponsors/coderabbit-banner.png new file mode 100644 index 0000000000000000000000000000000000000000..da3bb348204a39d83203e4580ad213dddce5ac99 GIT binary patch literal 9522 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 YVD9}kX5O^}o_9i$mQ;`^7dQ0(A0pkdO#lD@ literal 0 HcmV?d00001 diff --git a/docs/en/docs/img/sponsors/coderabbit.png b/docs/en/docs/img/sponsors/coderabbit.png new file mode 100644 index 0000000000000000000000000000000000000000..74c25e88466fa1b5251f7136bb86103cf79e874f GIT binary patch literal 20695 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 O0000
    + {% endblock %} From 5c8fa58fd06d6d6bb4ae9fe7ef95894bdc94d4fc Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 20 Feb 2025 17:49:39 +0000 Subject: [PATCH 836/932] =?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 [skip ci] --- 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 59501b554..3b41affa7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -45,6 +45,7 @@ hide: ### Internal +* 🔧 Update sponsors: add CodeRabbit. PR [#13402](https://github.com/fastapi/fastapi/pull/13402) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update team: Add Ludovico. PR [#13390](https://github.com/fastapi/fastapi/pull/13390) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors: Add LambdaTest. PR [#13389](https://github.com/fastapi/fastapi/pull/13389) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump cloudflare/wrangler-action from 3.13 to 3.14. PR [#13350](https://github.com/fastapi/fastapi/pull/13350) by [@dependabot[bot]](https://github.com/apps/dependabot). From f8878f3a98057c6ab6161d2577fab49087ba7015 Mon Sep 17 00:00:00 2001 From: Sofie Van Landeghem Date: Thu, 20 Feb 2025 21:53:18 +0100 Subject: [PATCH 837/932] =?UTF-8?q?=F0=9F=A9=BA=20Unify=20the=20badges=20a?= =?UTF-8?q?cross=20all=20tutorial=20translations=20(#13329)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- docs/az/docs/index.md | 2 +- docs/bn/docs/index.md | 11 +++++++---- docs/de/docs/index.md | 2 +- docs/em/docs/index.md | 2 +- docs/es/docs/index.md | 2 +- docs/fa/docs/index.md | 8 ++++---- docs/fr/docs/index.md | 2 +- docs/he/docs/index.md | 6 +++--- docs/hu/docs/index.md | 2 +- docs/id/docs/index.md | 2 +- docs/it/docs/index.md | 14 +++++++++----- docs/ja/docs/index.md | 13 ++++++++----- docs/ko/docs/index.md | 11 +++++++---- docs/nl/docs/index.md | 2 +- docs/pl/docs/index.md | 11 +++++++---- docs/pt/docs/index.md | 2 +- docs/ru/docs/index.md | 6 +++--- docs/tr/docs/index.md | 2 +- docs/uk/docs/index.md | 2 +- docs/vi/docs/index.md | 2 +- docs/yo/docs/index.md | 2 +- docs/zh-hant/docs/index.md | 2 +- docs/zh/docs/index.md | 8 ++++---- 23 files changed, 66 insertions(+), 50 deletions(-) diff --git a/docs/az/docs/index.md b/docs/az/docs/index.md index ad78d7d06..fbbbce130 100644 --- a/docs/az/docs/index.md +++ b/docs/az/docs/index.md @@ -6,7 +6,7 @@

    - Test + Test Əhatə diff --git a/docs/bn/docs/index.md b/docs/bn/docs/index.md index 678ac9ca9..74ee230a1 100644 --- a/docs/bn/docs/index.md +++ b/docs/bn/docs/index.md @@ -5,15 +5,18 @@ FastAPI উচ্চক্ষমতা সম্পন্ন, সহজে শেখার এবং দ্রুত কোড করে প্রোডাকশনের জন্য ফ্রামওয়ার্ক।

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

    --- diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md index 411c8e969..d239f0815 100644 --- a/docs/de/docs/index.md +++ b/docs/de/docs/index.md @@ -12,7 +12,7 @@

    - Test + Test Coverage diff --git a/docs/em/docs/index.md b/docs/em/docs/index.md index 16b2019d3..57be59b07 100644 --- a/docs/em/docs/index.md +++ b/docs/em/docs/index.md @@ -12,7 +12,7 @@

    - Test + Test Coverage diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md index db8da6933..c1da5d633 100644 --- a/docs/es/docs/index.md +++ b/docs/es/docs/index.md @@ -12,7 +12,7 @@

    - Test + Test Coverage diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md index 6addce763..0aa0bec36 100644 --- a/docs/fa/docs/index.md +++ b/docs/fa/docs/index.md @@ -11,11 +11,11 @@ فریم‌ورک FastAPI، کارایی بالا، یادگیری آسان، کدنویسی سریع، آماده برای استفاده در محیط پروداکشن

    - - Test + + Test - - Coverage + + Coverage Package version diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md index 695429008..d25f7a939 100644 --- a/docs/fr/docs/index.md +++ b/docs/fr/docs/index.md @@ -12,7 +12,7 @@

    - Test + Test Coverage diff --git a/docs/he/docs/index.md b/docs/he/docs/index.md index 6498d15e1..bd166f205 100644 --- a/docs/he/docs/index.md +++ b/docs/he/docs/index.md @@ -12,10 +12,10 @@

    - Test + Test - - Coverage + + Coverage Package version diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md index c6f596650..45ff49c3b 100644 --- a/docs/hu/docs/index.md +++ b/docs/hu/docs/index.md @@ -6,7 +6,7 @@

    - Test + Test Coverage diff --git a/docs/id/docs/index.md b/docs/id/docs/index.md index 7fdd1cc7a..5fb0c4c9c 100644 --- a/docs/id/docs/index.md +++ b/docs/id/docs/index.md @@ -12,7 +12,7 @@

    - Test + Test Coverage diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md index 8a1039bc5..dc8f5b846 100644 --- a/docs/it/docs/index.md +++ b/docs/it/docs/index.md @@ -4,15 +4,19 @@

    FastAPI framework, alte prestazioni, facile da imparare, rapido da implementare, pronto per il rilascio in produzione

    +

    - - Build Status + + Test + + + Coverage - - Coverage + + Package version - Package version + Supported Python versions

    diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index 682c94e83..1ba85f8e0 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -11,14 +11,17 @@ FastAPI framework, high performance, easy to learn, fast to code, ready for production

    - - Build Status + + Test - - Coverage + + Coverage - Package version + Package version + + + Supported Python versions

    diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index 8b00d90bc..0df2000fa 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -11,15 +11,18 @@ FastAPI 프레임워크, 고성능, 간편한 학습, 빠른 코드 작성, 준비된 프로덕션

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

    --- diff --git a/docs/nl/docs/index.md b/docs/nl/docs/index.md index d88bb7771..32b20e31e 100644 --- a/docs/nl/docs/index.md +++ b/docs/nl/docs/index.md @@ -12,7 +12,7 @@

    - Test + Test Coverage diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index 9a96c6553..0e13d2631 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -11,15 +11,18 @@ FastAPI to szybki, prosty w nauce i gotowy do użycia w produkcji framework

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

    --- diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md index 138048f06..9f08d5224 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -12,7 +12,7 @@

    - Test + Test Coverage diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 5ebe1494b..a9546cf1e 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -12,10 +12,10 @@

    - Test + Test - - Coverage + + Coverage Package version diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md index 7ecaf1ba3..f666e2d06 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -12,7 +12,7 @@

    - Test + Test Coverage diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md index 012bac2e2..b573ee259 100644 --- a/docs/uk/docs/index.md +++ b/docs/uk/docs/index.md @@ -6,7 +6,7 @@

    - Test + Test Coverage diff --git a/docs/vi/docs/index.md b/docs/vi/docs/index.md index 5e346ded8..5c6b7e8a4 100644 --- a/docs/vi/docs/index.md +++ b/docs/vi/docs/index.md @@ -12,7 +12,7 @@

    - Test + Test Coverage diff --git a/docs/yo/docs/index.md b/docs/yo/docs/index.md index 3ad1483de..d6aa78b3d 100644 --- a/docs/yo/docs/index.md +++ b/docs/yo/docs/index.md @@ -12,7 +12,7 @@

    - Test + Test Coverage diff --git a/docs/zh-hant/docs/index.md b/docs/zh-hant/docs/index.md index 137a17284..81d99ede4 100644 --- a/docs/zh-hant/docs/index.md +++ b/docs/zh-hant/docs/index.md @@ -6,7 +6,7 @@

    - Test + Test Coverage diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index d3e9e3112..94cf8745c 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -11,11 +11,11 @@ FastAPI 框架,高性能,易于学习,高效编码,生产可用

    - - Test + + Test - - Coverage + + Coverage Package version From 4516a48c7cd068897ee45c715a5d2aacd692b4e8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 21 Feb 2025 11:36:43 +0000 Subject: [PATCH 838/932] =?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 [skip ci] --- 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 3b41affa7..83ffa8deb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,7 @@ hide: ### Docs +* 🩺 Unify the badges across all tutorial translations. PR [#13329](https://github.com/fastapi/fastapi/pull/13329) by [@svlandeg](https://github.com/svlandeg). * 📝 Fix typos in virtual environments documentation. PR [#13396](https://github.com/fastapi/fastapi/pull/13396) by [@bullet-ant](https://github.com/bullet-ant). * 🐛 Fix issue with Swagger theme change example in the official tutorial. PR [#13289](https://github.com/fastapi/fastapi/pull/13289) by [@Zerohertz](https://github.com/Zerohertz). * 📝 Add more precise description of HTTP status code range in docs. PR [#13347](https://github.com/fastapi/fastapi/pull/13347) by [@DanielYang59](https://github.com/DanielYang59). From 31920eff623a49ab177ba29f8f795e69b4cbb7cf Mon Sep 17 00:00:00 2001 From: Valentyn Date: Sat, 22 Feb 2025 17:01:44 -0500 Subject: [PATCH 839/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/tutorial/request-files.md`=20(#1339?= =?UTF-8?q?5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/uk/docs/tutorial/request-files.md | 175 +++++++++++++++++++++++++ 1 file changed, 175 insertions(+) create mode 100644 docs/uk/docs/tutorial/request-files.md diff --git a/docs/uk/docs/tutorial/request-files.md b/docs/uk/docs/tutorial/request-files.md new file mode 100644 index 000000000..18b7cc01c --- /dev/null +++ b/docs/uk/docs/tutorial/request-files.md @@ -0,0 +1,175 @@ +# Запит файлів + +Ви можете визначити файли, які будуть завантажуватися клієнтом, використовуючи `File`. + +/// info | Інформація + +Щоб отримувати завантажені файли, спочатку встановіть python-multipart. + +Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його та встановили пакет, наприклад: + +```console +$ pip install python-multipart +``` + +Це необхідно, оскільки завантажені файли передаються у вигляді "форматованих даних форми". + +/// + +## Імпорт `File` + +Імпортуйте `File` та `UploadFile` з `fastapi`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} + +## Визначення параметрів `File` + +Створіть параметри файлів так само як Ви б створювали `Body` або `Form`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} + +/// info | Інформація + +`File` — це клас, який безпосередньо успадковує `Form`. + +Але пам’ятайте, що коли Ви імпортуєте `Query`, `Path`, `File` та інші з `fastapi`, це насправді функції, які повертають спеціальні класи. + +/// + +/// tip | Підказка + +Щоб оголосити тіла файлів, Вам потрібно використовувати `File`, тому що інакше параметри будуть інтерпретовані як параметри запиту або параметри тіла (JSON). + +/// + +Файли будуть завантажені у вигляді "форматованих даних форми". + +Якщо Ви оголосите тип параметра функції обробника маршруту як `bytes`, **FastAPI** прочитає файл за Вас, і Ви отримаєте його вміст у вигляді `bytes`. + +Однак майте на увазі, що весь вміст буде збережено в пам'яті. Це працюватиме добре для малих файлів. + +Але в деяких випадках Вам може знадобитися `UploadFile`. + +## Параметри файлу з `UploadFile` + +Визначте параметр файлу з типом `UploadFile`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} + +Використання `UploadFile` має кілька переваг перед `bytes`: + +* Вам не потрібно використовувати `File()` у значенні за замовчуванням параметра. +* Використовується "буферизований" файл: + * Файл зберігається в пам'яті до досягнення певного обмеження, після чого він записується на диск. +* Це означає, що він добре працює для великих файлів, таких як зображення, відео, великі двійкові файли тощо, не споживаючи всю пам'ять. +Ви можете отримати метадані про завантажений файл. +* Він має file-like `асинхронний файловий інтерфейс` interface. +* Він надає фактичний об'єкт Python `SpooledTemporaryFile`, який можна передавати безпосередньо іншим бібліотекам. + +### `UploadFile` + +`UploadFile` має такі атрибути: + +* `filename`: Рядок `str` з оригінальною назвою файлу, який був завантажений (наприклад, `myimage.jpg`). +* `content_type`: Рядок `str` з MIME-типом (наприклад, `image/jpeg`). +* `file`: Об'єкт SpooledTemporaryFile (файлоподібний об'єкт). Це фактичний файловий об'єкт Python, який можна безпосередньо передавати іншим функціям або бібліотекам, що очікують "файлоподібний" об'єкт. + +`UploadFile` має такі асинхронні `async` методи. Вони викликають відповідні методи файлу під капотом (використовуючи внутрішній `SpooledTemporaryFile`). + +* `write(data)`: Записує `data` (`str` або `bytes`) у файл. +* `read(size)`: Читає `size` (`int`) байтів/символів з файлу. +* `seek(offset)`: Переміщується до позиції `offset` (`int`) у файлі. + * Наприклад, `await myfile.seek(0)` поверне курсор на початок файлу. + * This is especially useful if you run `await myfile.read()` once and then need to read the contents again. Це особливо корисно, якщо Ви виконуєте await `await myfile.read()` один раз, а потім потрібно знову прочитати вміст. +* `close()`: Закриває файл. + +Оскільки всі ці методи є асинхронними `async`, Вам потрібно використовувати "await": + +Наприклад, всередині `async` *функції обробки шляху* Ви можете отримати вміст за допомогою: + +```Python +contents = await myfile.read() +``` +Якщо Ви знаходитесь у звичайній `def` *функції обробки шляху*, Ви можете отримати доступ до `UploadFile.file` безпосередньо, наприклад: + +```Python +contents = myfile.file.read() +``` + +/// note | Технічні деталі `async` + +Коли Ви використовуєте `async` методи, **FastAPI** виконує файлові операції у пулі потоків та очікує їх завершення. + +/// + +/// note | Технічні деталі Starlette + +`UploadFile` у **FastAPI** успадковується безпосередньо від `UploadFile` у **Starlette**, але додає деякі необхідні частини, щоб зробити його сумісним із **Pydantic** та іншими компонентами FastAPI. + +/// + +## Що таке "Form Data" + +Спосіб, у який HTML-форми (`

    `) надсилають дані на сервер, зазвичай використовує "спеціальне" кодування, відмінне від JSON. + +**FastAPI** забезпечує правильне зчитування цих даних з відповідної частини запиту, а не з JSON. + +/// note | Технічні деталі + +Дані з форм зазвичай кодуються за допомогою "media type" `application/x-www-form-urlencoded`, якщо вони не містять файлів. + +Але якщо форма містить файли, вона кодується у форматі `multipart/form-data`. Якщо Ви використовуєте `File`, **FastAPI** визначить, що потрібно отримати файли з відповідної частини тіла запиту. + +Щоб дізнатися більше про ці типи кодування та формові поля, ознайомтеся з документацією MDN щодо POST. + +/// + +/// warning | Увага + +Ви можете оголосити кілька параметрів `File` і `Form` в *операції шляху*, але Ви не можете одночасно оголошувати поля `Body`, які мають надходити у форматі JSON, оскільки тіло запиту буде закодоване у форматі `multipart/form-data`, а не `application/json`. + +Це не обмеження **FastAPI**, а особливість протоколу HTTP. + +/// + +## Опціональне Завантаження Файлів + +Файл можна зробити необов’язковим, використовуючи стандартні анотації типів і встановлюючи значення за замовчуванням `None`: + +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} + +## `UploadFile` із Додатковими Мета Даними + +Ви також можете використовувати `File()` разом із `UploadFile`, наприклад, для встановлення додаткових метаданих: + +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} + +## Завантаження Кількох Файлів + +Можна завантажувати кілька файлів одночасно. + +Вони будуть пов’язані з одним і тим самим "form field", який передається у вигляді "form data". + +Щоб це реалізувати, потрібно оголосити список `bytes` або `UploadFile`: + +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} + +Ви отримаєте, як і було оголошено, `list` із `bytes` або `UploadFile`. + +/// note | Технічні деталі + +Ви також можете використати `from starlette.responses import HTMLResponse`. + +**FastAPI** надає ті ж самі `starlette.responses`, що й `fastapi.responses`, для зручності розробників. Однак більшість доступних відповідей надходять безпосередньо від Starlette. + +/// + +### Завантаження декількох файлів із додатковими метаданими + +Так само як і раніше, Ви можете використовувати `File()`, щоб встановити додаткові параметри навіть для `UploadFile`: + +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} + +## Підсумок + +Використовуйте `File`, `bytes`та `UploadFile`, щоб оголошувати файли для завантаження у запитах, які надсилаються у вигляді form data. From b1102e2388e36d0b4a3c75c2d5a89656c3e55970 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 22 Feb 2025 22:02:06 +0000 Subject: [PATCH 840/932] =?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 [skip ci] --- 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 83ffa8deb..732f76438 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -26,6 +26,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-files.md`. PR [#13395](https://github.com/fastapi/fastapi/pull/13395) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-form-models.md`. PR [#13384](https://github.com/fastapi/fastapi/pull/13384) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-forms-and-files.md`. PR [#13386](https://github.com/fastapi/fastapi/pull/13386) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Update Korean translation for `docs/ko/docs/help-fastapi.md`. PR [#13262](https://github.com/fastapi/fastapi/pull/13262) by [@Zerohertz](https://github.com/Zerohertz). From 48676b4f112b7500721bdc239719dd89e3787c82 Mon Sep 17 00:00:00 2001 From: Valentyn Date: Sat, 22 Feb 2025 17:02:19 -0500 Subject: [PATCH 841/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/tutorial/header-params.md`=20(#1338?= =?UTF-8?q?1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/uk/docs/tutorial/header-params.md | 91 ++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 docs/uk/docs/tutorial/header-params.md diff --git a/docs/uk/docs/tutorial/header-params.md b/docs/uk/docs/tutorial/header-params.md new file mode 100644 index 000000000..09c70a4f6 --- /dev/null +++ b/docs/uk/docs/tutorial/header-params.md @@ -0,0 +1,91 @@ +# Header-параметри + +Ви можете визначати параметри заголовків, так само як визначаєте `Query`, `Path` і `Cookie` параметри. + +## Імпорт `Header` + +Спочатку імпортуйте `Header`: + +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[3] *} + +## Оголошення параметрів `Header` + +Потім оголосіть параметри заголовків, використовуючи ту ж структуру, що й для `Path`, `Query` та `Cookie`. + +Ви можете визначити значення за замовчуванням, а також усі додаткові параметри валідації або анотації: + +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *} + +/// note | Технічні деталі + +`Header`є "сестринським" класом для `Path`, `Query` і `Cookie`. Він також успадковується від загального класу `Param`. + +Але пам’ятайте, що при імпорті `Query`, `Path`, `Header` та інших із `fastapi`, то насправді вони є функціями, які повертають спеціальні класи. + +/// + +/// info | Інформація + +Щоб оголосити заголовки, потрібно використовувати `Header`, інакше параметри будуть інтерпретуватися як параметри запиту. + +/// + +## Автоматичне перетворення + +`Header` має додатковий функціонал порівняно з `Path`, `Query` та `Cookie`. + +Більшість стандартних заголовків розділяються символом «дефіс», також відомим як «мінус» (`-`). + +Але змінна, така як `user-agent`, є недійсною в Python. + +Тому, за замовчуванням, `Header` автоматично перетворює символи підкреслення (`_`) на дефіси (`-`) для отримання та документування заголовків. + +Оскільки заголовки HTTP не чутливі до регістру, Ви можете використовувати стандартний стиль Python ("snake_case"). + +Тому Ви можете використовувати `user_agent`, як зазвичай у коді Python, замість того щоб писати з великої літери, як `User_Agent` або щось подібне. + +Якщо Вам потрібно вимкнути автоматичне перетворення підкреслень у дефіси, встановіть `convert_underscores` в `Header` значення `False`: + +{* ../../docs_src/header_params/tutorial002_an_py310.py hl[10] *} + +/// warning | Увага + +Перед тим як встановити значення `False` для `convert_underscores` пам’ятайте, що деякі HTTP-проксі та сервери не підтримують заголовки з підкресленнями. + +/// + +## Дубльовані заголовки + +Можливо отримати дубльовані заголовки, тобто той самий заголовок із кількома значеннями. + +Це можна визначити, використовуючи список у типізації параметра. + +Ви отримаєте всі значення дубльованого заголовка у вигляді `list` у Python. + +Наприклад, щоб оголосити заголовок `X-Token`, який може з’являтися більше ніж один раз: + +{* ../../docs_src/header_params/tutorial003_an_py310.py hl[9] *} + +Якщо Ви взаємодієте з цією операцією шляху, надсилаючи два HTTP-заголовки, наприклад: + +``` +X-Token: foo +X-Token: bar +``` + +Відповідь буде така: + +```JSON +{ + "X-Token values": [ + "bar", + "foo" + ] +} +``` + +## Підсумок + +Оголошуйте заголовки за допомогою `Header`, використовуючи той самий підхід, що й для `Query`, `Path` та `Cookie`. + +Не хвилюйтеся про підкреслення у змінних — **FastAPI** автоматично конвертує їх. From b0215699137c41a96c57f650640cb9db1c25314a Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 22 Feb 2025 22:03:09 +0000 Subject: [PATCH 842/932] =?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 [skip ci] --- 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 732f76438..84d680d91 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -26,6 +26,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/header-params.md`. PR [#13381](https://github.com/fastapi/fastapi/pull/13381) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-files.md`. PR [#13395](https://github.com/fastapi/fastapi/pull/13395) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-form-models.md`. PR [#13384](https://github.com/fastapi/fastapi/pull/13384) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-forms-and-files.md`. PR [#13386](https://github.com/fastapi/fastapi/pull/13386) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). From ccc7c8fef9eaab9d74ad142c50847be7e38e250a Mon Sep 17 00:00:00 2001 From: Arthur Rio Date: Thu, 27 Feb 2025 05:29:20 -0700 Subject: [PATCH 843/932] =?UTF-8?q?=F0=9F=90=9B=20Ensure=20that=20`HTTPDig?= =?UTF-8?q?est`=20only=20raises=20an=20exception=20when=20`auto=5Ferror=20?= =?UTF-8?q?is=20True`=20(#2939)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: svlandeg --- fastapi/security/http.py | 11 +++++++---- tests/test_security_http_digest_optional.py | 4 ++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/fastapi/security/http.py b/fastapi/security/http.py index e06f3d66d..9ab2df3c9 100644 --- a/fastapi/security/http.py +++ b/fastapi/security/http.py @@ -413,8 +413,11 @@ class HTTPDigest(HTTPBase): else: return None if scheme.lower() != "digest": - raise HTTPException( - status_code=HTTP_403_FORBIDDEN, - detail="Invalid authentication credentials", - ) + if self.auto_error: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, + detail="Invalid authentication credentials", + ) + else: + return None return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials) diff --git a/tests/test_security_http_digest_optional.py b/tests/test_security_http_digest_optional.py index 1e6eb8bd7..0d66f9c72 100644 --- a/tests/test_security_http_digest_optional.py +++ b/tests/test_security_http_digest_optional.py @@ -37,8 +37,8 @@ def test_security_http_digest_incorrect_scheme_credentials(): response = client.get( "/users/me", headers={"Authorization": "Other invalidauthorization"} ) - assert response.status_code == 403, response.text - assert response.json() == {"detail": "Invalid authentication credentials"} + assert response.status_code == 200, response.text + assert response.json() == {"msg": "Create an account first"} def test_openapi_schema(): From d974fbdda06c606ee49c3d440d61a4018d249383 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 27 Feb 2025 12:29:47 +0000 Subject: [PATCH 844/932] =?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 [skip ci] --- 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 84d680d91..8754f5228 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Fixes + +* 🐛 Ensure that `HTTPDigest` only raises an exception when `auto_error is True`. PR [#2939](https://github.com/fastapi/fastapi/pull/2939) by [@arthurio](https://github.com/arthurio). + ### Refactors * ✅ Simplify tests for `query_params_str_validations`. PR [#13218](https://github.com/fastapi/fastapi/pull/13218) by [@alv2017](https://github.com/alv2017). From 26f27982ac6cf1930ae2db223a2dd35a7a8a9349 Mon Sep 17 00:00:00 2001 From: Joakim Nordling Date: Thu, 27 Feb 2025 15:06:27 +0200 Subject: [PATCH 845/932] =?UTF-8?q?=F0=9F=91=B7=20Use=20`wrangler-action`?= =?UTF-8?q?=20v3=20(#13415)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy-docs.yml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 0b3096143..aec327f48 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -62,10 +62,7 @@ jobs: env: PROJECT_NAME: fastapitiangolo BRANCH: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} - # TODO: Use v3 when it's fixed, probably in v3.11 - # https://github.com/cloudflare/wrangler-action/issues/307 - uses: cloudflare/wrangler-action@v3.14 - # uses: cloudflare/wrangler-action@v3 + uses: cloudflare/wrangler-action@v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} From 63208321785d6d11b72f4819fd7d154f14676d3a Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 27 Feb 2025 13:06:50 +0000 Subject: [PATCH 846/932] =?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 [skip ci] --- 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 8754f5228..de2062798 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -52,6 +52,7 @@ hide: ### Internal +* 👷 Use `wrangler-action` v3. PR [#13415](https://github.com/fastapi/fastapi/pull/13415) by [@joakimnordling](https://github.com/joakimnordling). * 🔧 Update sponsors: add CodeRabbit. PR [#13402](https://github.com/fastapi/fastapi/pull/13402) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update team: Add Ludovico. PR [#13390](https://github.com/fastapi/fastapi/pull/13390) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors: Add LambdaTest. PR [#13389](https://github.com/fastapi/fastapi/pull/13389) by [@tiangolo](https://github.com/tiangolo). From 7710a3480003518f48dc86cf29e8f19b5a4e5e46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 27 Feb 2025 15:39:48 +0100 Subject: [PATCH 847/932] =?UTF-8?q?=F0=9F=8D=B1=20Update=20sponsors:=20Cod?= =?UTF-8?q?eRabbit=20logo=20(#13424)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/img/sponsors/coderabbit.png | Bin 20695 -> 21167 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/docs/en/docs/img/sponsors/coderabbit.png b/docs/en/docs/img/sponsors/coderabbit.png index 74c25e88466fa1b5251f7136bb86103cf79e874f..1fb74569be3efae62ed0eb5608867b9d86e230b2 100644 GIT binary patch literal 21167 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 O0000 Date: Thu, 27 Feb 2025 14:40:09 +0000 Subject: [PATCH 848/932] =?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 [skip ci] --- 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 de2062798..5366ae437 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -19,6 +19,7 @@ hide: ### Docs +* 🍱 Update sponsors: CodeRabbit logo. PR [#13424](https://github.com/fastapi/fastapi/pull/13424) by [@tiangolo](https://github.com/tiangolo). * 🩺 Unify the badges across all tutorial translations. PR [#13329](https://github.com/fastapi/fastapi/pull/13329) by [@svlandeg](https://github.com/svlandeg). * 📝 Fix typos in virtual environments documentation. PR [#13396](https://github.com/fastapi/fastapi/pull/13396) by [@bullet-ant](https://github.com/bullet-ant). * 🐛 Fix issue with Swagger theme change example in the official tutorial. PR [#13289](https://github.com/fastapi/fastapi/pull/13289) by [@Zerohertz](https://github.com/Zerohertz). From 7eabff43de6717a366c79ec92b808da988c085a3 Mon Sep 17 00:00:00 2001 From: alv2017 Date: Thu, 27 Feb 2025 16:42:41 +0200 Subject: [PATCH 849/932] =?UTF-8?q?=E2=9C=85=20Fix=20a=20minor=20bug=20in?= =?UTF-8?q?=20the=20test=20`tests/test=5Fmodules=5Fsame=5Fname=5Fbody/test?= =?UTF-8?q?=5Fmain.py`=20(#13411)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../test_modules_same_name_body/test_main.py | 30 ++++++++----------- 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/tests/test_modules_same_name_body/test_main.py b/tests/test_modules_same_name_body/test_main.py index cc165bdca..263d87df2 100644 --- a/tests/test_modules_same_name_body/test_main.py +++ b/tests/test_modules_same_name_body/test_main.py @@ -1,3 +1,4 @@ +import pytest from fastapi.testclient import TestClient from .app.main import app @@ -5,29 +6,22 @@ from .app.main import app client = TestClient(app) -def test_post_a(): +@pytest.mark.parametrize( + "path", ["/a/compute", "/a/compute/", "/b/compute", "/b/compute/"] +) +def test_post(path): data = {"a": 2, "b": "foo"} - response = client.post("/a/compute", json=data) + response = client.post(path, json=data) assert response.status_code == 200, response.text - data = response.json() + assert data == response.json() -def test_post_a_invalid(): +@pytest.mark.parametrize( + "path", ["/a/compute", "/a/compute/", "/b/compute", "/b/compute/"] +) +def test_post_invalid(path): data = {"a": "bar", "b": "foo"} - response = client.post("/a/compute", json=data) - assert response.status_code == 422, response.text - - -def test_post_b(): - data = {"a": 2, "b": "foo"} - response = client.post("/b/compute/", json=data) - assert response.status_code == 200, response.text - data = response.json() - - -def test_post_b_invalid(): - data = {"a": "bar", "b": "foo"} - response = client.post("/b/compute/", json=data) + response = client.post(path, json=data) assert response.status_code == 422, response.text From 3639fb00be3acad3618f97c56859e221f7fba4a7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 27 Feb 2025 14:43:04 +0000 Subject: [PATCH 850/932] =?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 [skip ci] --- 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 5366ae437..95d0edfe7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -53,6 +53,7 @@ hide: ### Internal +* ✅ Fix a minor bug in the test `tests/test_modules_same_name_body/test_main.py`. PR [#13411](https://github.com/fastapi/fastapi/pull/13411) by [@alv2017](https://github.com/alv2017). * 👷 Use `wrangler-action` v3. PR [#13415](https://github.com/fastapi/fastapi/pull/13415) by [@joakimnordling](https://github.com/joakimnordling). * 🔧 Update sponsors: add CodeRabbit. PR [#13402](https://github.com/fastapi/fastapi/pull/13402) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update team: Add Ludovico. PR [#13390](https://github.com/fastapi/fastapi/pull/13390) by [@tiangolo](https://github.com/tiangolo). From d90030c1e242d1e954a097c253734122eec926e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 27 Feb 2025 17:40:41 +0100 Subject: [PATCH 851/932] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?5.9?= 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 95d0edfe7..833d52bda 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.115.9 + ### Fixes * 🐛 Ensure that `HTTPDigest` only raises an exception when `auto_error is True`. PR [#2939](https://github.com/fastapi/fastapi/pull/2939) by [@arthurio](https://github.com/arthurio). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index e3e0200ae..c0b4cb989 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.8" +__version__ = "0.115.9" from starlette import status as status From cc1f5de03c715d3908d19aa1216f14ba99c4dd6b Mon Sep 17 00:00:00 2001 From: Ben Beasley Date: Fri, 28 Feb 2025 09:07:47 -0500 Subject: [PATCH 852/932] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Bump=20Starlette?= =?UTF-8?q?=20to=20allow=20up=20to=200.46.0:=20`>=3D0.40.0,<0.47.0`=20(#13?= =?UTF-8?q?426)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sofie Van Landeghem --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 51d63fd44..1c540e2f6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,7 +43,7 @@ classifiers = [ "Topic :: Internet :: WWW/HTTP", ] dependencies = [ - "starlette>=0.40.0,<0.46.0", + "starlette>=0.40.0,<0.47.0", "pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0", "typing-extensions>=4.8.0", ] From b78887f3d3248ec3fad8cd0c93382354096d4f11 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 28 Feb 2025 14:08:09 +0000 Subject: [PATCH 853/932] =?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 [skip ci] --- 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 833d52bda..1c6bd259e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Upgrades + +* ⬆️ Bump Starlette to allow up to 0.46.0: `>=0.40.0,<0.47.0`. PR [#13426](https://github.com/fastapi/fastapi/pull/13426) by [@musicinmybrain](https://github.com/musicinmybrain). + ## 0.115.9 ### Fixes From 29d3739bcfd26160a4c77a391789feaffa416552 Mon Sep 17 00:00:00 2001 From: Valentyn Date: Fri, 28 Feb 2025 09:12:19 -0500 Subject: [PATCH 854/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/tutorial/testing.md`=20(#13371)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Valentyn Druzhynin Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Rostyslav Co-authored-by: Sofie Van Landeghem --- docs/uk/docs/tutorial/testing.md | 240 +++++++++++++++++++++++++++++++ 1 file changed, 240 insertions(+) create mode 100644 docs/uk/docs/tutorial/testing.md diff --git a/docs/uk/docs/tutorial/testing.md b/docs/uk/docs/tutorial/testing.md new file mode 100644 index 000000000..25fc370d6 --- /dev/null +++ b/docs/uk/docs/tutorial/testing.md @@ -0,0 +1,240 @@ +# Тестування + +Тестування **FastAPI** додатків є простим та ефективним завдяки бібліотеці Starlette, яка базується на HTTPX. +Оскільки HTTPX розроблений на основі Requests, його API є інтуїтивно зрозумілим для тих, хто вже знайомий з Requests. + +З його допомогою Ви можете використовувати pytest безпосередньо з **FastAPI**. + +## Використання `TestClient` + +/// info | Інформація + +Щоб використовувати `TestClient`, спочатку встановіть `httpx`. + +Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили саму бібліотеку, наприклад: + +```console +$ pip install httpx +``` + +/// + +Імпортуйте `TestClient`. + +Створіть `TestClient`, передавши йому Ваш застосунок **FastAPI**. + +Створюйте функції з іменами, що починаються з `test_` (це стандартна угода для `pytest`). + +Використовуйте об'єкт `TestClient` так само як і `httpx`. + +Записуйте прості `assert`-вирази зі стандартними виразами Python, які потрібно перевірити (це також стандарт для `pytest`). + +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} + + +/// tip | Порада + +Зверніть увагу, що тестові функції — це звичайні `def`, а не `async def`. + +Виклики клієнта також звичайні, без використання `await`. + +Це дозволяє використовувати `pytest` без зайвих ускладнень. + +/// + +/// note | Технічні деталі + +Ви також можете використовувати `from starlette.testclient import TestClient`. + +**FastAPI** надає той самий `starlette.testclient` під назвою `fastapi.testclient` для зручності розробників, але він безпосередньо походить із Starlette. + +/// + +/// tip | Порада + +Якщо Вам потрібно викликати `async`-функції у ваших тестах, окрім відправлення запитів до FastAPI-застосунку (наприклад, асинхронні функції роботи з базою даних), перегляньте [Асинхронні тести](../advanced/async-tests.md){.internal-link target=_blank} у розширеному керівництві. + +/// + +## Розділення тестів + +У реальному застосунку Ваші тести, ймовірно, будуть в окремому файлі. + +Також Ваш **FastAPI**-застосунок може складатися з кількох файлів або модулів тощо. + +### Файл застосунку **FastAPI** + +Припустимо, у Вас є структура файлів, описана в розділі [Більші застосунки](bigger-applications.md){.internal-link target=_blank}: + +``` +. +├── app +│   ├── __init__.py +│   └── main.py +``` +У файлі `main.py` знаходиться Ваш застосунок **FastAPI** : + +{* ../../docs_src/app_testing/main.py *} + +### Файл тестування + +Ви можете створити файл `test_main.py` з Вашими тестами. Він може знаходитися в тому ж пакеті Python (у тій самій директорії з файлом `__init__.py`): + + +``` hl_lines="5" +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Оскільки цей файл знаходиться в тому ж пакеті, Ви можете використовувати відносний імпорт, щоб імпортувати об'єкт `app` із модуля `main` (`main.py`): + +{* ../../docs_src/app_testing/test_main.py hl[3] *} + + +...і написати код для тестів так само як і раніше. + +## Тестування: розширений приклад + +Тепер розширимо цей приклад і додамо більше деталей, щоб побачити, як тестувати різні частини. + +### Розширений файл застосунку **FastAPI** + +Залишимо ту саму структуру файлів: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Припустимо, що тепер файл `main.py` із Вашим **FastAPI**-застосунком містить додаткові операції шляху (**path operations**). + +Він має `GET`-операцію, яка може повертати помилку. + +Він має `POST`-операцію, яка може повертати кілька помилок. + +Обидві операції шляху вимагають заголовок `X-Token`. + +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/app_testing/app_b_an/main.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Порада + +Бажано використовувати версію з `Annotated`, якщо це можливо + +/// + +```Python +{!> ../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Порада + +Бажано використовувати версію з `Annotated`, якщо це можливо + +/// + +```Python +{!> ../../docs_src/app_testing/app_b/main.py!} +``` + +//// + +### Розширений тестовий файл + +Потім Ви можете оновити `test_main.py`, додавши розширені тести: + +{* ../../docs_src/app_testing/app_b/test_main.py *} + +Коли Вам потрібно передати клієнту інформацію в запиті, але Ви не знаєте, як це зробити, Ви можете пошукати (наприклад, у Google) спосіб реалізації в `httpx`, або навіть у `requests`, оскільки HTTPX розроблений на основі дизайну Requests. + +Далі Ви просто повторюєте ці ж дії у ваших тестах. + +Наприклад: + +* Щоб передати *path* або *query* параметр, додайте його безпосередньо до URL. +* Щоб передати тіло JSON, передайте Python-об'єкт (наприклад, `dict`) у параметр `json`. +* Якщо потрібно надіслати *Form Data* замість JSON, використовуйте параметр `data`. +* Щоб передати заголовки *headers*, використовуйте `dict` у параметрі `headers`. +* Для *cookies* використовуйте `dict` у параметрі `cookies`. + +Докладніше про передачу даних у бекенд (за допомогою `httpx` або `TestClient`) можна знайти в документації HTTPX. + +/// info | Інформація + +Зверніть увагу, що `TestClient` отримує дані, які можна конвертувати в JSON, а не Pydantic-моделі. +Якщо у Вас є Pydantic-модель у тесті, і Ви хочете передати її дані в додаток під час тестування, Ви можете використати `jsonable_encoder`, описаний у розділі [JSON Compatible Encoder](encoder.md){.internal-link target=_blank}. + +/// + +## Запуск тестів + +Після цього вам потрібно встановити `pytest`. + +Переконайтеся, що Ви створили [віртуальне середовище]{.internal-link target=_blank}, активували його і встановили необхідні пакети, наприклад: + +
    + +```console +$ pip install pytest + +---> 100% +``` + +
    + +`pytest` автоматично знайде файли з тестами, виконає їх і надасть вам результати. + +Запустіть тести за допомогою: + +
    + +```console +$ pytest + +================ test session starts ================ +platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 +rootdir: /home/user/code/superawesome-cli/app +plugins: forked-1.1.3, xdist-1.31.0, cov-2.8.1 +collected 6 items + +---> 100% + +test_main.py ...... [100%] + +================= 1 passed in 0.03s ================= +``` + +
    From e992a2ec8bf8f5b40ec3fe9e3d38afcb6682b98c Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 28 Feb 2025 14:12:41 +0000 Subject: [PATCH 855/932] =?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 [skip ci] --- 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 1c6bd259e..88357912d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,10 @@ hide: * ⬆️ Bump Starlette to allow up to 0.46.0: `>=0.40.0,<0.47.0`. PR [#13426](https://github.com/fastapi/fastapi/pull/13426) by [@musicinmybrain](https://github.com/musicinmybrain). +### Translations + +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/testing.md`. PR [#13371](https://github.com/fastapi/fastapi/pull/13371) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). + ## 0.115.9 ### Fixes From f4b4b0b0f5b7bc3b616d14d1ece7aa000100faa0 Mon Sep 17 00:00:00 2001 From: Valentyn Date: Fri, 28 Feb 2025 09:13:50 -0500 Subject: [PATCH 856/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/tutorial/request-forms.md`=20(#1338?= =?UTF-8?q?3)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Valentyn Druzhynin Co-authored-by: Rostyslav --- docs/uk/docs/tutorial/request-forms.md | 73 ++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 docs/uk/docs/tutorial/request-forms.md diff --git a/docs/uk/docs/tutorial/request-forms.md b/docs/uk/docs/tutorial/request-forms.md new file mode 100644 index 000000000..10c58a73e --- /dev/null +++ b/docs/uk/docs/tutorial/request-forms.md @@ -0,0 +1,73 @@ +# Дані форми + +Якщо Вам потрібно отримувати поля форми замість JSON, Ви можете використовувати `Form`. + +/// info | Інформація + +Щоб використовувати форми, спочатку встановіть `python-multipart`. + +Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, і потім встановили бібліотеку, наприклад: + +```console +$ pip install python-multipart +``` + +/// + +## Імпорт `Form` + +Імпортуйте `Form` з `fastapi`: + +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} + +## Оголошення параметрів `Form` + +Створюйте параметри форми так само як Ви б створювали `Body` або `Query`: + +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} + +Наприклад, один зі способів використання специфікації OAuth2 (так званий "password flow") вимагає надсилати `username` та `password` як поля форми. + +spec вимагає, щоб ці поля мали точні назви `username` і `password` та надсилалися у вигляді полів форми, а не JSON. + +З `Form` Ви можете оголошувати ті ж конфігурації, що і з `Body` (та `Query`, `Path`, `Cookie`), включаючи валідацію, приклади, псевдоніми (наприклад, `user-name` замість `username`) тощо. + +/// info | Інформація + +`Form` — це клас, який безпосередньо наслідується від `Body`. + +/// + +/// tip | Порада + +Щоб оголосити тіло форми, потрібно явно використовувати `Form`, оскільки без нього параметри будуть інтерпретуватися як параметри запиту або тіла (JSON). + +/// + +## Про "поля форми" + +HTML-форми (`
    `) надсилають дані на сервер у "спеціальному" кодуванні, яке відрізняється від JSON. + +**FastAPI** подбає про те, щоб зчитати ці дані з правильного місця, а не з JSON. + +/// note | Технічні деталі + +Дані з форм зазвичай кодуються за допомогою "типу медіа" `application/x-www-form-urlencoded`. + +Але якщо форма містить файли, вона кодується як `multipart/form-data`. Ви дізнаєтеся про обробку файлів у наступному розділі. + +Якщо Ви хочете дізнатися більше про ці кодування та поля форм, зверніться до MDN вебдокументації для POST. + +/// + +/// warning | Попередження + +Ви можете оголосити кілька параметрів `Form` в *операції шляху*, але не можете одночасно оголосити поля `Body`, які Ви очікуєте отримати у форматі JSON, оскільки тіло запиту буде закодовано у форматі `application/x-www-form-urlencoded`, а не `application/json`. + +Це не обмеження **FastAPI**, а частина HTTP-протоколу. + +/// + +## Підсумок + +Використовуйте `Form` для оголошення вхідних параметрів у вигляді даних форми. From eb7cd4f6939f350c8ec9bb22e4dc62229a645c26 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 28 Feb 2025 14:14:34 +0000 Subject: [PATCH 857/932] =?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 [skip ci] --- 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 88357912d..cc7f6154c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-forms.md`. PR [#13383](https://github.com/fastapi/fastapi/pull/13383) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/testing.md`. PR [#13371](https://github.com/fastapi/fastapi/pull/13371) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). ## 0.115.9 From 2d60add4e2975c5f254729b8c76f54c5ef70bb01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=C6=B0=C6=A1ng=20T=E1=BA=A5n=20Th=C3=A0nh?= <51350651+ptt3199@users.noreply.github.com> Date: Fri, 28 Feb 2025 21:14:58 +0700 Subject: [PATCH 858/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Vietnamese=20trans?= =?UTF-8?q?lation=20for=20`docs/vi/docs/deployment/index.md`=20(#13405)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/vi/docs/deployment/index.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 docs/vi/docs/deployment/index.md diff --git a/docs/vi/docs/deployment/index.md b/docs/vi/docs/deployment/index.md new file mode 100644 index 000000000..24ffdc71b --- /dev/null +++ b/docs/vi/docs/deployment/index.md @@ -0,0 +1,21 @@ +# Triển khai + +Triển khai một ứng dụng **FastAPI** khá dễ dàng. + +## Triển khai là gì + +Triển khai một ứng dụng có nghĩa là thực hiện các bước cần thiết để làm cho nó **sẵn sàng phục vụ người dùng**. + +Đối với một **API web**, điều này có nghĩa là đặt nó trong một **máy chủ từ xa**, với một **chương trình máy chủ** cung cấp hiệu suất tốt, ổn định, v.v., để người dùng của bạn có thể truy cập ứng dụng của bạn một cách hiệu quả và không bị gián đoạn hoặc gặp vấn đề. + +Điều này trái ngược với các **giai đoạn phát triển**, trong đó bạn liên tục thay đổi mã, phá vỡ nó và sửa nó, ngừng và khởi động lại máy chủ phát triển, v.v. + +## Các Chiến lược Triển khai + +Có nhiều cách để triển khai ứng dụng của bạn tùy thuộc vào trường hợp sử dụng của bạn và các công cụ mà bạn sử dụng. + +Bạn có thể **triển khai một máy chủ** của riêng bạn bằng cách sử dụng một sự kết hợp các công cụ, hoặc bạn có thể sử dụng một **dịch vụ cloud** để làm một số công việc cho bạn, hoặc các tùy chọn khác. + +Tôi sẽ chỉ ra một số khái niệm chính cần thiết khi triển khai một ứng dụng **FastAPI** (mặc dù hầu hết nó áp dụng cho bất kỳ loại ứng dụng web nào). + +Bạn sẽ thấy nhiều chi tiết cần thiết và một số kỹ thuật để triển khai trong các phần tiếp theo. ✨ From d5324fb5c3b643e081d07a6b17a742176bf5d958 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=C6=B0=C6=A1ng=20T=E1=BA=A5n=20Th=C3=A0nh?= <51350651+ptt3199@users.noreply.github.com> Date: Fri, 28 Feb 2025 21:15:38 +0700 Subject: [PATCH 859/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Vietnamese=20trans?= =?UTF-8?q?lation=20for=20`docs/vi/docs/deployment/versions.md`=20(#13406)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sofie Van Landeghem --- docs/vi/docs/deployment/versions.md | 93 +++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 docs/vi/docs/deployment/versions.md diff --git a/docs/vi/docs/deployment/versions.md b/docs/vi/docs/deployment/versions.md new file mode 100644 index 000000000..04de393e7 --- /dev/null +++ b/docs/vi/docs/deployment/versions.md @@ -0,0 +1,93 @@ +# Về các phiên bản của FastAPI + +**FastAPI** đã được sử dụng ở quy mô thực tế (production) trong nhiều ứng dụng và hệ thống. Và phạm vi kiểm thử được giữ ở mức 100%. Nhưng việc phát triển của nó vẫn đang diễn ra nhanh chóng. + +Các tính năng mới được bổ sung thường xuyên, lỗi được sửa định kỳ, và mã nguồn vẫn đang được cải thiện liên tục + +Đó là lí do các phiên bản hiện tại vẫn còn là 0.x.x, điều này phản ánh rằng mỗi phiên bản có thể có các thay đổi gây mất tương thích. Điều này tuân theo các quy ước về Semantic Versioning. + +Bạn có thể tạo ra sản phẩm thực tế với **FastAPI** ngay bây giờ (và bạn có thể đã làm điều này trong một thời gian dài), bạn chỉ cần đảm bảo rằng bạn sử dụng một phiên bản hoạt động đúng với các đoạn mã còn lại của bạn. + +## Cố định phiên bản của `fastapi` + +Điều đầu tiên bạn nên làm là "cố định" phiên bản của **FastAPI** bạn đang sử dụng để phiên bản mới nhất mà bạn biết hoạt động đúng với ứng dụng của bạn. + +Ví dụ, giả sử bạn đang sử dụng phiên bản `0.112.0` trong ứng dụng của bạn. + +Nếu bạn sử dụng một tệp `requirements.txt` bạn có thể chỉ định phiên bản với: + +```txt +fastapi[standard]==0.112.0 +``` + +Như vậy, bạn sẽ sử dụng chính xác phiên bản `0.112.0`. + +Hoặc bạn cũng có thể cố định nó với: + +```txt +fastapi[standard]>=0.112.0,<0.113.0 +``` + +Như vậy, bạn sẽ sử dụng các phiên bản `0.112.0` trở lên, nhưng nhỏ hơn `0.113.0`, ví dụ, một phiên bản `0.112.2` vẫn được chấp nhận. + +Nếu bạn sử dụng bất kỳ công cụ nào để quản lý cài đặt của bạn, như `uv`, Poetry, Pipenv, hoặc bất kỳ công cụ nào khác, chúng đều có một cách để bạn có thể định nghĩa các phiên bản cụ thể cho các gói của bạn. + +## Các phiên bản có sẵn + +Bạn có thể xem các phiên bản có sẵn (ví dụ để kiểm tra phiên bản mới nhất) trong [Release Notes](../release-notes.md){.internal-link target=_blank}. + +## Về các phiên bản + +Theo quy ước về Semantic Versioning, bất kỳ phiên bản nào bên dưới `1.0.0` có thể thêm các thay đổi gây mất tương thích. + +**FastAPI** cũng theo quy ước rằng bất kỳ thay đổi phiên bản "PATCH" nào là cho các lỗi và các thay đổi không gây mất tương thích. + +/// tip + +"PATCH" là số cuối cùng, ví dụ, trong `0.2.3`, phiên bản PATCH là `3`. + +/// + +Vì vậy, bạn có thể cố định đến một phiên bản như: + +```txt +fastapi>=0.45.0,<0.46.0 +``` + +Các thay đổi gây mất tương thích và các tính năng mới được thêm vào trong các phiên bản "MINOR". + +/// tip + +"MINOR" là số ở giữa, ví dụ, trong `0.2.3`, phiên bản MINOR là `2`. + +/// + +## Nâng cấp các phiên bản của FastAPI + +Bạn nên thêm các bài kiểm tra (tests) cho ứng dụng của bạn. + +Với **FastAPI** điều này rất dễ dàng (nhờ vào Starlette), kiểm tra tài liệu: [Testing](../tutorial/testing.md){.internal-link target=_blank} + +Sau khi bạn có các bài kiểm tra, bạn có thể nâng cấp phiên bản **FastAPI** lên một phiên bản mới hơn, và đảm bảo rằng tất cả mã của bạn hoạt động đúng bằng cách chạy các bài kiểm tra của bạn. + +Nếu mọi thứ đang hoạt động, hoặc sau khi bạn thực hiện các thay đổi cần thiết, và tất cả các bài kiểm tra của bạn đều đi qua, thì bạn có thể cố định phiên bản của `fastapi` đến phiên bản mới hơn. + +## Về Starlette + +Bạn không nên cố định phiên bản của `starlette`. + +Các phiên bản khác nhau của **FastAPI** sẽ sử dụng một phiên bản Starlette mới hơn. + +Vì vậy, bạn có thể để **FastAPI** sử dụng phiên bản Starlette phù hợp. + +## Về Pydantic + +Pydantic bao gồm các bài kiểm tra của riêng nó cho **FastAPI**, vì vậy các phiên bản mới hơn của Pydantic (trên `1.0.0`) luôn tương thích với **FastAPI**. + +Bạn có thể cố định Pydantic đến bất kỳ phiên bản nào trên `1.0.0` mà bạn muốn. + +Ví dụ: + +```txt +pydantic>=2.7.0,<3.0.0 +``` From 67e7c15701d9531338e9e1c676d6b3d2b5c41b14 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 28 Feb 2025 14:15:51 +0000 Subject: [PATCH 860/932] =?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 [skip ci] --- 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 cc7f6154c..714531cfe 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Vietnamese translation for `docs/vi/docs/deployment/index.md`. PR [#13405](https://github.com/fastapi/fastapi/pull/13405) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-forms.md`. PR [#13383](https://github.com/fastapi/fastapi/pull/13383) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/testing.md`. PR [#13371](https://github.com/fastapi/fastapi/pull/13371) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). From 34e03db0683a1d5d24902ff236ea10b833bff9e7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 28 Feb 2025 14:16:22 +0000 Subject: [PATCH 861/932] =?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 [skip ci] --- 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 714531cfe..fd5059145 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Vietnamese translation for `docs/vi/docs/deployment/versions.md`. PR [#13406](https://github.com/fastapi/fastapi/pull/13406) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Vietnamese translation for `docs/vi/docs/deployment/index.md`. PR [#13405](https://github.com/fastapi/fastapi/pull/13405) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-forms.md`. PR [#13383](https://github.com/fastapi/fastapi/pull/13383) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/testing.md`. PR [#13371](https://github.com/fastapi/fastapi/pull/13371) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). From 99ea5bb641774d99a93a28264d925c95b91abbaf Mon Sep 17 00:00:00 2001 From: Valentyn Date: Fri, 28 Feb 2025 09:18:01 -0500 Subject: [PATCH 862/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/tutorial/body-nested-models.md`=20(?= =?UTF-8?q?#13409)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Valentyn Druzhynin Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sofie Van Landeghem --- docs/uk/docs/tutorial/body-nested-models.md | 245 ++++++++++++++++++++ 1 file changed, 245 insertions(+) create mode 100644 docs/uk/docs/tutorial/body-nested-models.md diff --git a/docs/uk/docs/tutorial/body-nested-models.md b/docs/uk/docs/tutorial/body-nested-models.md new file mode 100644 index 000000000..abc33f2eb --- /dev/null +++ b/docs/uk/docs/tutorial/body-nested-models.md @@ -0,0 +1,245 @@ +# Тіло запиту - Вкладені моделі + +З **FastAPI** Ви можете визначати, перевіряти, документувати та використовувати моделі, які можуть бути вкладені на будь-яку глибину (завдяки Pydantic). + +## Поля списку + +Ви можете визначити атрибут як підтип. Наприклад, Python-список (`list`): + +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} + +Це зробить `tags` списком, хоча не визначається тип елементів списку. + +## Поля списку з параметром типу + +Але Python має специфічний спосіб оголошення списків з внутрішніми типами або "параметрами типу": +### Імпортуємо `List` з модуля typing + +У Python 3.9 і вище можна використовувати стандартний `list` для оголошення таких типів, як ми побачимо нижче. 💡 + +Але в Python версії до 3.9 (від 3.6 і вище) спочатку потрібно імпортувати `List` з модуля стандартної бібліотеки Python `typing`: + +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} + +### Оголошення `list` з параметром типу + +Щоб оголосити типи з параметрами типу (внутрішніми типами), такими як `list`, `dict`, `tuple`: + +* Якщо Ви використовуєте версію Python до 3.9, імпортуйте їх відповідну версію з модуля `typing`. +* Передайте внутрішні типи як "параметри типу", використовуючи квадратні дужки: `[` and `]`. + +У Python 3.9 це буде виглядати так: + +```Python +my_list: list[str] +``` + +У версіях Python до 3.9 це виглядає так: + +```Python +from typing import List + +my_list: List[str] +``` + +Це стандартний синтаксис Python для оголошення типів. + +Використовуйте той самий стандартний синтаксис для атрибутів моделей з внутрішніми типами. + +Отже, у нашому прикладі, ми можемо зробити `tags` саме "списком рядків": + +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} + +## Типи множин + +Але потім ми подумали, що теги не повинні повторюватися, вони, ймовірно, повинні бути унікальними рядками. + +І Python має спеціальний тип даних для множин унікальних елементів — це `set`. + +Тому ми можемо оголосити `tags` як множину рядків: + +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} + +Навіть якщо Ви отримаєте запит з дубльованими даними, він буде перетворений у множину унікальних елементів. + +І коли Ви будете виводити ці дані, навіть якщо джерело містить дублікати, вони будуть виведені як множина унікальних елементів. + +І це буде анотовано/документовано відповідно. + +## Вкладені моделі + +Кожен атрибут моделі Pydantic має тип. + +Але цей тип сам може бути іншою моделлю Pydantic. + +Отже, Ви можете оголосити глибоко вкладені JSON "об'єкти" з конкретними іменами атрибутів, типами та перевірками. + +Усе це, вкладене без обмежень. + +### Визначення підмоделі + +Наприклад, ми можемо визначити модель `Image`: + +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} + +### Використання підмоделі як типу + +А потім ми можемо використовувати її як тип атрибута: + +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} + +Це означатиме, що **FastAPI** очікуватиме тіло запиту такого вигляду: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": ["rock", "metal", "bar"], + "image": { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + } +} +``` + +Завдяки такій декларації у **FastAPI** Ви отримуєте: + +* Підтримку в редакторі (автозавершення тощо), навіть для вкладених моделей +* Конвертацію даних +* Валідацію даних +* Автоматичну документацію + +## Спеціальні типи та валідація + +Окрім звичайних типів, таких як `str`, `int`, `float`, та ін. Ви можете використовувати складніші типи, які наслідують `str`. + +Щоб побачити всі доступні варіанти, ознайомтеся з оглядом типів у Pydantic. Деякі приклади будуть у наступних розділах. + +Наприклад, у моделі `Image` є поле `url`, тому ми можемо оголосити його як `HttpUrl` від Pydantic замість `str`: + +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} + +Рядок буде перевірено як дійсну URL-адресу і задокументовано в JSON Schema / OpenAPI як URL. + +## Атрибути зі списками підмоделей + +У Pydantic Ви можете використовувати моделі як підтипи для `list`, `set` тощо: + +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} + +Це означає, що **FastAPI** буде очікувати (конвертувати, валідувати, документувати тощо) JSON тіло запиту у вигляді: + +```JSON hl_lines="11" +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": [ + "rock", + "metal", + "bar" + ], + "images": [ + { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + }, + { + "url": "http://example.com/dave.jpg", + "name": "The Baz" + } + ] +} +``` + +/// info | Інформація + +Зверніть увагу, що тепер ключ `images` містить список об'єктів зображень. + +/// + +## Глибоко вкладені моделі + +Ви можете визначати вкладені моделі довільної глибини: + +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} + +/// info | Інформація + +Зверніть увагу, що в моделі `Offer` є список `Item`ів, які, своєю чергою, можуть мати необов'язковий список `Image`ів. + +/// + +## Тіла запитів, що складаються зі списків + +Якщо верхній рівень JSON тіла, яке Ви очікуєте, є JSON `масивом` (у Python — `list`), Ви можете оголосити тип у параметрі функції, як і в моделях Pydantic: + +```Python +images: List[Image] +``` +або в Python 3.9 і вище: + +```Python +images: list[Image] +``` + +наприклад: + +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} + +## Підтримка в редакторі всюди + +Ви отримаєте підтримку в редакторі всюди. + +Навіть для елементів у списках: + + + +Ви не змогли б отримати таку підтримку в редакторі, якби працювали напряму зі `dict`, а не з моделями Pydantic. + +Але Вам не потрібно турбуватися про це: вхідні dict'и автоматично конвертуються, а вихідні дані автоматично перетворюються в JSON. + +## Тіла з довільними `dict` + +Ви також можете оголосити тіло як `dict` з ключами одного типу та значеннями іншого типу. + +Це корисно, якщо Ви не знаєте наперед, які імена полів будуть дійсними (як у випадку з моделями Pydantic). + +Це буде корисно, якщо Ви хочете приймати ключі, які заздалегідь невідомі. + +--- + +Це також зручно, якщо Ви хочете мати ключі іншого типу (наприклад, `int`). + +Ось що ми розглянемо далі. + +У цьому випадку Ви можете приймати будь-який `dict`, якщо його ключі — це `int`, а значення — `float`: + +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} + +/// tip | Порада + +Майте на увазі, що в JSON тілі ключі можуть бути лише рядками (`str`). + +Але Pydantic автоматично конвертує дані. + +Це означає, що навіть якщо клієнти вашого API надсилатимуть ключі у вигляді рядків, якщо вони містять цілі числа, Pydantic конвертує їх і проведе валідацію. + +Тобто `dict`, який Ви отримаєте як `weights`, матиме ключі типу `int` та значення типу `float`. + +/// + +## Підсумок + +З **FastAPI** Ви маєте максимальну гнучкість завдяки моделям Pydantic, зберігаючи при цьому код простим, коротким та елегантним. + +А також отримуєте всі переваги: + +* Підтримка в редакторі (автодоповнення всюди!) +* Конвертація даних (парсинг/сериалізація) +* Валідація даних +* Документація схем +* Автоматичне створення документації From 7047e59f2927e3b53b2033d2c9aa4ce53a81ab16 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 28 Feb 2025 14:18:36 +0000 Subject: [PATCH 863/932] =?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 [skip ci] --- 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 fd5059145..7f9aacbb5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-nested-models.md`. PR [#13409](https://github.com/fastapi/fastapi/pull/13409) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Vietnamese translation for `docs/vi/docs/deployment/versions.md`. PR [#13406](https://github.com/fastapi/fastapi/pull/13406) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Vietnamese translation for `docs/vi/docs/deployment/index.md`. PR [#13405](https://github.com/fastapi/fastapi/pull/13405) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-forms.md`. PR [#13383](https://github.com/fastapi/fastapi/pull/13383) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). From 2cf2fee588cf23a47b4899471aad57eda2035fd6 Mon Sep 17 00:00:00 2001 From: k94-ishi <32672580+k94-ishi@users.noreply.github.com> Date: Fri, 28 Feb 2025 23:18:46 +0900 Subject: [PATCH 864/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/query-param-models.md`=20(#?= =?UTF-8?q?13323)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ja/docs/tutorial/query-param-models.md | 68 +++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 docs/ja/docs/tutorial/query-param-models.md diff --git a/docs/ja/docs/tutorial/query-param-models.md b/docs/ja/docs/tutorial/query-param-models.md new file mode 100644 index 000000000..053d0740b --- /dev/null +++ b/docs/ja/docs/tutorial/query-param-models.md @@ -0,0 +1,68 @@ +# クエリパラメータモデル + +もし関連する**複数のクエリパラメータ**から成るグループがあるなら、それらを宣言するために、**Pydanticモデル**を作成できます。 + +こうすることで、**複数の場所**で**そのPydanticモデルを再利用**でき、バリデーションやメタデータを、すべてのクエリパラメータに対して一度に宣言できます。😎 + +/// note | 備考 + +この機能は、FastAPIのバージョン `0.115.0` からサポートされています。🤓 + +/// + +## クエリパラメータにPydanticモデルを使用する + +必要な**複数のクエリパラメータ**を**Pydanticモデル**で宣言し、さらに、それを `Query` として宣言しましょう: + +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} + +**FastAPI**は、リクエストの**クエリパラメータ**からそれぞれの**フィールド**のデータを**抽出**し、定義された**Pydanticモデル**を提供します。 + +## ドキュメントの確認 + +対話的APIドキュメント `/docs` でクエリパラメータを確認できます: + +
    + +
    + +## 余分なクエリパラメータを禁止する + +特定の(あまり一般的ではないかもしれない)ケースで、受け付けるクエリパラメータを**制限**する必要があるかもしれません。 + +Pydanticのモデルの Configuration を利用して、 `extra` フィールドを `forbid` とすることができます。 + +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} + +もしクライアントが**クエリパラメータ**として**余分な**データを送ろうとすると、**エラー**レスポンスが返されます。 + +例えば、クライアントがクエリパラメータ `tool` に、値 `plumbus` を設定して送ろうとすると: + +```http +https://example.com/items/?limit=10&tool=plumbus +``` + +クエリパラメータ `tool` が許可されていないことを通知する**エラー**レスポンスが返されます。 + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus" + } + ] +} +``` + +## まとめ + +**FastAPI**では、**クエリパラメータ**を宣言するために、**Pydanticモデル**を使用できます。😎 + +/// tip | 豆知識 + +ネタバレ注意: Pydanticモデルはクッキーやヘッダーの宣言にも使用できますが、その内容については後のチュートリアルで学びます。🤫 + +/// From c42c0d31b0aece706776dde8e6de39cc7c4dd5b7 Mon Sep 17 00:00:00 2001 From: Valentyn Date: Fri, 28 Feb 2025 09:19:00 -0500 Subject: [PATCH 865/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/tutorial/body-multiple-params.md`?= =?UTF-8?q?=20(#13408)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Valentyn Druzhynin Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sofie Van Landeghem --- docs/uk/docs/tutorial/body-multiple-params.md | 170 ++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 docs/uk/docs/tutorial/body-multiple-params.md diff --git a/docs/uk/docs/tutorial/body-multiple-params.md b/docs/uk/docs/tutorial/body-multiple-params.md new file mode 100644 index 000000000..e2acf8a70 --- /dev/null +++ b/docs/uk/docs/tutorial/body-multiple-params.md @@ -0,0 +1,170 @@ +# Тіло запиту - Декілька параметрів + +Тепер, коли ми розглянули використання `Path` та `Query`, розгляньмо більш просунуті способи оголошення тіла запиту в **FastAPI**. + +## Змішування `Path`, `Query` та параметрів тіла запиту + +По-перше, звісно, Ви можете вільно змішувати оголошення параметрів `Path`, `Query` та тіла запиту, і **FastAPI** правильно їх обробить. + +Також Ви можете оголосити параметри тіла як необов’язкові, встановивши для них значення за замовчуванням `None`: + +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} + +/// note | Примітка + +Зверніть увагу, що в цьому випадку параметр `item`, який береться з тіла запиту, є необов'язковим, оскільки має значення за замовчуванням `None`. + +/// + +## Декілька параметрів тіла запиту + +У попередньому прикладі *операція шляху* очікувала JSON з атрибутами `Item`, наприклад: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` +Але Ви також можете оголосити декілька параметрів тіла, наприклад `item` та `user`: + +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} + +У цьому випадку **FastAPI** розпізнає, що є кілька параметрів тіла (два параметри є моделями Pydantic). + +Тому він використає назви параметрів як ключі (назви полів) у тілі запиту, очікуючи: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +/// note | Примітка + +Зверніть увагу, що хоча `item` оголошено, так само як і раніше, тепер він очікується в тілі під ключем `item`. + +/// + +**FastAPI** автоматично конвертує дані із запиту таким чином, щоб параметр `item` отримав свій вміст, і те ж саме стосується `user`. + +Він виконає валідацію складених даних і задокументує їх відповідним чином у схемі OpenAPI та в автоматичній документації. + +## Одиничні значення в тілі запиту + +Так само як є `Query` і `Path` для визначення додаткових даних для параметрів запиту та шляху, **FastAPI** надає еквівалентний `Body`. + +Наприклад, розширюючи попередню модель, Ви можете вирішити додати ще один ключ `importance` в те ж саме тіло запиту разом із `item` і `user`. + +Якщо Ви оголосите його як є, то, оскільки це одиничне значення, **FastAPI** припускатиме, що це параметр запиту (query parameter). + +Але Ви можете вказати **FastAPI** обробляти його як інший ключ тіла (body key), використовуючи `Body`: + +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} + +У цьому випадку **FastAPI** очікуватиме тіло запиту у такому вигляді: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` +Знову ж таки, **FastAPI** конвертуватиме типи даних, перевірятиме їх, створюватиме документацію тощо. + +## Декілька body та query параметрів + +Звісно, Ви можете оголошувати додаткові query параметри запиту, коли це необхідно, на додаток до будь-яких параметрів тіла запиту. + +Оскільки за замовчуванням окремі значення інтерпретуються як параметри запиту, Вам не потрібно явно додавати `Query`, можна просто використати: + +```Python +q: Union[str, None] = None +``` + +Або в Python 3.10 та вище: + +```Python +q: str | None = None +``` + +Наприклад: + +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *} + + +/// info | Інформація + +`Body` також має ті самі додаткові параметри валідації та метаданих, що й `Query`, `Path` та інші, які Ви побачите пізніше. + +/// + +## Вкладений поодинокий параметр тіла запиту + +Припустимо, у вас є лише один параметр тіла запиту `item` з моделі Pydantic `Item`. + +За замовчуванням **FastAPI** очікуватиме, що тіло запиту міститиме вміст безпосередньо. + +Але якщо Ви хочете, щоб він очікував JSON з ключем `item`, а всередині — вміст моделі (так, як це відбувається при оголошенні додаткових параметрів тіла), Ви можете використати спеціальний параметр `Body` — `embed`: + +```Python +item: Item = Body(embed=True) +``` + +як у прикладі: + +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} + +У цьому випадку **FastAPI** очікуватиме тіло запиту такого вигляду: + +```JSON hl_lines="2" +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +замість: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +## Підсумок + +Ви можете додавати кілька параметрів тіла до Вашої *функції операції шляху* (*path operation function*), навіть якщо запит може мати лише одне тіло. + +Але **FastAPI** обробить це, надасть Вам потрібні дані у функції, перевірить їх та задокументує коректну схему в *операції шляху*. + +Також Ви можете оголошувати окремі значення, які будуть отримані як частина тіла запиту. + +Крім того, Ви можете вказати **FastAPI** вбудовувати тіло в ключ, навіть якщо оголошено лише один параметр. From f9c8726a1a67132831c9c20cbd160e80b62f2b37 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 28 Feb 2025 14:19:27 +0000 Subject: [PATCH 866/932] =?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 [skip ci] --- 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 7f9aacbb5..1a2f5abc2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/query-param-models.md`. PR [#13323](https://github.com/fastapi/fastapi/pull/13323) by [@k94-ishi](https://github.com/k94-ishi). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-nested-models.md`. PR [#13409](https://github.com/fastapi/fastapi/pull/13409) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Vietnamese translation for `docs/vi/docs/deployment/versions.md`. PR [#13406](https://github.com/fastapi/fastapi/pull/13406) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Vietnamese translation for `docs/vi/docs/deployment/index.md`. PR [#13405](https://github.com/fastapi/fastapi/pull/13405) by [@ptt3199](https://github.com/ptt3199). From 720dcc0990d2b125085aecad1dd0761119213f38 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 28 Feb 2025 14:19:54 +0000 Subject: [PATCH 867/932] =?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 [skip ci] --- 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 1a2f5abc2..79269bc1b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-multiple-params.md`. PR [#13408](https://github.com/fastapi/fastapi/pull/13408) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/query-param-models.md`. PR [#13323](https://github.com/fastapi/fastapi/pull/13323) by [@k94-ishi](https://github.com/k94-ishi). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-nested-models.md`. PR [#13409](https://github.com/fastapi/fastapi/pull/13409) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Vietnamese translation for `docs/vi/docs/deployment/versions.md`. PR [#13406](https://github.com/fastapi/fastapi/pull/13406) by [@ptt3199](https://github.com/ptt3199). From 344d76579622f285e75e394dd0b9404c8a1b11db Mon Sep 17 00:00:00 2001 From: k94-ishi <32672580+k94-ishi@users.noreply.github.com> Date: Fri, 28 Feb 2025 23:21:27 +0900 Subject: [PATCH 868/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/tutorial/cookie-param-models.md`=20(?= =?UTF-8?q?#13330)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ja/docs/tutorial/cookie-param-models.md | 77 ++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 docs/ja/docs/tutorial/cookie-param-models.md diff --git a/docs/ja/docs/tutorial/cookie-param-models.md b/docs/ja/docs/tutorial/cookie-param-models.md new file mode 100644 index 000000000..8285f44ef --- /dev/null +++ b/docs/ja/docs/tutorial/cookie-param-models.md @@ -0,0 +1,77 @@ +# クッキーパラメータモデル + +もし関連する**複数のクッキー**から成るグループがあるなら、それらを宣言するために、**Pydanticモデル**を作成できます。🍪 + +こうすることで、**複数の場所**で**そのPydanticモデルを再利用**でき、バリデーションやメタデータを、すべてのクッキーパラメータに対して一度に宣言できます。😎 + +/// note | 備考 + +この機能は、FastAPIのバージョン `0.115.0` からサポートされています。🤓 + +/// + +/// tip | 豆知識 + +これと同じテクニックは `Query` 、 `Cookie` 、 `Header` にも適用できます。 😎 + +/// + +## クッキーにPydanticモデルを使用する + +必要な複数の**クッキー**パラメータを**Pydanticモデル**で宣言し、さらに、それを `Cookie` として宣言しましょう: + +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} + +**FastAPI**は、リクエストの**クッキー**から**それぞれのフィールド**のデータを**抽出**し、定義された**Pydanticモデル**を提供します。 + +## ドキュメントの確認 + +対話的APIドキュメントUI `/docs` で、定義されているクッキーを確認できます: + +
    + +
    + +/// info | 備考 + + +**ブラウザがクッキーを処理し**ていますが、特別な方法で内部的に処理を行っているために、**JavaScript**からは簡単に操作**できない**ことに留意してください。 + +**対話的APIドキュメントUI** `/docs` にアクセスすれば、*パスオペレーション*に関するクッキーの**ドキュメンテーション**を確認できます。 + +しかし、たとえ**クッキーデータを入力して**「Execute」をクリックしても、対話的APIドキュメントUIは**JavaScript**で動作しているためクッキーは送信されず、まるで値を入力しなかったかのような**エラー**メッセージが表示されます。 + +/// + +## 余分なクッキーを禁止する + +特定の(あまり一般的ではないかもしれない)ケースで、受け付けるクッキーを**制限**する必要があるかもしれません。 + +あなたのAPIは独自の クッキー同意 を管理する能力を持っています。 🤪🍪 + +Pydanticのモデルの Configuration を利用して、 `extra` フィールドを `forbid` とすることができます。 + +{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *} + +もしクライアントが**余分なクッキー**を送ろうとすると、**エラー**レスポンスが返されます。 + +どうせAPIに拒否されるのにあなたの同意を得ようと精一杯努力する可哀想なクッキーバナーたち... 🍪 + +例えば、クライアントがクッキー `santa_tracker` を `good-list-please` という値で送ろうとすると、`santa_tracker` という クッキーが許可されていない ことを通知する**エラー**レスポンスが返されます: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "santa_tracker"], + "msg": "Extra inputs are not permitted", + "input": "good-list-please", + } + ] +} +``` + +## まとめ + +**FastAPI**では、**クッキー**を宣言するために、**Pydanticモデル**を使用できます。😎 From ee729d45225ee0d3bb93b071f305e493d1b381c3 Mon Sep 17 00:00:00 2001 From: Valentyn Date: Fri, 28 Feb 2025 09:21:46 -0500 Subject: [PATCH 869/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/tutorial/path-params.md`=20(#13354)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Valentyn Druzhynin Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sofie Van Landeghem --- docs/uk/docs/tutorial/path-params.md | 261 +++++++++++++++++++++++++++ 1 file changed, 261 insertions(+) create mode 100644 docs/uk/docs/tutorial/path-params.md diff --git a/docs/uk/docs/tutorial/path-params.md b/docs/uk/docs/tutorial/path-params.md new file mode 100644 index 000000000..e7df1f19a --- /dev/null +++ b/docs/uk/docs/tutorial/path-params.md @@ -0,0 +1,261 @@ +# Path Параметри + +Ви можете визначити "параметри" або "змінні" шляху, використовуючи синтаксис форматованих рядків: + +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} + +Значення параметра шляху `item_id` передається у функцію як аргумент `item_id`. + +Якщо запустити цей приклад та перейти за посиланням http://127.0.0.1:8000/items/foo, то отримаємо таку відповідь: + +```JSON +{"item_id":"foo"} +``` + +## Path параметри з типами + +Ви можете визначити тип параметра шляху у функції, використовуючи стандартні анотації типів Python: + +{* ../../docs_src/path_params/tutorial002.py hl[7] *} + +У такому випадку `item_id` визначається як `int`. + +/// check | Примітка + +Це дасть можливість підтримки редактора всередині функції з перевірками помилок, автодоповнення тощо. + +/// + +## Перетворення даних + +Якщо запустити цей приклад і перейти за посиланням http://127.0.0.1:8000/items/3, то отримаєте таку відповідь: + +```JSON +{"item_id":3} +``` + +/// check | Примітка + +Зверніть увагу, що значення, яке отримала (і повернула) ваша функція, — це `3`. Це Python `int`, а не рядок `"3"`. + +Отже, з таким оголошенням типу **FastAPI** автоматично виконує "парсинг" запитів. + +/// + +## Перевірка даних + +Якщо ж відкрити у браузері посилання http://127.0.0.1:8000/items/foo, то побачимо цікаву HTTP-помилку: + +```JSON +{ + "detail": [ + { + "type": "int_parsing", + "loc": [ + "path", + "item_id" + ], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": "https://errors.pydantic.dev/2.1/v/int_parsing" + } + ] +} +``` +тому що параметр шляху має значення `"foo"`, яке не є типом `int`. + +Таку саму помилку отримаємо, якщо передати `float` замість `int`, як бачимо, у цьому прикладі: http://127.0.0.1:8000/items/4.2 + +/// check | Примітка + +Отже, **FastAPI** надає перевірку типів з таким самим оголошенням типу в Python. + +Зверніть увагу, що помилка також чітко вказує саме на те місце, де валідація не пройшла. + +Це неймовірно корисно під час розробки та дебагінгу коду, що взаємодіє з вашим API. + +/// + +## Документація + +Тепер коли відкриєте свій браузер за посиланням http://127.0.0.1:8000/docs, то побачите автоматично згенеровану, інтерактивну API-документацію: + + + +/// check | Примітка + +Знову ж таки, лише з цим самим оголошенням типу в Python, FastAPI надає вам автоматичну, інтерактивну документацію (з інтеграцією Swagger UI). + +Зверніть увагу, що параметр шляху оголошений як ціле число. + + +/// + +## Переваги стандартизації, альтернативна документація + +І оскільки згенерована схема відповідає стандарту OpenAPI, існує багато сумісних інструментів. + +З цієї причини FastAPI також надає альтернативну документацію API (використовуючи ReDoc), до якої можна отримати доступ за посиланням http://127.0.0.1:8000/redoc: + + + +Таким чином, існує багато сумісних інструментів, включаючи інструменти для генерації коду для багатьох мов. + + +## Pydantic + +Вся валідація даних виконується за лаштунками за допомогою Pydantic, тому Ви отримуєте всі переваги від його використання. І можете бути впевнені, що все в надійних руках. + +Ви можете використовувати ті самі оголошення типів з `str`, `float`, `bool` та багатьма іншими складними типами даних. + +Декілька з них будуть розглянуті в наступних розділах посібника. + +## Порядок має значення + +При створенні *операцій шляху* можуть виникати ситуації, коли шлях фіксований. + +Наприклад, `/users/me`. Припустимо, що це шлях для отримання даних про поточного користувача. + +А також у вас може бути шлях `/users/{user_id}`, щоб отримати дані про конкретного користувача за його ID. + +Оскільки *операції шляху* оцінюються по черзі, Ви повинні переконатися, що шлях для `/users/me` оголошений перед шляхом для `/users/{user_id}`: + +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} + +Інакше шлях для `/users/{user_id}` також буде відповідати для `/users/me`, "вважаючи", що він отримує параметр `user_id` зі значенням `"me"`. + +Аналогічно, Ви не можете оголосити операцію шляху: + +{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *} + +Перша операція буде завжди використовуватися, оскільки шлях збігається першим. +## Попередньо визначені значення + +Якщо у вас є *операція шляху*, яка приймає *параметр шляху*, але Ви хочете, щоб можливі допустимі значення *параметра шляху* були попередньо визначені, Ви можете використати стандартний Python Enum. + +### Створення класу `Enum` + +Імпортуйте `Enum` і створіть підклас, що наслідується від `str` та `Enum`. + +Наслідуючи від `str`, документація API зможе визначити, що значення повинні бути типу `string`, і правильно їх відобразить. + +Після цього створіть атрибути класу з фіксованими значеннями, які будуть доступними допустимими значеннями: + +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} + +/// info | Додаткова інформація + +Перелічення (або enums) доступні в Python починаючи з версії 3.4. + +/// + +/// tip | Порада + +Якщо вам цікаво, "AlexNet", "ResNet" та "LeNet" — це просто назви ML моделей Machine Learning. + +/// + + +### Оголосіть *параметр шляху* + +Потім створіть *параметр шляху* з анотацією типу, використовуючи створений вами клас enum (`ModelName`): + +{* ../../docs_src/path_params/tutorial005.py hl[16] *} + +### Перевірка документації + +Оскільки доступні значення для *параметра шляху* визначені заздалегідь, інтерактивна документація зможе красиво їх відобразити: + + + +### Робота з *перелічуваннями* у Python + +Значення *параметра шляху* буде елементом *перелічування*. + +#### Порівняння *елементів перелічування* + +Ви можете порівнювати його з *елементами перелічування* у створеному вами enum `ModelName`: + +{* ../../docs_src/path_params/tutorial005.py hl[17] *} + +#### Отримання *значення перелічування* + +Ви можете отримати фактичне значення (у цьому випадку це `str`), використовуючи `model_name.value`, або загалом `your_enum_member.value`: + +{* ../../docs_src/path_params/tutorial005.py hl[20] *} + +/// tip | Порада + +Ви також можете отримати доступ до значення `"lenet"`, використовуючи `ModelName.lenet.value`. + +/// + + +#### Повернення *елементів перелічування* + +Ви можете повертати *елементи перелічування* з вашої *операції шляху*, навіть вкладені у JSON-тіло (наприклад, `dict`). + +Вони будуть перетворені на відповідні значення (у цьому випадку рядки) перед поверненням клієнту: + +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} + +На стороні клієнта Ви отримаєте відповідь у форматі JSON, наприклад: + +```JSON +{ + "model_name": "alexnet", + "message": "Deep Learning FTW!" +} +``` + +## Path-параметри, що містять шляхи + +Припустимо, у вас є *операція шляху* з маршрутом `/files/{file_path}`. + +Але вам потрібно, щоб `file_path` містив *шлях*, наприклад `home/johndoe/myfile.txt`. + +Отже, URL для цього файлу виглядатиме так: `/files/home/johndoe/myfile.txt`. + + + +### Підтримка OpenAPI + +OpenAPI не підтримує спосіб оголошення *параметра шляху*, що містить *шлях* всередині, оскільки це може призвести до сценаріїв, які складно тестувати та визначати. + +Однак (одначе), Ви все одно можете зробити це в **FastAPI**, використовуючи один із внутрішніх інструментів Starlette. + +Документація все ще працюватиме, хоча й не додаватиме опису про те, що параметр повинен містити шлях. + +### Конвертер шляху + +Використовуючи опцію безпосередньо зі Starlette, Ви можете оголосити *параметр шляху*, що містить *шлях*, використовуючи URL на кшталт: + +``` +/files/{file_path:path} +``` +У цьому випадку ім'я параметра — `file_path`, а остання частина `:path` вказує на те, що параметр повинен відповідати будь-якому *шляху*. + +Отже, Ви можете використати його так: + +{* ../../docs_src/path_params/tutorial004.py hl[6] *} + +/// tip | Порада + +Вам може знадобитися, щоб параметр містив `/home/johndoe/myfile.txt` із початковою косою рискою (`/`). + +У такому випадку URL виглядатиме так: `/files//home/johndoe/myfile.txt`, із подвійною косою рискою (`//`) між `files` і `home`. + +/// + +## Підсумок + +З **FastAPI**, використовуючи короткі, інтуїтивно зрозумілі та стандартні оголошення типів Python, Ви отримуєте: + +* Підтримку в редакторі: перевірка помилок, автодоповнення тощо. +* "Парсинг" даних +* Валідацію даних +* Анотацію API та автоматичну документацію + +І вам потрібно оголосити їх лише один раз. + +Це, ймовірно, основна видима перевага **FastAPI** порівняно з альтернативними фреймворками (окрім високої продуктивності). From 5fbaf6d28c17b3bcae37fa194104043f4f8ad265 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 28 Feb 2025 14:22:42 +0000 Subject: [PATCH 870/932] =?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 [skip ci] --- 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 79269bc1b..8c3a3127c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/cookie-param-models.md`. PR [#13330](https://github.com/fastapi/fastapi/pull/13330) by [@k94-ishi](https://github.com/k94-ishi). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-multiple-params.md`. PR [#13408](https://github.com/fastapi/fastapi/pull/13408) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/query-param-models.md`. PR [#13323](https://github.com/fastapi/fastapi/pull/13323) by [@k94-ishi](https://github.com/k94-ishi). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-nested-models.md`. PR [#13409](https://github.com/fastapi/fastapi/pull/13409) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). From 8bfec9fb6b4a8cd6a499c6e3e3c9de6ed0b6dc02 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 28 Feb 2025 14:23:04 +0000 Subject: [PATCH 871/932] =?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 [skip ci] --- 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 8c3a3127c..47af66a92 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/path-params.md`. PR [#13354](https://github.com/fastapi/fastapi/pull/13354) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/cookie-param-models.md`. PR [#13330](https://github.com/fastapi/fastapi/pull/13330) by [@k94-ishi](https://github.com/k94-ishi). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-multiple-params.md`. PR [#13408](https://github.com/fastapi/fastapi/pull/13408) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/query-param-models.md`. PR [#13323](https://github.com/fastapi/fastapi/pull/13323) by [@k94-ishi](https://github.com/k94-ishi). From 23821e916b40e9f9d981fe16aba4a888b80a049e Mon Sep 17 00:00:00 2001 From: Valentyn Date: Fri, 28 Feb 2025 09:23:55 -0500 Subject: [PATCH 872/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/tutorial/query-params.md`=20(#13362?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Valentyn Druzhynin Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> Co-authored-by: Sofie Van Landeghem --- docs/uk/docs/tutorial/query-params.md | 192 ++++++++++++++++++++++++++ 1 file changed, 192 insertions(+) create mode 100644 docs/uk/docs/tutorial/query-params.md diff --git a/docs/uk/docs/tutorial/query-params.md b/docs/uk/docs/tutorial/query-params.md new file mode 100644 index 000000000..16bb42af3 --- /dev/null +++ b/docs/uk/docs/tutorial/query-params.md @@ -0,0 +1,192 @@ +# Query Параметри + +Коли Ви оголошуєте інші параметри функції, які не є частиною параметрів шляху, вони автоматично інтерпретуються як "query" параметри. + +{* ../../docs_src/query_params/tutorial001.py hl[9] *} + +Query параметри — це набір пар ключ-значення, що йдуть після символу `?` в URL, розділені символами `&`. + +Наприклад, в URL: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +...query параметрами є: + +* `skip`: зі значенням `0` +* `limit`: зі значенням `10` + +Оскільки вони є частиною URL, вони "за замовчуванням" є рядками. + +Але коли Ви оголошуєте їх із типами Python (у наведеному прикладі як `int`), вони перетворюються на цей тип і проходять перевірку відповідності. + +Увесь той самий процес, який застосовується до параметрів шляху, також застосовується до query параметрів: + +* Підтримка в редакторі (автодоповнення, перевірка помилок) +* "Парсинг" даних +* Валідація даних +* Автоматична документація + + +## Значення за замовчуванням + +Оскільки query параметри не є фіксованою частиною шляху, вони можуть бути необов’язковими та мати значення за замовчуванням. + +У наведеному вище прикладі вони мають значення за замовчуванням: `skip=0` і `limit=10`. + +Отже, результат переходу за URL: + +``` +http://127.0.0.1:8000/items/ +``` +буде таким самим, як і перехід за посиланням: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +Але якщо Ви перейдете, наприклад, за посиланням: + +``` +http://127.0.0.1:8000/items/?skip=20 +``` + +Значення параметрів у вашій функції будуть такими: + +* `skip=20`: оскільки Ви вказали його в URL +* `limit=10`: оскільки це значення за замовчуванням + +## Необов'язкові параметри + +Аналогічно, Ви можете оголосити необов’язкові query параметри, встановивши для них значення за замовчуванням `None`: + +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} + +У цьому випадку параметр функції `q` буде необов’язковим і за замовчуванням матиме значення `None`. + +/// check | Примітка + +Також зверніть увагу, що **FastAPI** достатньо розумний, щоб визначити, що параметр шляху `item_id` є параметром шляху, а `q` — ні, отже, це query параметр. + +/// + +## Перетворення типу Query параметра + +Ви також можете оголошувати параметри типу `bool`, і вони будуть автоматично конвертовані: + +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} + +У цьому випадку, якщо Ви звернетесь до: + + +``` +http://127.0.0.1:8000/items/foo?short=1 +``` + +або + +``` +http://127.0.0.1:8000/items/foo?short=True +``` + +або + +``` +http://127.0.0.1:8000/items/foo?short=true +``` + +або + +``` +http://127.0.0.1:8000/items/foo?short=on +``` + +або + +``` +http://127.0.0.1:8000/items/foo?short=yes +``` + +або будь-який інший варіант написання (великі літери, перша літера велика тощо), ваша функція побачить параметр `short` зі значенням `True` з типом даних `bool`. В іншому випадку – `False`. + +## Кілька path і query параметрів + +Ви можете одночасно оголошувати кілька path і query параметрів, і **FastAPI** автоматично визначить, який з них до чого належить. + + +Не потрібно дотримуватись певного порядку їх оголошення. + +Вони визначаються за назвою: + +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} + +## Обов’язкові Query параметри + +Якщо Ви оголошуєте значення за замовчуванням для параметрів, які не є path-параметрами (у цьому розділі ми бачили поки що лише path параметри), тоді вони стають необов’язковими. + +Якщо Ви не хочете вказувати конкретні значення, але хочете зробити параметр опціональним, задайте `None` як значення за замовчуванням. + +Але якщо Ви хочете зробити query параметр обов’язковим, просто не вказуйте для нього значення за замовчуванням: + +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} + +Тут `needy` – обов’язковий query параметр типу `str`. + +Якщо Ви відкриєте у браузері URL-адресу: + +``` +http://127.0.0.1:8000/items/foo-item +``` + +...без додавання обов’язкового параметра `needy`, Ви побачите помилку: + +```JSON +{ + "detail": [ + { + "type": "missing", + "loc": [ + "query", + "needy" + ], + "msg": "Field required", + "input": null, + "url": "https://errors.pydantic.dev/2.1/v/missing" + } + ] +} +``` + +Оскільки `needy` є обов’язковим параметром, вам потрібно вказати його в URL: + +``` +http://127.0.0.1:8000/items/foo-item?needy=sooooneedy +``` + +...цей запит поверне: + +```JSON +{ + "item_id": "foo-item", + "needy": "sooooneedy" +} +``` + + +Звичайно, Ви можете визначити деякі параметри як обов’язкові, інші зі значенням за замовчуванням, а ще деякі — повністю опціональні: + +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} + +У цьому випадку є 3 query параметри: + +* `needy`, обов’язковий `str`. +* `skip`, `int` зі значенням за замовчуванням `0`. +* `limit`, опціональний `int`. + + +/// tip | Підказка + +Ви також можете використовувати `Enum`-и, так само як і з [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}. + +/// From 7c4d1fe13d37059f05796556c6d0a0c80ddbeee3 Mon Sep 17 00:00:00 2001 From: Valentyn Date: Fri, 28 Feb 2025 09:24:45 -0500 Subject: [PATCH 873/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/tutorial/debugging.md`=20(#13370)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Valentyn Druzhynin Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Rostyslav --- docs/uk/docs/tutorial/debugging.md | 112 +++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 docs/uk/docs/tutorial/debugging.md diff --git a/docs/uk/docs/tutorial/debugging.md b/docs/uk/docs/tutorial/debugging.md new file mode 100644 index 000000000..b0e5344f8 --- /dev/null +++ b/docs/uk/docs/tutorial/debugging.md @@ -0,0 +1,112 @@ +# Налагодження (Debugging) + +Ви можете під'єднати дебагер у Вашому редакторі коду, наприклад, у Visual Studio Code або PyCharm. + +## Виклик `uvicorn` + +У Вашому FastAPI-додатку імпортуйте та запустіть `uvicorn` безпосередньо: + +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} + +### Про `__name__ == "__main__"` + +Головна мета використання `__name__ == "__main__"` — це забезпечення виконання певного коду тільки тоді, коли файл запускається безпосередньо: + +
    + +```console +$ python myapp.py +``` + +
    + +але не виконується при його імпорті в інший файл, наприклад: + +```Python +from myapp import app +``` + +#### Детальніше + +Припустимо, Ваш файл називається `myapp.py`. + +Якщо Ви запустите його так: + +
    + +```console +$ python myapp.py +``` + +
    + +тоді внутрішня змінна `__name__`, яка створюється автоматично Python, матиме значення `"__main__"`. + +Отже, цей блок коду: + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +буде виконаний. + +--- + +Це не станеться, якщо Ви імпортуєте цей модуль (файл). + +Якщо у Вас є інший файл, наприклад `importer.py`, з наступним кодом: + +```Python +from myapp import app + +# Додатковий код +``` + +У цьому випадку автоматично створена змінна у файлі `myapp.py` не матиме значення змінної `__name__` як `"__main__"`. + +Отже, рядок: + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +не буде виконано. + +/// info | Інформація + +Більш детальну інформацію можна знайти в офіційній документації Python. + +/// + +## Запуск коду з вашим дебагером + +Оскільки Ви запускаєте сервер Uvicorn безпосередньо з Вашого коду, Ви можете запустити вашу Python програму (ваш FastAPI додаток) безпосередньо з дебагера. + +--- + +Наприклад, у Visual Studio Code Ви можете: + +* Перейдіть на вкладку "Debug". +* Натисніть "Add configuration...". +* Виберіть "Python" +* Запустіть дебагер з опцією "`Python: Current File (Integrated Terminal)`". + +Це запустить сервер з Вашим **FastAPI** кодом, зупиниться на точках зупину тощо. + +Ось як це може виглядати: + + + +--- +Якщо Ви використовуєте PyCharm, ви можете: + +* Відкрити меню "Run". +* Вибрати опцію "Debug...". +* Потім з'явиться контекстне меню. +* Вибрати файл для налагодження (у цьому випадку, `main.py`). + +Це запустить сервер з Вашим **FastAPI** кодом, зупиниться на точках зупину тощо. + +Ось як це може виглядати: + + From 74954352ede29062acb0c5177a6d783f92c7475a Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 28 Feb 2025 14:24:48 +0000 Subject: [PATCH 874/932] =?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 [skip ci] --- 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 47af66a92..9b93b3743 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/query-params.md`. PR [#13362](https://github.com/fastapi/fastapi/pull/13362) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/path-params.md`. PR [#13354](https://github.com/fastapi/fastapi/pull/13354) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/cookie-param-models.md`. PR [#13330](https://github.com/fastapi/fastapi/pull/13330) by [@k94-ishi](https://github.com/k94-ishi). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-multiple-params.md`. PR [#13408](https://github.com/fastapi/fastapi/pull/13408) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). From 45e018517bedfaaec0c40247362da931e5ecde31 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 28 Feb 2025 14:26:01 +0000 Subject: [PATCH 875/932] =?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 [skip ci] --- 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 9b93b3743..46eff6c9d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/debugging.md`. PR [#13370](https://github.com/fastapi/fastapi/pull/13370) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/query-params.md`. PR [#13362](https://github.com/fastapi/fastapi/pull/13362) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/path-params.md`. PR [#13354](https://github.com/fastapi/fastapi/pull/13354) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Japanese translation for `docs/ja/docs/tutorial/cookie-param-models.md`. PR [#13330](https://github.com/fastapi/fastapi/pull/13330) by [@k94-ishi](https://github.com/k94-ishi). From 15dd2b67d3f8763d5cd523b79a1c901c05d48bd7 Mon Sep 17 00:00:00 2001 From: Victorien <65306057+Viicos@users.noreply.github.com> Date: Fri, 28 Feb 2025 16:15:02 +0100 Subject: [PATCH 876/932] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Update=20internal?= =?UTF-8?q?=20annotation=20usage=20for=20compatibilty=20with=20Pydantic=20?= =?UTF-8?q?2.11=20(#13314)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sofie Van Landeghem Co-authored-by: svlandeg --- fastapi/dependencies/utils.py | 8 ++++---- tests/test_analyze_param.py | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) create mode 100644 tests/test_analyze_param.py diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index e2866b488..09dd6f1b9 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -449,15 +449,15 @@ def analyze_param( # We might check here that `default_value is RequiredParam`, but the fact is that the same # parameter might sometimes be a path parameter and sometimes not. See # `tests/test_infer_param_optionality.py` for an example. - field_info = params.Path(annotation=use_annotation) + field_info = params.Path(annotation=type_annotation) elif is_uploadfile_or_nonable_uploadfile_annotation( type_annotation ) or is_uploadfile_sequence_annotation(type_annotation): - field_info = params.File(annotation=use_annotation, default=default_value) + field_info = params.File(annotation=type_annotation, default=default_value) elif not field_annotation_is_scalar(annotation=type_annotation): - field_info = params.Body(annotation=use_annotation, default=default_value) + field_info = params.Body(annotation=type_annotation, default=default_value) else: - field_info = params.Query(annotation=use_annotation, default=default_value) + field_info = params.Query(annotation=type_annotation, default=default_value) field = None # It's a field_info, not a dependency diff --git a/tests/test_analyze_param.py b/tests/test_analyze_param.py new file mode 100644 index 000000000..9fd3fa6d0 --- /dev/null +++ b/tests/test_analyze_param.py @@ -0,0 +1,22 @@ +from inspect import signature + +from fastapi.dependencies.utils import ParamDetails, analyze_param +from pydantic import Field +from typing_extensions import Annotated + +from .utils import needs_pydanticv2 + + +def func(user: Annotated[int, Field(strict=True)]): ... + + +@needs_pydanticv2 +def test_analyze_param(): + result = analyze_param( + param_name="user", + annotation=signature(func).parameters["user"].annotation, + value=object(), + is_path_param=False, + ) + assert isinstance(result, ParamDetails) + assert result.field.field_info.annotation is int From 68074badcc036b908479b146bd64d61e6d953aa2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 28 Feb 2025 15:15:29 +0000 Subject: [PATCH 877/932] =?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 [skip ci] --- 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 46eff6c9d..f256a8d8e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Fixes + +* ♻️ Update internal annotation usage for compatibilty with Pydantic 2.11. PR [#13314](https://github.com/fastapi/fastapi/pull/13314) by [@Viicos](https://github.com/Viicos). + ### Upgrades * ⬆️ Bump Starlette to allow up to 0.46.0: `>=0.40.0,<0.47.0`. PR [#13426](https://github.com/fastapi/fastapi/pull/13426) by [@musicinmybrain](https://github.com/musicinmybrain). From 433837d9cabd4e87367eda9ab6c81cbea2bdf7dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 28 Feb 2025 17:43:04 +0100 Subject: [PATCH 878/932] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?5.10?= 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 f256a8d8e..0d04cb935 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.115.10 + ### Fixes * ♻️ Update internal annotation usage for compatibilty with Pydantic 2.11. PR [#13314](https://github.com/fastapi/fastapi/pull/13314) by [@Viicos](https://github.com/Viicos). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index c0b4cb989..a6e7e47fd 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.9" +__version__ = "0.115.10" from starlette import status as status From a2644728f6cdfe48c686803446ca92a5aa386061 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 28 Feb 2025 17:46:04 +0100 Subject: [PATCH 879/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 0d04cb935..fe455c686 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,7 +11,7 @@ hide: ### Fixes -* ♻️ Update internal annotation usage for compatibilty with Pydantic 2.11. PR [#13314](https://github.com/fastapi/fastapi/pull/13314) by [@Viicos](https://github.com/Viicos). +* ♻️ Update internal annotation usage for compatibility with Pydantic 2.11. PR [#13314](https://github.com/fastapi/fastapi/pull/13314) by [@Viicos](https://github.com/Viicos). ### Upgrades From bb98f7df6d85b91827d3144aacdc53bcd49ab2e8 Mon Sep 17 00:00:00 2001 From: alv2017 Date: Fri, 28 Feb 2025 19:09:29 +0200 Subject: [PATCH 880/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20=20`docs/ru/docs/tutorial/middleware.md`=20(#13412)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ru/docs/tutorial/middleware.md | 74 +++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 docs/ru/docs/tutorial/middleware.md diff --git a/docs/ru/docs/tutorial/middleware.md b/docs/ru/docs/tutorial/middleware.md new file mode 100644 index 000000000..845e881e1 --- /dev/null +++ b/docs/ru/docs/tutorial/middleware.md @@ -0,0 +1,74 @@ +# Middleware (Промежуточный слой) + +Вы можете добавить промежуточный слой (middleware) в **FastAPI** приложение. + +"Middleware" это функция, которая выполняется с каждым запросом до его обработки какой-либо конкретной *операцией пути*. +А также с каждым ответом перед его возвращением. + + +* Она принимает каждый поступающий **запрос**. +* Может что-то сделать с этим **запросом** или выполнить любой нужный код. +* Затем передает **запрос** для последующей обработки (какой-либо *операцией пути*). +* Получает **ответ** (от *операции пути*). +* Может что-то сделать с этим **ответом** или выполнить любой нужный код. +* И возвращает **ответ**. + +/// note | Технические детали + +Если у вас есть зависимости с `yield`, то код выхода (код после `yield`) будет выполняться *после* middleware. + +Если у вас имеются некие фоновые задачи (см. документацию), то они будут запущены после middleware. + +/// + +## Создание middleware + +Для создания middleware используйте декоратор `@app.middleware("http")`. + +Функция middleware получает: + +* `request` (объект запроса). +* Функцию `call_next`, которая получает `request` в качестве параметра. + * Эта функция передаёт `request` соответствующей *операции пути*. + * Затем она возвращает ответ `response`, сгенерированный *операцией пути*. +* Также имеется возможность видоизменить `response`, перед тем как его вернуть. + +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} + +/// tip | Примечание + +Имейте в виду, что можно добавлять свои собственные заголовки при помощи префикса 'X-'. + +Если же вы хотите добавить собственные заголовки, которые клиент сможет увидеть в браузере, то вам потребуется добавить их в настройки CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}), используя параметр `expose_headers`, см. документацию Starlette's CORS docs. + +/// + +/// note | Технические детали + +Вы также можете использовать `from starlette.requests import Request`. + +**FastAPI** предоставляет такой доступ для удобства разработчиков. Но, на самом деле, это `Request` из Starlette. + +/// + +### До и после `response` + +Вы можете добавить код, использующий `request` до передачи его какой-либо *операции пути*. + +А также после формирования `response`, до того, как вы его вернёте. + +Например, вы можете добавить собственный заголовок `X-Process-Time`, содержащий время в секундах, необходимое для обработки запроса и генерации ответа: + +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} + +/// tip | Примечание + +Мы используем `time.perf_counter()` вместо `time.time()` для обеспечения большей точности наших примеров. 🤓 + +/// + +## Другие middleware + +О других middleware вы можете узнать больше в разделе [Advanced User Guide: Advanced Middleware](../advanced/middleware.md){.internal-link target=_blank}. + +В следующем разделе вы можете прочитать, как настроить CORS с помощью middleware. From 3fca8b2be80d45282e68e8512a0aaebb6d5c458c Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 28 Feb 2025 17:10:10 +0000 Subject: [PATCH 881/932] =?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 [skip ci] --- 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 fe455c686..f78994c5a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Translations + +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/middleware.md`. PR [#13412](https://github.com/fastapi/fastapi/pull/13412) by [@alv2017](https://github.com/alv2017). + ## 0.115.10 ### Fixes From 89e0c105474075f5e6b50192da82d7189e5d6617 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 1 Mar 2025 18:19:17 +0100 Subject: [PATCH 882/932] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e=20-=20Sponsors=20(#13433)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions --- docs/en/data/github_sponsors.yml | 177 ++++++++++++++----------------- 1 file changed, 81 insertions(+), 96 deletions(-) diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml index feb4e727f..805d72b73 100644 --- a/docs/en/data/github_sponsors.yml +++ b/docs/en/data/github_sponsors.yml @@ -1,10 +1,10 @@ sponsors: -- - login: bump-sh - avatarUrl: https://avatars.githubusercontent.com/u/33217836?v=4 - url: https://github.com/bump-sh - - login: renderinc +- - login: renderinc avatarUrl: https://avatars.githubusercontent.com/u/36424661?v=4 url: https://github.com/renderinc + - login: bump-sh + avatarUrl: https://avatars.githubusercontent.com/u/33217836?v=4 + url: https://github.com/bump-sh - login: Nixtla avatarUrl: https://avatars.githubusercontent.com/u/79945230?v=4 url: https://github.com/Nixtla @@ -23,6 +23,9 @@ sponsors: - login: zuplo avatarUrl: https://avatars.githubusercontent.com/u/85497839?v=4 url: https://github.com/zuplo + - login: coderabbitai + avatarUrl: https://avatars.githubusercontent.com/u/132028505?v=4 + url: https://github.com/coderabbitai - login: porter-dev avatarUrl: https://avatars.githubusercontent.com/u/62078005?v=4 url: https://github.com/porter-dev @@ -59,6 +62,9 @@ sponsors: - login: Ponte-Energy-Partners avatarUrl: https://avatars.githubusercontent.com/u/114745848?v=4 url: https://github.com/Ponte-Energy-Partners + - login: LambdaTest-Inc + avatarUrl: https://avatars.githubusercontent.com/u/171592363?u=96606606a45fa170427206199014f2a5a2a4920b&v=4 + url: https://github.com/LambdaTest-Inc - login: BoostryJP avatarUrl: https://avatars.githubusercontent.com/u/57932412?v=4 url: https://github.com/BoostryJP @@ -80,9 +86,6 @@ sponsors: - login: yasyf avatarUrl: https://avatars.githubusercontent.com/u/709645?u=f36736b3c6a85f578886ecc42a740e7b436e7a01&v=4 url: https://github.com/yasyf -- - login: genzou9201 - avatarUrl: https://avatars.githubusercontent.com/u/42960762?u=1ca6c18c59e8b327ae584c545b72de31ebc05275&v=4 - url: https://github.com/genzou9201 - - login: primer-io avatarUrl: https://avatars.githubusercontent.com/u/62146168?v=4 url: https://github.com/primer-io @@ -98,24 +101,18 @@ sponsors: - - login: samuelcolvin avatarUrl: https://avatars.githubusercontent.com/u/4039449?u=42eb3b833047c8c4b4f647a031eaef148c16d93f&v=4 url: https://github.com/samuelcolvin - - login: ProteinQure - avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 - url: https://github.com/ProteinQure + - login: vincentkoc + avatarUrl: https://avatars.githubusercontent.com/u/25068?u=fbd5b2d51142daa4bdbc21e21953a3b8b8188a4a&v=4 + url: https://github.com/vincentkoc - login: ddilidili avatarUrl: https://avatars.githubusercontent.com/u/42176885?u=c0a849dde06987434653197b5f638d3deb55fc6c&v=4 url: https://github.com/ddilidili - login: otosky avatarUrl: https://avatars.githubusercontent.com/u/42260747?u=69d089387c743d89427aa4ad8740cfb34045a9e0&v=4 url: https://github.com/otosky - - login: khadrawy - avatarUrl: https://avatars.githubusercontent.com/u/13686061?u=59f25ef42ecf04c22657aac4238ce0e2d3d30304&v=4 - url: https://github.com/khadrawy - - login: mjohnsey - avatarUrl: https://avatars.githubusercontent.com/u/16784016?u=38fad2e6b411244560b3af99c5f5a4751bc81865&v=4 - url: https://github.com/mjohnsey - - login: ashi-agrawal - avatarUrl: https://avatars.githubusercontent.com/u/17105294?u=99c7a854035e5398d8e7b674f2d42baae6c957f8&v=4 - url: https://github.com/ashi-agrawal + - login: ramonalmeidam + avatarUrl: https://avatars.githubusercontent.com/u/45269580?u=3358750b3a5854d7c3ed77aaca7dd20a0f529d32&v=4 + url: https://github.com/ramonalmeidam - login: sepsi77 avatarUrl: https://avatars.githubusercontent.com/u/18682303?v=4 url: https://github.com/sepsi77 @@ -140,11 +137,17 @@ sponsors: - login: Leay15 avatarUrl: https://avatars.githubusercontent.com/u/32212558?u=c4aa9c1737e515959382a5515381757b1fd86c53&v=4 url: https://github.com/Leay15 + - login: BoYanZh + avatarUrl: https://avatars.githubusercontent.com/u/32470225?u=55b174d080382822759d74307f8a0355fa86e808&v=4 + url: https://github.com/BoYanZh - login: ygorpontelo avatarUrl: https://avatars.githubusercontent.com/u/32963605?u=35f7103f9c4c4c2589ae5737ee882e9375ef072e&v=4 url: https://github.com/ygorpontelo + - login: ProteinQure + avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 + url: https://github.com/ProteinQure - login: chickenandstats - avatarUrl: https://avatars.githubusercontent.com/u/79477966?v=4 + avatarUrl: https://avatars.githubusercontent.com/u/79477966?u=ae2b894aa954070db1d7830dab99b49eba4e4567&v=4 url: https://github.com/chickenandstats - login: kaoru0310 avatarUrl: https://avatars.githubusercontent.com/u/80977929?u=1b61d10142b490e56af932ddf08a390fae8ee94f&v=4 @@ -164,12 +167,6 @@ sponsors: - login: logic-automation avatarUrl: https://avatars.githubusercontent.com/u/144732884?v=4 url: https://github.com/logic-automation - - login: Torqsight-Labs - avatarUrl: https://avatars.githubusercontent.com/u/169598176?v=4 - url: https://github.com/Torqsight-Labs - - login: ramonalmeidam - avatarUrl: https://avatars.githubusercontent.com/u/45269580?u=3358750b3a5854d7c3ed77aaca7dd20a0f529d32&v=4 - url: https://github.com/ramonalmeidam - login: roboflow avatarUrl: https://avatars.githubusercontent.com/u/53104118?v=4 url: https://github.com/roboflow @@ -185,12 +182,6 @@ sponsors: - login: patricioperezv avatarUrl: https://avatars.githubusercontent.com/u/73832292?u=5f471f156e19ee7920e62ae0f4a47b95580e61cf&v=4 url: https://github.com/patricioperezv - - login: mintuhouse - avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4 - url: https://github.com/mintuhouse - - login: tcsmith - avatarUrl: https://avatars.githubusercontent.com/u/989034?u=7d8d741552b3279e8f4d3878679823a705a46f8f&v=4 - url: https://github.com/tcsmith - login: dodo5522 avatarUrl: https://avatars.githubusercontent.com/u/1362607?u=9bf1e0e520cccc547c046610c468ce6115bbcf9f&v=4 url: https://github.com/dodo5522 @@ -218,9 +209,15 @@ sponsors: - login: anomaly avatarUrl: https://avatars.githubusercontent.com/u/3654837?v=4 url: https://github.com/anomaly - - login: vincentkoc - avatarUrl: https://avatars.githubusercontent.com/u/25068?u=fbd5b2d51142daa4bdbc21e21953a3b8b8188a4a&v=4 - url: https://github.com/vincentkoc + - login: gorhack + avatarUrl: https://avatars.githubusercontent.com/u/4141690?u=ec119ebc4bdf00a7bc84657a71aa17834f4f27f3&v=4 + url: https://github.com/gorhack + - login: Ryandaydev + avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 + url: https://github.com/Ryandaydev + - login: jaredtrog + avatarUrl: https://avatars.githubusercontent.com/u/4381365?v=4 + url: https://github.com/jaredtrog - login: jstanden avatarUrl: https://avatars.githubusercontent.com/u/63288?u=c3658d57d2862c607a0e19c2101c3c51876e36ad&v=4 url: https://github.com/jstanden @@ -251,12 +248,12 @@ sponsors: - login: falkben avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 url: https://github.com/falkben + - login: mintuhouse + avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4 + url: https://github.com/mintuhouse - login: TrevorBenson avatarUrl: https://avatars.githubusercontent.com/u/9167887?u=dccbea3327a57750923333d8ebf1a0b3f1948949&v=4 url: https://github.com/TrevorBenson - - login: kaangiray26 - avatarUrl: https://avatars.githubusercontent.com/u/11297495?u=e85327a77db45906d44f3ff06dd7f3303c644096&v=4 - url: https://github.com/kaangiray26 - login: wdwinslow avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4 url: https://github.com/wdwinslow @@ -272,21 +269,18 @@ sponsors: - login: dannywade avatarUrl: https://avatars.githubusercontent.com/u/13680237?u=418ee985bd41577b20fde81417fb2d901e875e8a&v=4 url: https://github.com/dannywade - - login: gorhack - avatarUrl: https://avatars.githubusercontent.com/u/4141690?u=ec119ebc4bdf00a7bc84657a71aa17834f4f27f3&v=4 - url: https://github.com/gorhack - - login: Ryandaydev - avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 - url: https://github.com/Ryandaydev - - login: jaredtrog - avatarUrl: https://avatars.githubusercontent.com/u/4381365?v=4 - url: https://github.com/jaredtrog + - login: khadrawy + avatarUrl: https://avatars.githubusercontent.com/u/13686061?u=59f25ef42ecf04c22657aac4238ce0e2d3d30304&v=4 + url: https://github.com/khadrawy + - login: mjohnsey + avatarUrl: https://avatars.githubusercontent.com/u/16784016?u=38fad2e6b411244560b3af99c5f5a4751bc81865&v=4 + url: https://github.com/mjohnsey + - login: ashi-agrawal + avatarUrl: https://avatars.githubusercontent.com/u/17105294?u=99c7a854035e5398d8e7b674f2d42baae6c957f8&v=4 + url: https://github.com/ashi-agrawal - login: oliverxchen avatarUrl: https://avatars.githubusercontent.com/u/4471774?u=534191f25e32eeaadda22dfab4b0a428733d5489&v=4 url: https://github.com/oliverxchen - - login: ennui93 - avatarUrl: https://avatars.githubusercontent.com/u/5300907?u=5b5452725ddb391b2caaebf34e05aba873591c3a&v=4 - url: https://github.com/ennui93 - login: ternaus avatarUrl: https://avatars.githubusercontent.com/u/5481618?u=513a26b02a39e7a28d587cd37c6cc877ea368e6e&v=4 url: https://github.com/ternaus @@ -308,9 +302,6 @@ sponsors: - - login: pawamoy avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4 url: https://github.com/pawamoy - - login: engineerjoe440 - avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4 - url: https://github.com/engineerjoe440 - login: bnkc avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=db5e6f4f87836cad26c2aa90ce390ce49041c5a9&v=4 url: https://github.com/bnkc @@ -323,15 +314,12 @@ sponsors: - login: mobyw avatarUrl: https://avatars.githubusercontent.com/u/44370805?v=4 url: https://github.com/mobyw - - login: PelicanQ - avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4 - url: https://github.com/PelicanQ - - login: TheR1D - avatarUrl: https://avatars.githubusercontent.com/u/16740832?u=b0dfdbdb27b79729430c71c6128962f77b7b53f7&v=4 - url: https://github.com/TheR1D - - login: joshuatz - avatarUrl: https://avatars.githubusercontent.com/u/17817563?u=f1bf05b690d1fc164218f0b420cdd3acb7913e21&v=4 - url: https://github.com/joshuatz + - login: ArtyomVancyan + avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4 + url: https://github.com/ArtyomVancyan + - login: caviri + avatarUrl: https://avatars.githubusercontent.com/u/45425937?u=4e14bd64282bad8f385eafbdb004b5a279366d6e&v=4 + url: https://github.com/caviri - login: SebTota avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4 url: https://github.com/SebTota @@ -350,12 +338,9 @@ sponsors: - login: dvlpjrs avatarUrl: https://avatars.githubusercontent.com/u/32254642?u=fbd6ad0324d4f1eb6231cf775be1c7bd4404e961&v=4 url: https://github.com/dvlpjrs - - login: ArtyomVancyan - avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4 - url: https://github.com/ArtyomVancyan - - login: caviri - avatarUrl: https://avatars.githubusercontent.com/u/45425937?u=4e14bd64282bad8f385eafbdb004b5a279366d6e&v=4 - url: https://github.com/caviri + - login: engineerjoe440 + avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4 + url: https://github.com/engineerjoe440 - login: hgalytoby avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=62c7ff3519858423579676cd0efbd7e3f1ffe63a&v=4 url: https://github.com/hgalytoby @@ -368,9 +353,9 @@ sponsors: - login: PunRabbit avatarUrl: https://avatars.githubusercontent.com/u/70463212?u=1a835cfbc99295a60c8282f6aa6199d1b42241a5&v=4 url: https://github.com/PunRabbit - - login: tochikuji - avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4 - url: https://github.com/tochikuji + - login: PelicanQ + avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4 + url: https://github.com/PelicanQ - login: browniebroke avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4 url: https://github.com/browniebroke @@ -389,9 +374,6 @@ sponsors: - login: Alisa-lisa avatarUrl: https://avatars.githubusercontent.com/u/4137964?u=e7e393504f554f4ff15863a1e01a5746863ef9ce&v=4 url: https://github.com/Alisa-lisa - - login: hcristea - avatarUrl: https://avatars.githubusercontent.com/u/7814406?u=61d7a4fcf846983a4606788eac25e1c6c1209ba8&v=4 - url: https://github.com/hcristea - login: ddanier avatarUrl: https://avatars.githubusercontent.com/u/113563?u=ed1dc79de72f93bd78581f88ebc6952b62f472da&v=4 url: https://github.com/ddanier @@ -404,15 +386,9 @@ sponsors: - login: ceb10n avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 url: https://github.com/ceb10n - - login: eteq - avatarUrl: https://avatars.githubusercontent.com/u/346587?v=4 - url: https://github.com/eteq - - login: securancy - avatarUrl: https://avatars.githubusercontent.com/u/606673?v=4 - url: https://github.com/securancy - - login: moonape1226 - avatarUrl: https://avatars.githubusercontent.com/u/8532038?u=d9f8b855a429fff9397c3833c2ff83849ebf989d&v=4 - url: https://github.com/moonape1226 + - login: tochikuji + avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4 + url: https://github.com/tochikuji - login: msehnout avatarUrl: https://avatars.githubusercontent.com/u/9369632?u=8c988f1b008a3f601385a3616f9327820f66e3a5&v=4 url: https://github.com/msehnout @@ -420,7 +396,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=a80a7bb349555b277645632ed66639ff43400614&v=4 url: https://github.com/xncbf - login: DMantis - avatarUrl: https://avatars.githubusercontent.com/u/9536869?v=4 + avatarUrl: https://avatars.githubusercontent.com/u/9536869?u=652dd0d49717803c0cbcbf44f7740e53cf2d4892&v=4 url: https://github.com/DMantis - login: hard-coders avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 @@ -434,18 +410,18 @@ sponsors: - login: pheanex avatarUrl: https://avatars.githubusercontent.com/u/10408624?u=5b6bab6ee174aa6e991333e06eb29f628741013d&v=4 url: https://github.com/pheanex - - login: dzoladz - avatarUrl: https://avatars.githubusercontent.com/u/10561752?u=5ee314d54aa79592c18566827ad8914debd5630d&v=4 - url: https://github.com/dzoladz - login: Zuzah avatarUrl: https://avatars.githubusercontent.com/u/10934846?u=1ef43e075ddc87bd1178372bf4d95ee6175cae27&v=4 url: https://github.com/Zuzah - login: artempronevskiy avatarUrl: https://avatars.githubusercontent.com/u/12235104?u=03df6e1e55c9c6fe5d230adabb8dd7d43d8bbe8f&v=4 url: https://github.com/artempronevskiy - - login: Graeme22 - avatarUrl: https://avatars.githubusercontent.com/u/4185684?u=498182a42300d7bcd4de1215190cb17eb501136c&v=4 - url: https://github.com/Graeme22 + - login: TheR1D + avatarUrl: https://avatars.githubusercontent.com/u/16740832?u=b0dfdbdb27b79729430c71c6128962f77b7b53f7&v=4 + url: https://github.com/TheR1D + - login: joshuatz + avatarUrl: https://avatars.githubusercontent.com/u/17817563?u=f1bf05b690d1fc164218f0b420cdd3acb7913e21&v=4 + url: https://github.com/joshuatz - login: danielunderwood avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4 url: https://github.com/danielunderwood @@ -470,6 +446,12 @@ sponsors: - login: harsh183 avatarUrl: https://avatars.githubusercontent.com/u/7780198?v=4 url: https://github.com/harsh183 + - login: hcristea + avatarUrl: https://avatars.githubusercontent.com/u/7814406?u=19092923a4ea5b338567961c8270b9206a6d81bb&v=4 + url: https://github.com/hcristea + - login: moonape1226 + avatarUrl: https://avatars.githubusercontent.com/u/8532038?u=d9f8b855a429fff9397c3833c2ff83849ebf989d&v=4 + url: https://github.com/moonape1226 - - login: larsyngvelundin avatarUrl: https://avatars.githubusercontent.com/u/34173819?u=74958599695bf83ac9f1addd935a51548a10c6b0&v=4 url: https://github.com/larsyngvelundin @@ -479,6 +461,9 @@ sponsors: - login: rwxd avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=cd04a39e3655923be4f25c2ba8a5a07b3da3230a&v=4 url: https://github.com/rwxd + - login: morzan1001 + avatarUrl: https://avatars.githubusercontent.com/u/47593005?u=c30ab7230f82a12a9b938dcb54f84a996931409a&v=4 + url: https://github.com/morzan1001 - login: sadikkuzu avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=d179c06bb9f65c4167fcab118526819f8e0dac17&v=4 url: https://github.com/sadikkuzu @@ -488,12 +473,12 @@ sponsors: - login: FabulousCodingFox avatarUrl: https://avatars.githubusercontent.com/u/78906517?u=924a27cbee3db7e0ece5cc1509921402e1445e74&v=4 url: https://github.com/FabulousCodingFox - - login: gateremark - avatarUrl: https://avatars.githubusercontent.com/u/91592218?u=969314eb2cfb035196f4d19499ec6f5050d7583a&v=4 - url: https://github.com/gateremark - - login: morzan1001 - avatarUrl: https://avatars.githubusercontent.com/u/47593005?u=c30ab7230f82a12a9b938dcb54f84a996931409a&v=4 - url: https://github.com/morzan1001 + - login: anqorithm + avatarUrl: https://avatars.githubusercontent.com/u/61029571?u=468256fa4e2d9ce2870b608299724bebb7a33f18&v=4 + url: https://github.com/anqorithm + - login: Materacl + avatarUrl: https://avatars.githubusercontent.com/u/70155818?u=ae11d084518856127cca483816a91a187e3124ee&v=4 + url: https://github.com/Materacl - login: Toothwitch avatarUrl: https://avatars.githubusercontent.com/u/1710406?u=5eebb23b46cd26e48643b9e5179536cad491c17a&v=4 url: https://github.com/Toothwitch From 186544760a803b39895ad9a563d56646a334588c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 1 Mar 2025 18:19:24 +0100 Subject: [PATCH 883/932] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e=20-=20Contributors=20and=20Translators=20(#13432)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions --- docs/en/data/contributors.yml | 38 +++-- docs/en/data/translation_reviewers.yml | 199 ++++++++++++++++--------- docs/en/data/translators.yml | 56 ++++--- 3 files changed, 194 insertions(+), 99 deletions(-) diff --git a/docs/en/data/contributors.yml b/docs/en/data/contributors.yml index 0e1a6505b..c4364e923 100644 --- a/docs/en/data/contributors.yml +++ b/docs/en/data/contributors.yml @@ -1,11 +1,11 @@ tiangolo: login: tiangolo - count: 713 + count: 723 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 url: https://github.com/tiangolo dependabot: login: dependabot - count: 90 + count: 94 avatarUrl: https://avatars.githubusercontent.com/in/29110?v=4 url: https://github.com/apps/dependabot alejsdev: @@ -68,6 +68,11 @@ vishnuvskvkl: count: 8 avatarUrl: https://avatars.githubusercontent.com/u/84698110?u=8af5de0520dd4fa195f53c2850a26f57c0f6bc64&v=4 url: https://github.com/vishnuvskvkl +svlandeg: + login: svlandeg + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 + url: https://github.com/svlandeg alissadb: login: alissadb count: 6 @@ -88,16 +93,16 @@ waynerv: count: 5 avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 url: https://github.com/waynerv -svlandeg: - login: svlandeg - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 - url: https://github.com/svlandeg krishnamadhavan: login: krishnamadhavan count: 5 avatarUrl: https://avatars.githubusercontent.com/u/31798870?u=950693b28f3ae01105fd545c046e46ca3d31ab06&v=4 url: https://github.com/krishnamadhavan +alv2017: + login: alv2017 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 jekirl: login: jekirl count: 4 @@ -121,7 +126,7 @@ adriangb: iudeen: login: iudeen count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=f09cdd745e5bf16138f29b42732dd57c7f02bee1&v=4 url: https://github.com/iudeen philipokiokio: login: philipokiokio @@ -211,7 +216,7 @@ TeoZosa: graingert: login: graingert count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/413772?u=64b77b6aa405c68a9c6bcf45f84257c66eea5f32&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/413772?v=4 url: https://github.com/graingert jaystone776: login: jaystone776 @@ -233,6 +238,11 @@ papb: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/20914054?u=890511fae7ea90d887e2a65ce44a1775abba38d5&v=4 url: https://github.com/papb +musicinmybrain: + login: musicinmybrain + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/6898909?u=9010312053e7141383b9bdf538036c7f37fbaba0&v=4 + url: https://github.com/musicinmybrain gitworkflows: login: gitworkflows count: 3 @@ -468,11 +478,6 @@ yezz123: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=d7062cbc6eb7671d5dc9cc0e32a24ae335e0f225&v=4 url: https://github.com/yezz123 -musicinmybrain: - login: musicinmybrain - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/6898909?u=9010312053e7141383b9bdf538036c7f37fbaba0&v=4 - url: https://github.com/musicinmybrain softwarebloat: login: softwarebloat count: 2 @@ -518,3 +523,8 @@ DanielKusyDev: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/36250676?u=2ea6114ff751fc48b55f231987a0e2582c6b1bd2&v=4 url: https://github.com/DanielKusyDev +DanielYang59: + login: DanielYang59 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/80093591?u=63873f701c7c74aac83c906800a1dddc0bc8c92f&v=4 + url: https://github.com/DanielYang59 diff --git a/docs/en/data/translation_reviewers.yml b/docs/en/data/translation_reviewers.yml index 6f16893ba..1a3c12988 100644 --- a/docs/en/data/translation_reviewers.yml +++ b/docs/en/data/translation_reviewers.yml @@ -10,9 +10,14 @@ Xewus: url: https://github.com/Xewus ceb10n: login: ceb10n - count: 110 + count: 112 avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 url: https://github.com/ceb10n +sodaMelon: + login: sodaMelon + count: 111 + avatarUrl: https://avatars.githubusercontent.com/u/66295123?u=be939db90f1119efee9e6110cc05066ff1f40f00&v=4 + url: https://github.com/sodaMelon tokusumi: login: tokusumi count: 104 @@ -28,31 +33,26 @@ hard-coders: count: 92 avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 url: https://github.com/hard-coders +nazarepiedady: + login: nazarepiedady + count: 83 + avatarUrl: https://avatars.githubusercontent.com/u/31008635?u=8dc25777dc9cb51fb0dbba2f137988953d330b78&v=4 + url: https://github.com/nazarepiedady AlertRED: login: AlertRED count: 81 avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 url: https://github.com/AlertRED -nazarepiedady: - login: nazarepiedady - count: 81 - avatarUrl: https://avatars.githubusercontent.com/u/31008635?u=8dc25777dc9cb51fb0dbba2f137988953d330b78&v=4 - url: https://github.com/nazarepiedady -sodaMelon: - login: sodaMelon +alv2017: + login: alv2017 count: 81 - avatarUrl: https://avatars.githubusercontent.com/u/66295123?u=be939db90f1119efee9e6110cc05066ff1f40f00&v=4 - url: https://github.com/sodaMelon + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 Alexandrhub: login: Alexandrhub count: 68 avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 url: https://github.com/Alexandrhub -alv2017: - login: alv2017 - count: 64 - avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 - url: https://github.com/alv2017 waynerv: login: waynerv count: 63 @@ -68,6 +68,11 @@ mattwang44: count: 58 avatarUrl: https://avatars.githubusercontent.com/u/24987826?u=58e37fb3927b9124b458945ac4c97aa0f1062d85&v=4 url: https://github.com/mattwang44 +tiangolo: + login: tiangolo + count: 51 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo Laineyzhang55: login: Laineyzhang55 count: 48 @@ -88,11 +93,11 @@ alperiox: count: 42 avatarUrl: https://avatars.githubusercontent.com/u/34214152?u=2c5acad3461d4dbc2d48371ba86cac56ae9b25cc&v=4 url: https://github.com/alperiox -tiangolo: - login: tiangolo - count: 40 - avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 - url: https://github.com/tiangolo +rostik1410: + login: rostik1410 + count: 41 + avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4 + url: https://github.com/rostik1410 Winand: login: Winand count: 40 @@ -118,11 +123,31 @@ SwftAlpc: count: 36 avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 url: https://github.com/SwftAlpc +alejsdev: + login: alejsdev + count: 36 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 + url: https://github.com/alejsdev +timothy-jeong: + login: timothy-jeong + count: 36 + avatarUrl: https://avatars.githubusercontent.com/u/53824764?u=db3d0cea2f5fab64d810113c5039a369699a2774&v=4 + url: https://github.com/timothy-jeong nilslindemann: login: nilslindemann count: 35 avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 url: https://github.com/nilslindemann +svlandeg: + login: svlandeg + count: 35 + avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 + url: https://github.com/svlandeg +Rishat-F: + login: Rishat-F + count: 35 + avatarUrl: https://avatars.githubusercontent.com/u/66554797?v=4 + url: https://github.com/Rishat-F rjNemo: login: rjNemo count: 34 @@ -143,11 +168,6 @@ romashevchenko: count: 32 avatarUrl: https://avatars.githubusercontent.com/u/132477732?v=4 url: https://github.com/romashevchenko -alejsdev: - login: alejsdev - count: 32 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 - url: https://github.com/alejsdev wdh99: login: wdh99 count: 31 @@ -208,6 +228,11 @@ junah201: count: 26 avatarUrl: https://avatars.githubusercontent.com/u/75025529?u=2451c256e888fa2a06bcfc0646d09b87ddb6a945&v=4 url: https://github.com/junah201 +mezgoodle: + login: mezgoodle + count: 26 + avatarUrl: https://avatars.githubusercontent.com/u/41520940?u=e871bc26734eb2436d98c19c3fb57a4773e13c24&v=4 + url: https://github.com/mezgoodle Vincy1230: login: Vincy1230 count: 26 @@ -248,11 +273,6 @@ wisderfin: count: 23 avatarUrl: https://avatars.githubusercontent.com/u/77553770?u=f3b00a26736ba664e9927a1116c6e8088295e073&v=4 url: https://github.com/wisderfin -rostik1410: - login: rostik1410 - count: 22 - avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4 - url: https://github.com/rostik1410 AGolicyn: login: AGolicyn count: 21 @@ -266,7 +286,7 @@ Attsun1031: ycd: login: ycd count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=f1e7bae394a315da950912c92dc861a8eaf95d4c&v=4 url: https://github.com/ycd delhi09: login: delhi09 @@ -283,26 +303,21 @@ DevDae: count: 20 avatarUrl: https://avatars.githubusercontent.com/u/87962045?u=08e10fa516e844934f4b3fc7c38b33c61697e4a1&v=4 url: https://github.com/DevDae -svlandeg: - login: svlandeg - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 - url: https://github.com/svlandeg sattosan: login: sattosan count: 19 avatarUrl: https://avatars.githubusercontent.com/u/20574756?u=b0d8474d2938189c6954423ae8d81d91013f80a8&v=4 url: https://github.com/sattosan +yes0ng: + login: yes0ng + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/25501794?u=3aed18b0d491e0220a167a1e9e58bea3638c6707&v=4 + url: https://github.com/yes0ng ComicShrimp: login: ComicShrimp count: 18 avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=d2fbf412e7730183ce91686ca48d4147e1b7dc74&v=4 url: https://github.com/ComicShrimp -mezgoodle: - login: mezgoodle - count: 18 - avatarUrl: https://avatars.githubusercontent.com/u/41520940?u=e871bc26734eb2436d98c19c3fb57a4773e13c24&v=4 - url: https://github.com/mezgoodle simatheone: login: simatheone count: 18 @@ -473,11 +488,6 @@ kwang1215: count: 12 avatarUrl: https://avatars.githubusercontent.com/u/74170199?u=2a63ff6692119dde3f5e5693365b9fcd6f977b08&v=4 url: https://github.com/kwang1215 -Rishat-F: - login: Rishat-F - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/66554797?v=4 - url: https://github.com/Rishat-F AdrianDeAnda: login: AdrianDeAnda count: 11 @@ -498,6 +508,11 @@ glsglsgls: count: 11 avatarUrl: https://avatars.githubusercontent.com/u/76133879?v=4 url: https://github.com/glsglsgls +k94-ishi: + login: k94-ishi + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/32672580?u=bc7c5c07af0656be9fe4f1784a444af8d81ded89&v=4 + url: https://github.com/k94-ishi codespearhead: login: codespearhead count: 11 @@ -586,7 +601,7 @@ waketzheng: lucasbalieiro: login: lucasbalieiro count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/37416577?u=5a395a69384e7fa0f9840ea32ef963d3f1cd9da4&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/37416577?u=eabaf4aebbaa88a94a4886273edba689012cee70&v=4 url: https://github.com/lucasbalieiro RunningIkkyu: login: RunningIkkyu @@ -648,6 +663,11 @@ Zhongheng-Cheng: count: 9 avatarUrl: https://avatars.githubusercontent.com/u/95612344?u=a0f7730a3cc7486827965e01a119ad610bda4b0a&v=4 url: https://github.com/Zhongheng-Cheng +Yarous: + login: Yarous + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/61277193?u=5b462347458a373b2d599c6f416d2b75eddbffad&v=4 + url: https://github.com/Yarous dimaqq: login: dimaqq count: 8 @@ -683,11 +703,21 @@ KimJoonSeo: count: 8 avatarUrl: https://avatars.githubusercontent.com/u/17760162?u=a58cdc77ae1c069a64166f7ecc4d42eecfd9a468&v=4 url: https://github.com/KimJoonSeo +MinLee0210: + login: MinLee0210 + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/57653278?u=7def7c0654ad82f43b46d6dfc3b51c4d2be15011&v=4 + url: https://github.com/MinLee0210 camigomezdev: login: camigomezdev count: 8 avatarUrl: https://avatars.githubusercontent.com/u/16061815?u=25b5ebc042fff53fa03dc107ded10e36b1b7a5b9&v=4 url: https://github.com/camigomezdev +maru0123-2004: + login: maru0123-2004 + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/43961566?u=16ed8603a4d6a4665cb6c53a7aece6f31379b769&v=4 + url: https://github.com/maru0123-2004 Serrones: login: Serrones count: 7 @@ -843,6 +873,16 @@ bankofsardine: count: 6 avatarUrl: https://avatars.githubusercontent.com/u/44944207?u=0368e1b698ffab6bf29e202f9fd2dddd352429f1&v=4 url: https://github.com/bankofsardine +SofiiaTrufanova: + login: SofiiaTrufanova + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/63260929?v=4 + url: https://github.com/SofiiaTrufanova +DianaTrufanova: + login: DianaTrufanova + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/119067607?v=4 + url: https://github.com/DianaTrufanova rsip22: login: rsip22 count: 5 @@ -856,7 +896,7 @@ jessicapaz: mohsen-mahmoodi: login: mohsen-mahmoodi count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/2872586?u=9274b3b13d8a992dba29b162fee48473a0fa142d&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/2872586?u=3a9fc1aa16a3a0ab93a1f8550de82a940592857d&v=4 url: https://github.com/mohsen-mahmoodi jeesang7: login: jeesang7 @@ -958,11 +998,11 @@ devluisrodrigues: count: 5 avatarUrl: https://avatars.githubusercontent.com/u/103431660?u=d9674a3249edc4601d2c712cdebf899918503c3a&v=4 url: https://github.com/devluisrodrigues -timothy-jeong: - login: timothy-jeong +11kkw: + login: 11kkw count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/53824764?u=db3d0cea2f5fab64d810113c5039a369699a2774&v=4 - url: https://github.com/timothy-jeong + avatarUrl: https://avatars.githubusercontent.com/u/21125286?v=4 + url: https://github.com/11kkw lpdswing: login: lpdswing count: 4 @@ -976,7 +1016,7 @@ SepehrRasouli: Zxilly: login: Zxilly count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/31370133?u=122e23d6e974614736be606e4ea816f45e7745f8&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/31370133?u=c5359b8d9d80a7cdc23d5295d179ed90174996c8&v=4 url: https://github.com/Zxilly eavv: login: eavv @@ -1016,7 +1056,7 @@ personage-hub: aminalaee: login: aminalaee count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/19784933?u=2f45a312b73e7fb29f3b6f8676e5be6f7220da25&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/19784933?v=4 url: https://github.com/aminalaee erfan-rfmhr: login: erfan-rfmhr @@ -1058,11 +1098,11 @@ matiasbertani: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/65260383?u=d5edd86a6e2ab4fb1aab7751931fe045a963afd7&v=4 url: https://github.com/matiasbertani -k94-ishi: - login: k94-ishi +thiennc254: + login: thiennc254 count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/32672580?u=bc7c5c07af0656be9fe4f1784a444af8d81ded89&v=4 - url: https://github.com/k94-ishi + avatarUrl: https://avatars.githubusercontent.com/u/97406628?u=1b2860679694b9a552764d0fa81dbd7a016322ec&v=4 + url: https://github.com/thiennc254 javillegasna: login: javillegasna count: 4 @@ -1078,11 +1118,16 @@ ilhamfadillah: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/20577838?u=c56192cf99b55affcaad408b240259c62e633450&v=4 url: https://github.com/ilhamfadillah -Yarous: - login: Yarous +gerry-sabar: + login: gerry-sabar count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/61277193?u=5b462347458a373b2d599c6f416d2b75eddbffad&v=4 - url: https://github.com/Yarous + avatarUrl: https://avatars.githubusercontent.com/u/1120123?v=4 + url: https://github.com/gerry-sabar +valentinDruzhinin: + login: valentinDruzhinin + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/12831905?u=aae1ebc675c91e8fa582df4fcc4fc4128106344d&v=4 + url: https://github.com/valentinDruzhinin tyronedamasceno: login: tyronedamasceno count: 3 @@ -1308,11 +1353,16 @@ RyaWcksn: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/42831964?u=0cb4265faf3e3425a89e59b6fddd3eb2de180af0&v=4 url: https://github.com/RyaWcksn -gerry-sabar: - login: gerry-sabar +Zerohertz: + login: Zerohertz count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/1120123?v=4 - url: https://github.com/gerry-sabar + avatarUrl: https://avatars.githubusercontent.com/u/42334717?u=c6acda352c866b1747921e0ff8782b58571d849e&v=4 + url: https://github.com/Zerohertz +tienduong-21: + login: tienduong-21 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/80129618?v=4 + url: https://github.com/tienduong-21 blaisep: login: blaisep count: 2 @@ -1471,7 +1521,7 @@ felipebpl: iudeen: login: iudeen count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=f09cdd745e5bf16138f29b42732dd57c7f02bee1&v=4 url: https://github.com/iudeen dwisulfahnur: login: dwisulfahnur @@ -1623,6 +1673,16 @@ UN-9BOT: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/111110804?u=39e158937ed795972c2d0400fc521c50e9bfb9e7&v=4 url: https://github.com/UN-9BOT +flasonme: + login: flasonme + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/30571019?v=4 + url: https://github.com/flasonme +ptt3199: + login: ptt3199 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/51350651?u=ccf51f8820787e17983954f26b06acf226cba293&v=4 + url: https://github.com/ptt3199 gustavoprezoto: login: gustavoprezoto count: 2 @@ -1668,3 +1728,8 @@ kiharito: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/38311245?v=4 url: https://github.com/kiharito +J-Fuji: + login: J-Fuji + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/101452903?v=4 + url: https://github.com/J-Fuji diff --git a/docs/en/data/translators.yml b/docs/en/data/translators.yml index 13859044d..9874afa56 100644 --- a/docs/en/data/translators.yml +++ b/docs/en/data/translators.yml @@ -10,7 +10,7 @@ jaystone776: url: https://github.com/jaystone776 ceb10n: login: ceb10n - count: 26 + count: 27 avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 url: https://github.com/ceb10n tokusumi: @@ -43,21 +43,26 @@ hard-coders: count: 15 avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 url: https://github.com/hard-coders +Joao-Pedro-P-Holanda: + login: Joao-Pedro-P-Holanda + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/110267046?u=331bd016326dac4cf3df4848f6db2dbbf8b5f978&v=4 + url: https://github.com/Joao-Pedro-P-Holanda codingjenny: login: codingjenny count: 14 avatarUrl: https://avatars.githubusercontent.com/u/103817302?u=3a042740dc0ff58615da0d8679230966fd7693e8&v=4 url: https://github.com/codingjenny +valentinDruzhinin: + login: valentinDruzhinin + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/12831905?u=aae1ebc675c91e8fa582df4fcc4fc4128106344d&v=4 + url: https://github.com/valentinDruzhinin Xewus: login: Xewus count: 13 avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 url: https://github.com/Xewus -Joao-Pedro-P-Holanda: - login: Joao-Pedro-P-Holanda - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/110267046?u=331bd016326dac4cf3df4848f6db2dbbf8b5f978&v=4 - url: https://github.com/Joao-Pedro-P-Holanda Smlep: login: Smlep count: 11 @@ -106,13 +111,18 @@ batlopes: lucasbalieiro: login: lucasbalieiro count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/37416577?u=5a395a69384e7fa0f9840ea32ef963d3f1cd9da4&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/37416577?u=eabaf4aebbaa88a94a4886273edba689012cee70&v=4 url: https://github.com/lucasbalieiro Alexandrhub: login: Alexandrhub count: 6 avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 url: https://github.com/Alexandrhub +ptt3199: + login: ptt3199 + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/51350651?u=ccf51f8820787e17983954f26b06acf226cba293&v=4 + url: https://github.com/ptt3199 Serrones: login: Serrones count: 5 @@ -143,6 +153,11 @@ rostik1410: count: 5 avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4 url: https://github.com/rostik1410 +alv2017: + login: alv2017 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 komtaki: login: komtaki count: 4 @@ -188,11 +203,6 @@ kwang1215: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/74170199?u=2a63ff6692119dde3f5e5693365b9fcd6f977b08&v=4 url: https://github.com/kwang1215 -alv2017: - login: alv2017 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 - url: https://github.com/alv2017 jfunez: login: jfunez count: 3 @@ -201,7 +211,7 @@ jfunez: ycd: login: ycd count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=f1e7bae394a315da950912c92dc861a8eaf95d4c&v=4 url: https://github.com/ycd mariacamilagl: login: mariacamilagl @@ -323,6 +333,16 @@ gerry-sabar: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/1120123?v=4 url: https://github.com/gerry-sabar +k94-ishi: + login: k94-ishi + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/32672580?u=bc7c5c07af0656be9fe4f1784a444af8d81ded89&v=4 + url: https://github.com/k94-ishi +Rishat-F: + login: Rishat-F + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/66554797?v=4 + url: https://github.com/Rishat-F izaguerreiro: login: izaguerreiro count: 2 @@ -451,7 +471,7 @@ choi-haram: imtiaz101325: login: imtiaz101325 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/54007087?u=7a210ee38a0a30b7536226419b3b799620ad57d9&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/54007087?u=194d972b501b9ea9d2ddeaed757c492936e0121a&v=4 url: https://github.com/imtiaz101325 waketzheng: login: waketzheng @@ -488,8 +508,8 @@ timothy-jeong: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/53824764?u=db3d0cea2f5fab64d810113c5039a369699a2774&v=4 url: https://github.com/timothy-jeong -Rishat-F: - login: Rishat-F +11kkw: + login: 11kkw count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/66554797?v=4 - url: https://github.com/Rishat-F + avatarUrl: https://avatars.githubusercontent.com/u/21125286?v=4 + url: https://github.com/11kkw From ea57612d69290be8298369d9f1542d6afeea459e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 1 Mar 2025 18:19:34 +0100 Subject: [PATCH 884/932] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20GitHu?= =?UTF-8?q?b=20topic=20repositories=20(#13439)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions --- docs/en/data/topic_repos.yml | 336 +++++++++++++++++------------------ 1 file changed, 168 insertions(+), 168 deletions(-) diff --git a/docs/en/data/topic_repos.yml b/docs/en/data/topic_repos.yml index 302dc3bb5..633b0aee3 100644 --- a/docs/en/data/topic_repos.yml +++ b/docs/en/data/topic_repos.yml @@ -1,86 +1,86 @@ - name: full-stack-fastapi-template html_url: https://github.com/fastapi/full-stack-fastapi-template - stars: 29409 + stars: 30645 owner_login: fastapi owner_html_url: https://github.com/fastapi - name: Hello-Python html_url: https://github.com/mouredev/Hello-Python - stars: 28113 + stars: 28690 owner_login: mouredev owner_html_url: https://github.com/mouredev - name: serve html_url: https://github.com/jina-ai/serve - stars: 21264 + stars: 21356 owner_login: jina-ai owner_html_url: https://github.com/jina-ai - name: sqlmodel html_url: https://github.com/fastapi/sqlmodel - stars: 15109 + stars: 15312 owner_login: fastapi owner_html_url: https://github.com/fastapi - name: HivisionIDPhotos html_url: https://github.com/Zeyi-Lin/HivisionIDPhotos - stars: 14564 + stars: 14957 owner_login: Zeyi-Lin owner_html_url: https://github.com/Zeyi-Lin - name: Douyin_TikTok_Download_API html_url: https://github.com/Evil0ctal/Douyin_TikTok_Download_API - stars: 10701 + stars: 11192 owner_login: Evil0ctal owner_html_url: https://github.com/Evil0ctal - name: fastapi-best-practices html_url: https://github.com/zhanymkanov/fastapi-best-practices - stars: 10180 + stars: 10501 owner_login: zhanymkanov owner_html_url: https://github.com/zhanymkanov - name: awesome-fastapi html_url: https://github.com/mjhea0/awesome-fastapi - stars: 9061 + stars: 9193 owner_login: mjhea0 owner_html_url: https://github.com/mjhea0 - name: FastUI html_url: https://github.com/pydantic/FastUI - stars: 8644 + stars: 8721 owner_login: pydantic owner_html_url: https://github.com/pydantic - name: nonebot2 html_url: https://github.com/nonebot/nonebot2 - stars: 6312 + stars: 6433 owner_login: nonebot owner_html_url: https://github.com/nonebot - name: serge html_url: https://github.com/serge-chat/serge - stars: 5686 + stars: 5699 owner_login: serge-chat owner_html_url: https://github.com/serge-chat - name: FileCodeBox html_url: https://github.com/vastsa/FileCodeBox - stars: 4933 + stars: 5534 owner_login: vastsa owner_html_url: https://github.com/vastsa - name: fastapi-users html_url: https://github.com/fastapi-users/fastapi-users - stars: 4849 + stars: 4921 owner_login: fastapi-users owner_html_url: https://github.com/fastapi-users +- name: polar + html_url: https://github.com/polarsource/polar + stars: 4598 + owner_login: polarsource + owner_html_url: https://github.com/polarsource - name: hatchet html_url: https://github.com/hatchet-dev/hatchet - stars: 4514 + stars: 4585 owner_login: hatchet-dev owner_html_url: https://github.com/hatchet-dev - name: chatgpt-web-share html_url: https://github.com/chatpire/chatgpt-web-share - stars: 4319 + stars: 4318 owner_login: chatpire owner_html_url: https://github.com/chatpire -- name: polar - html_url: https://github.com/polarsource/polar - stars: 4216 - owner_login: polarsource - owner_html_url: https://github.com/polarsource - name: strawberry html_url: https://github.com/strawberry-graphql/strawberry - stars: 4126 + stars: 4180 owner_login: strawberry-graphql owner_html_url: https://github.com/strawberry-graphql - name: atrilabs-engine @@ -90,279 +90,284 @@ owner_html_url: https://github.com/Atri-Labs - name: dynaconf html_url: https://github.com/dynaconf/dynaconf - stars: 3874 + stars: 3904 owner_login: dynaconf owner_html_url: https://github.com/dynaconf - name: poem html_url: https://github.com/poem-web/poem - stars: 3746 + stars: 3781 owner_login: poem-web owner_html_url: https://github.com/poem-web -- name: opyrator - html_url: https://github.com/ml-tooling/opyrator - stars: 3117 - owner_login: ml-tooling - owner_html_url: https://github.com/ml-tooling - name: farfalle html_url: https://github.com/rashadphz/farfalle - stars: 3094 + stars: 3190 owner_login: rashadphz owner_html_url: https://github.com/rashadphz +- name: opyrator + html_url: https://github.com/ml-tooling/opyrator + stars: 3119 + owner_login: ml-tooling + owner_html_url: https://github.com/ml-tooling - name: fastapi-admin html_url: https://github.com/fastapi-admin/fastapi-admin - stars: 3040 + stars: 3086 owner_login: fastapi-admin owner_html_url: https://github.com/fastapi-admin - name: docarray html_url: https://github.com/docarray/docarray - stars: 3007 + stars: 3021 owner_login: docarray owner_html_url: https://github.com/docarray - name: datamodel-code-generator html_url: https://github.com/koxudaxi/datamodel-code-generator - stars: 2914 + stars: 2988 owner_login: koxudaxi owner_html_url: https://github.com/koxudaxi -- name: fastapi-realworld-example-app - html_url: https://github.com/nsidnev/fastapi-realworld-example-app - stars: 2840 - owner_login: nsidnev - owner_html_url: https://github.com/nsidnev - name: LitServe html_url: https://github.com/Lightning-AI/LitServe - stars: 2804 + stars: 2863 owner_login: Lightning-AI owner_html_url: https://github.com/Lightning-AI -- name: uvicorn-gunicorn-fastapi-docker - html_url: https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker - stars: 2730 - owner_login: tiangolo - owner_html_url: https://github.com/tiangolo +- name: fastapi-realworld-example-app + html_url: https://github.com/nsidnev/fastapi-realworld-example-app + stars: 2850 + owner_login: nsidnev + owner_html_url: https://github.com/nsidnev - name: logfire html_url: https://github.com/pydantic/logfire - stars: 2620 + stars: 2757 owner_login: pydantic owner_html_url: https://github.com/pydantic +- name: uvicorn-gunicorn-fastapi-docker + html_url: https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker + stars: 2731 + owner_login: tiangolo + owner_html_url: https://github.com/tiangolo - name: huma html_url: https://github.com/danielgtaylor/huma - stars: 2567 + stars: 2700 owner_login: danielgtaylor owner_html_url: https://github.com/danielgtaylor - name: tracecat html_url: https://github.com/TracecatHQ/tracecat - stars: 2494 + stars: 2539 owner_login: TracecatHQ owner_html_url: https://github.com/TracecatHQ - name: best-of-web-python html_url: https://github.com/ml-tooling/best-of-web-python - stars: 2433 + stars: 2460 owner_login: ml-tooling owner_html_url: https://github.com/ml-tooling - name: RasaGPT html_url: https://github.com/paulpierre/RasaGPT - stars: 2386 + stars: 2401 owner_login: paulpierre owner_html_url: https://github.com/paulpierre - name: fastapi-react html_url: https://github.com/Buuntu/fastapi-react - stars: 2293 + stars: 2315 owner_login: Buuntu owner_html_url: https://github.com/Buuntu - name: nextpy html_url: https://github.com/dot-agent/nextpy - stars: 2256 + stars: 2266 owner_login: dot-agent owner_html_url: https://github.com/dot-agent - name: 30-Days-of-Python html_url: https://github.com/codingforentrepreneurs/30-Days-of-Python - stars: 2155 + stars: 2163 owner_login: codingforentrepreneurs owner_html_url: https://github.com/codingforentrepreneurs - name: FastAPI-template html_url: https://github.com/s3rius/FastAPI-template - stars: 2121 + stars: 2156 owner_login: s3rius owner_html_url: https://github.com/s3rius - name: sqladmin html_url: https://github.com/aminalaee/sqladmin - stars: 2021 + stars: 2051 owner_login: aminalaee owner_html_url: https://github.com/aminalaee - name: langserve html_url: https://github.com/langchain-ai/langserve - stars: 2006 + stars: 2025 owner_login: langchain-ai owner_html_url: https://github.com/langchain-ai - name: fastapi-utils html_url: https://github.com/fastapiutils/fastapi-utils - stars: 2002 + stars: 2021 owner_login: fastapiutils owner_html_url: https://github.com/fastapiutils - name: solara html_url: https://github.com/widgetti/solara - stars: 1967 + stars: 1980 owner_login: widgetti owner_html_url: https://github.com/widgetti - name: supabase-py html_url: https://github.com/supabase/supabase-py - stars: 1848 + stars: 1874 owner_login: supabase owner_html_url: https://github.com/supabase - name: python-week-2022 html_url: https://github.com/rochacbruno/python-week-2022 - stars: 1832 + stars: 1829 owner_login: rochacbruno owner_html_url: https://github.com/rochacbruno - name: mangum html_url: https://github.com/Kludex/mangum - stars: 1789 + stars: 1820 owner_login: Kludex owner_html_url: https://github.com/Kludex +- name: Kokoro-FastAPI + html_url: https://github.com/remsky/Kokoro-FastAPI + stars: 1771 + owner_login: remsky + owner_html_url: https://github.com/remsky - name: manage-fastapi html_url: https://github.com/ycd/manage-fastapi - stars: 1711 + stars: 1719 owner_login: ycd owner_html_url: https://github.com/ycd - name: ormar html_url: https://github.com/collerek/ormar - stars: 1701 + stars: 1710 owner_login: collerek owner_html_url: https://github.com/collerek - name: agentkit html_url: https://github.com/BCG-X-Official/agentkit - stars: 1630 + stars: 1658 owner_login: BCG-X-Official owner_html_url: https://github.com/BCG-X-Official - name: langchain-serve html_url: https://github.com/jina-ai/langchain-serve - stars: 1617 + stars: 1618 owner_login: jina-ai owner_html_url: https://github.com/jina-ai - name: termpair html_url: https://github.com/cs01/termpair - stars: 1612 + stars: 1611 owner_login: cs01 owner_html_url: https://github.com/cs01 - name: coronavirus-tracker-api html_url: https://github.com/ExpDev07/coronavirus-tracker-api - stars: 1590 + stars: 1588 owner_login: ExpDev07 owner_html_url: https://github.com/ExpDev07 - name: piccolo html_url: https://github.com/piccolo-orm/piccolo - stars: 1519 + stars: 1546 owner_login: piccolo-orm owner_html_url: https://github.com/piccolo-orm -- name: fastapi-crudrouter - html_url: https://github.com/awtkns/fastapi-crudrouter - stars: 1449 - owner_login: awtkns - owner_html_url: https://github.com/awtkns - name: fastapi-cache html_url: https://github.com/long2ice/fastapi-cache - stars: 1447 + stars: 1478 owner_login: long2ice owner_html_url: https://github.com/long2ice - name: openapi-python-client html_url: https://github.com/openapi-generators/openapi-python-client - stars: 1434 + stars: 1467 owner_login: openapi-generators owner_html_url: https://github.com/openapi-generators +- name: fastapi-crudrouter + html_url: https://github.com/awtkns/fastapi-crudrouter + stars: 1462 + owner_login: awtkns + owner_html_url: https://github.com/awtkns - name: awesome-fastapi-projects html_url: https://github.com/Kludex/awesome-fastapi-projects - stars: 1398 + stars: 1418 owner_login: Kludex owner_html_url: https://github.com/Kludex - name: awesome-python-resources html_url: https://github.com/DjangoEx/awesome-python-resources - stars: 1380 + stars: 1383 owner_login: DjangoEx owner_html_url: https://github.com/DjangoEx +- name: slowapi + html_url: https://github.com/laurentS/slowapi + stars: 1363 + owner_login: laurentS + owner_html_url: https://github.com/laurentS - name: budgetml html_url: https://github.com/ebhy/budgetml stars: 1344 owner_login: ebhy owner_html_url: https://github.com/ebhy -- name: slowapi - html_url: https://github.com/laurentS/slowapi - stars: 1339 - owner_login: laurentS - owner_html_url: https://github.com/laurentS - name: fastapi-pagination html_url: https://github.com/uriyyo/fastapi-pagination - stars: 1263 + stars: 1284 owner_login: uriyyo owner_html_url: https://github.com/uriyyo - name: fastapi-boilerplate html_url: https://github.com/teamhide/fastapi-boilerplate - stars: 1206 + stars: 1234 owner_login: teamhide owner_html_url: https://github.com/teamhide - name: fastapi-tutorial html_url: https://github.com/liaogx/fastapi-tutorial - stars: 1178 + stars: 1181 owner_login: liaogx owner_html_url: https://github.com/liaogx - name: fastapi-amis-admin html_url: https://github.com/amisadmin/fastapi-amis-admin - stars: 1142 + stars: 1164 owner_login: amisadmin owner_html_url: https://github.com/amisadmin - name: fastapi-code-generator html_url: https://github.com/koxudaxi/fastapi-code-generator - stars: 1119 + stars: 1132 owner_login: koxudaxi owner_html_url: https://github.com/koxudaxi - name: bolt-python html_url: https://github.com/slackapi/bolt-python - stars: 1116 + stars: 1130 owner_login: slackapi owner_html_url: https://github.com/slackapi -- name: odmantic - html_url: https://github.com/art049/odmantic - stars: 1096 - owner_login: art049 - owner_html_url: https://github.com/art049 - name: langchain-extract html_url: https://github.com/langchain-ai/langchain-extract - stars: 1093 + stars: 1110 owner_login: langchain-ai owner_html_url: https://github.com/langchain-ai +- name: odmantic + html_url: https://github.com/art049/odmantic + stars: 1104 + owner_login: art049 + owner_html_url: https://github.com/art049 - name: fastapi_production_template html_url: https://github.com/zhanymkanov/fastapi_production_template - stars: 1078 + stars: 1093 owner_login: zhanymkanov owner_html_url: https://github.com/zhanymkanov +- name: SurfSense + html_url: https://github.com/MODSetter/SurfSense + stars: 1081 + owner_login: MODSetter + owner_html_url: https://github.com/MODSetter - name: fastapi-alembic-sqlmodel-async html_url: https://github.com/jonra1993/fastapi-alembic-sqlmodel-async - stars: 1055 + stars: 1063 owner_login: jonra1993 owner_html_url: https://github.com/jonra1993 -- name: Kokoro-FastAPI - html_url: https://github.com/remsky/Kokoro-FastAPI - stars: 1047 - owner_login: remsky - owner_html_url: https://github.com/remsky - name: prometheus-fastapi-instrumentator html_url: https://github.com/trallnag/prometheus-fastapi-instrumentator - stars: 1036 + stars: 1059 owner_login: trallnag owner_html_url: https://github.com/trallnag -- name: SurfSense - html_url: https://github.com/MODSetter/SurfSense - stars: 1018 - owner_login: MODSetter - owner_html_url: https://github.com/MODSetter - name: bedrock-claude-chat html_url: https://github.com/aws-samples/bedrock-claude-chat - stars: 1010 + stars: 1039 owner_login: aws-samples owner_html_url: https://github.com/aws-samples - name: runhouse html_url: https://github.com/run-house/runhouse - stars: 1000 + stars: 1005 owner_login: run-house owner_html_url: https://github.com/run-house +- name: vue-fastapi-admin + html_url: https://github.com/mizhexiaoxiao/vue-fastapi-admin + stars: 987 + owner_login: mizhexiaoxiao + owner_html_url: https://github.com/mizhexiaoxiao - name: lanarky html_url: https://github.com/ajndkr/lanarky stars: 986 @@ -370,126 +375,121 @@ owner_html_url: https://github.com/ajndkr - name: autollm html_url: https://github.com/viddexa/autollm - stars: 982 + stars: 986 owner_login: viddexa owner_html_url: https://github.com/viddexa - name: restish html_url: https://github.com/danielgtaylor/restish - stars: 970 + stars: 984 owner_login: danielgtaylor owner_html_url: https://github.com/danielgtaylor - name: fastcrud html_url: https://github.com/igorbenav/fastcrud - stars: 929 + stars: 964 owner_login: igorbenav owner_html_url: https://github.com/igorbenav - name: secure html_url: https://github.com/TypeError/secure - stars: 921 + stars: 928 owner_login: TypeError owner_html_url: https://github.com/TypeError - name: langcorn html_url: https://github.com/msoedov/langcorn - stars: 915 + stars: 916 owner_login: msoedov owner_html_url: https://github.com/msoedov -- name: vue-fastapi-admin - html_url: https://github.com/mizhexiaoxiao/vue-fastapi-admin - stars: 915 - owner_login: mizhexiaoxiao - owner_html_url: https://github.com/mizhexiaoxiao - name: energy-forecasting html_url: https://github.com/iusztinpaul/energy-forecasting - stars: 891 + stars: 898 owner_login: iusztinpaul owner_html_url: https://github.com/iusztinpaul - name: authx html_url: https://github.com/yezz123/authx - stars: 862 + stars: 874 owner_login: yezz123 owner_html_url: https://github.com/yezz123 - name: titiler html_url: https://github.com/developmentseed/titiler - stars: 823 + stars: 841 owner_login: developmentseed owner_html_url: https://github.com/developmentseed -- name: marker-api - html_url: https://github.com/adithya-s-k/marker-api - stars: 798 - owner_login: adithya-s-k - owner_html_url: https://github.com/adithya-s-k - name: FastAPI-boilerplate html_url: https://github.com/igorbenav/FastAPI-boilerplate - stars: 774 + stars: 820 owner_login: igorbenav owner_html_url: https://github.com/igorbenav +- name: marker-api + html_url: https://github.com/adithya-s-k/marker-api + stars: 813 + owner_login: adithya-s-k + owner_html_url: https://github.com/adithya-s-k - name: fastapi_best_architecture html_url: https://github.com/fastapi-practices/fastapi_best_architecture - stars: 766 + stars: 802 owner_login: fastapi-practices owner_html_url: https://github.com/fastapi-practices -- name: fastapi-mail - html_url: https://github.com/sabuhish/fastapi-mail - stars: 735 - owner_login: sabuhish - owner_html_url: https://github.com/sabuhish -- name: annotated-py-projects - html_url: https://github.com/hhstore/annotated-py-projects - stars: 725 - owner_login: hhstore - owner_html_url: https://github.com/hhstore - name: fastapi-do-zero html_url: https://github.com/dunossauro/fastapi-do-zero - stars: 723 + stars: 745 owner_login: dunossauro owner_html_url: https://github.com/dunossauro -- name: lccn_predictor - html_url: https://github.com/baoliay2008/lccn_predictor - stars: 718 - owner_login: baoliay2008 - owner_html_url: https://github.com/baoliay2008 +- name: fastapi-mail + html_url: https://github.com/sabuhish/fastapi-mail + stars: 744 + owner_login: sabuhish + owner_html_url: https://github.com/sabuhish - name: fastapi-observability html_url: https://github.com/blueswen/fastapi-observability - stars: 718 + stars: 743 owner_login: blueswen owner_html_url: https://github.com/blueswen -- name: chatGPT-web - html_url: https://github.com/mic1on/chatGPT-web - stars: 708 - owner_login: mic1on - owner_html_url: https://github.com/mic1on +- name: lccn_predictor + html_url: https://github.com/baoliay2008/lccn_predictor + stars: 741 + owner_login: baoliay2008 + owner_html_url: https://github.com/baoliay2008 +- name: annotated-py-projects + html_url: https://github.com/hhstore/annotated-py-projects + stars: 727 + owner_login: hhstore + owner_html_url: https://github.com/hhstore - name: learn-generative-ai html_url: https://github.com/panaverse/learn-generative-ai - stars: 701 + stars: 714 owner_login: panaverse owner_html_url: https://github.com/panaverse -- name: linbing - html_url: https://github.com/taomujian/linbing - stars: 700 - owner_login: taomujian - owner_html_url: https://github.com/taomujian -- name: FastAPI-Backend-Template - html_url: https://github.com/Aeternalis-Ingenium/FastAPI-Backend-Template - stars: 692 - owner_login: Aeternalis-Ingenium - owner_html_url: https://github.com/Aeternalis-Ingenium - name: starlette-admin html_url: https://github.com/jowilf/starlette-admin - stars: 692 + stars: 713 owner_login: jowilf owner_html_url: https://github.com/jowilf +- name: chatGPT-web + html_url: https://github.com/mic1on/chatGPT-web + stars: 712 + owner_login: mic1on + owner_html_url: https://github.com/mic1on +- name: FastAPI-Backend-Template + html_url: https://github.com/Aeternalis-Ingenium/FastAPI-Backend-Template + stars: 709 + owner_login: Aeternalis-Ingenium + owner_html_url: https://github.com/Aeternalis-Ingenium +- name: linbing + html_url: https://github.com/taomujian/linbing + stars: 698 + owner_login: taomujian + owner_html_url: https://github.com/taomujian +- name: KonomiTV + html_url: https://github.com/tsukumijima/KonomiTV + stars: 687 + owner_login: tsukumijima + owner_html_url: https://github.com/tsukumijima - name: fastapi-jwt-auth html_url: https://github.com/IndominusByte/fastapi-jwt-auth - stars: 674 + stars: 685 owner_login: IndominusByte owner_html_url: https://github.com/IndominusByte - name: pity html_url: https://github.com/wuranxu/pity - stars: 663 + stars: 667 owner_login: wuranxu owner_html_url: https://github.com/wuranxu -- name: fastapi_login - html_url: https://github.com/MushroomMaula/fastapi_login - stars: 656 - owner_login: MushroomMaula - owner_html_url: https://github.com/MushroomMaula From b7d3f2a96ec2e3d548a1cbd8046dbfecdee38acf Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 1 Mar 2025 17:19:45 +0000 Subject: [PATCH 885/932] =?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 [skip ci] --- 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 f78994c5a..6ac228ba1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,10 @@ hide: * 🌐 Add Russian translation for `docs/ru/docs/tutorial/middleware.md`. PR [#13412](https://github.com/fastapi/fastapi/pull/13412) by [@alv2017](https://github.com/alv2017). +### Internal + +* 👥 Update FastAPI People - Sponsors. PR [#13433](https://github.com/fastapi/fastapi/pull/13433) by [@tiangolo](https://github.com/tiangolo). + ## 0.115.10 ### Fixes From 60f05868b786337cf00504fd5e5df2a46c6cd6d3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 1 Mar 2025 17:20:07 +0000 Subject: [PATCH 886/932] =?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 [skip ci] --- 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 6ac228ba1..37cb9aa56 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Internal +* 👥 Update FastAPI People - Contributors and Translators. PR [#13432](https://github.com/fastapi/fastapi/pull/13432) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI People - Sponsors. PR [#13433](https://github.com/fastapi/fastapi/pull/13433) by [@tiangolo](https://github.com/tiangolo). ## 0.115.10 From f5056f84b66344ee4fc0e15eff763cdb35381b5c Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 1 Mar 2025 17:21:19 +0000 Subject: [PATCH 887/932] =?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 [skip ci] --- 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 37cb9aa56..80075319d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Internal +* 👥 Update FastAPI GitHub topic repositories. PR [#13439](https://github.com/fastapi/fastapi/pull/13439) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI People - Contributors and Translators. PR [#13432](https://github.com/fastapi/fastapi/pull/13432) by [@tiangolo](https://github.com/tiangolo). * 👥 Update FastAPI People - Sponsors. PR [#13433](https://github.com/fastapi/fastapi/pull/13433) by [@tiangolo](https://github.com/tiangolo). From 74fe89bf35034aae531ca0a527c37d2f545161f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 1 Mar 2025 23:02:35 +0100 Subject: [PATCH 888/932] =?UTF-8?q?=F0=9F=90=9B=20Add=20docs=20examples=20?= =?UTF-8?q?and=20tests=20(support)=20for=20`Annotated`=20custom=20validati?= =?UTF-8?q?ons,=20like=20`AfterValidator`,=20revert=20#13440=20(#13442)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 15dd2b67d3f8763d5cd523b79a1c901c05d48bd7. --- .../tutorial/query-params-str-validations.md | 64 ++++++++ .../tutorial015_an.py | 31 ++++ .../tutorial015_an_py310.py | 30 ++++ .../tutorial015_an_py39.py | 30 ++++ fastapi/dependencies/utils.py | 8 +- tests/test_analyze_param.py | 22 --- .../test_tutorial015.py | 143 ++++++++++++++++++ 7 files changed, 302 insertions(+), 26 deletions(-) create mode 100644 docs_src/query_params_str_validations/tutorial015_an.py create mode 100644 docs_src/query_params_str_validations/tutorial015_an_py310.py create mode 100644 docs_src/query_params_str_validations/tutorial015_an_py39.py delete mode 100644 tests/test_analyze_param.py create mode 100644 tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index 511099186..e50fc347c 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -406,6 +406,68 @@ To exclude a query parameter from the generated OpenAPI schema (and thus, from t {* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *} +## Custom Validation + +There could be cases where you need to do some **custom validation** that can't be done with the parameters shown above. + +In those cases, you can use a **custom validator function** that is applied after the normal validation (e.g. after validating that the value is a `str`). + +You can achieve that using Pydantic's `AfterValidator` inside of `Annotated`. + +/// tip + +Pydantic also has `BeforeValidator` and others. 🤓 + +/// + +For example, this custom validator checks that the item ID starts with `isbn-` for an ISBN book number or with `imdb-` for an IMDB movie URL ID: + +{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *} + +/// info + +This is available with Pydantic version 2 or above. 😎 + +/// + +/// tip + +If you need to do any type of validation that requires communicating with any **external component**, like a database or another API, you should instead use **FastAPI Dependencies**, you will learn about them later. + +These custom validators are for things that can be checked with **only** the **same data** provided in the request. + +/// + +### Understand that Code + +The important point is just using **`AfterValidator` with a function inside `Annotated`**. Feel free to skip this part. 🤸 + +--- + +But if you're curious about this specific code example and you're still entertained, here are some extra details. + +#### String with `value.startswith()` + +Did you notice? a string using `value.startswith()` can take a tuple, and it will check each value in the tuple: + +{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *} + +#### A Random Item + +With `data.items()` we get an iterable object with tuples containing the key and value for each dictionary item. + +We convert this iterable object into a proper `list` with `list(data.items())`. + +Then with `random.choice()` we can get a **random value** from the list, so, we get a tuple with `(id, name)`. It will be something like `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")`. + +Then we **assign those two values** of the tuple to the variables `id` and `name`. + +So, if the user didn't provide an item ID, they will still receive a random suggestion. + +...we do all this in a **single simple line**. 🤯 Don't you love Python? 🐍 + +{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *} + ## Recap You can declare additional validations and metadata for your parameters. @@ -423,6 +485,8 @@ Validations specific for strings: * `max_length` * `pattern` +Custom validations using `AfterValidator`. + In these examples you saw how to declare validations for `str` values. See the next chapters to learn how to declare validations for other types, like numbers. diff --git a/docs_src/query_params_str_validations/tutorial015_an.py b/docs_src/query_params_str_validations/tutorial015_an.py new file mode 100644 index 000000000..f2ec6db12 --- /dev/null +++ b/docs_src/query_params_str_validations/tutorial015_an.py @@ -0,0 +1,31 @@ +import random +from typing import Union + +from fastapi import FastAPI +from pydantic import AfterValidator +from typing_extensions import Annotated + +app = FastAPI() + +data = { + "isbn-9781529046137": "The Hitchhiker's Guide to the Galaxy", + "imdb-tt0371724": "The Hitchhiker's Guide to the Galaxy", + "isbn-9781439512982": "Isaac Asimov: The Complete Stories, Vol. 2", +} + + +def check_valid_id(id: str): + if not id.startswith(("isbn-", "imdb-")): + raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"') + return id + + +@app.get("/items/") +async def read_items( + id: Annotated[Union[str, None], AfterValidator(check_valid_id)] = None, +): + if id: + item = data.get(id) + else: + id, item = random.choice(list(data.items())) + return {"id": id, "name": item} diff --git a/docs_src/query_params_str_validations/tutorial015_an_py310.py b/docs_src/query_params_str_validations/tutorial015_an_py310.py new file mode 100644 index 000000000..35f368094 --- /dev/null +++ b/docs_src/query_params_str_validations/tutorial015_an_py310.py @@ -0,0 +1,30 @@ +import random +from typing import Annotated + +from fastapi import FastAPI +from pydantic import AfterValidator + +app = FastAPI() + +data = { + "isbn-9781529046137": "The Hitchhiker's Guide to the Galaxy", + "imdb-tt0371724": "The Hitchhiker's Guide to the Galaxy", + "isbn-9781439512982": "Isaac Asimov: The Complete Stories, Vol. 2", +} + + +def check_valid_id(id: str): + if not id.startswith(("isbn-", "imdb-")): + raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"') + return id + + +@app.get("/items/") +async def read_items( + id: Annotated[str | None, AfterValidator(check_valid_id)] = None, +): + if id: + item = data.get(id) + else: + id, item = random.choice(list(data.items())) + return {"id": id, "name": item} diff --git a/docs_src/query_params_str_validations/tutorial015_an_py39.py b/docs_src/query_params_str_validations/tutorial015_an_py39.py new file mode 100644 index 000000000..989b6d2c2 --- /dev/null +++ b/docs_src/query_params_str_validations/tutorial015_an_py39.py @@ -0,0 +1,30 @@ +import random +from typing import Annotated, Union + +from fastapi import FastAPI +from pydantic import AfterValidator + +app = FastAPI() + +data = { + "isbn-9781529046137": "The Hitchhiker's Guide to the Galaxy", + "imdb-tt0371724": "The Hitchhiker's Guide to the Galaxy", + "isbn-9781439512982": "Isaac Asimov: The Complete Stories, Vol. 2", +} + + +def check_valid_id(id: str): + if not id.startswith(("isbn-", "imdb-")): + raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"') + return id + + +@app.get("/items/") +async def read_items( + id: Annotated[Union[str, None], AfterValidator(check_valid_id)] = None, +): + if id: + item = data.get(id) + else: + id, item = random.choice(list(data.items())) + return {"id": id, "name": item} diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 09dd6f1b9..e2866b488 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -449,15 +449,15 @@ def analyze_param( # We might check here that `default_value is RequiredParam`, but the fact is that the same # parameter might sometimes be a path parameter and sometimes not. See # `tests/test_infer_param_optionality.py` for an example. - field_info = params.Path(annotation=type_annotation) + field_info = params.Path(annotation=use_annotation) elif is_uploadfile_or_nonable_uploadfile_annotation( type_annotation ) or is_uploadfile_sequence_annotation(type_annotation): - field_info = params.File(annotation=type_annotation, default=default_value) + field_info = params.File(annotation=use_annotation, default=default_value) elif not field_annotation_is_scalar(annotation=type_annotation): - field_info = params.Body(annotation=type_annotation, default=default_value) + field_info = params.Body(annotation=use_annotation, default=default_value) else: - field_info = params.Query(annotation=type_annotation, default=default_value) + field_info = params.Query(annotation=use_annotation, default=default_value) field = None # It's a field_info, not a dependency diff --git a/tests/test_analyze_param.py b/tests/test_analyze_param.py deleted file mode 100644 index 9fd3fa6d0..000000000 --- a/tests/test_analyze_param.py +++ /dev/null @@ -1,22 +0,0 @@ -from inspect import signature - -from fastapi.dependencies.utils import ParamDetails, analyze_param -from pydantic import Field -from typing_extensions import Annotated - -from .utils import needs_pydanticv2 - - -def func(user: Annotated[int, Field(strict=True)]): ... - - -@needs_pydanticv2 -def test_analyze_param(): - result = analyze_param( - param_name="user", - annotation=signature(func).parameters["user"].annotation, - value=object(), - is_path_param=False, - ) - assert isinstance(result, ParamDetails) - assert result.field.field_info.annotation is int diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py new file mode 100644 index 000000000..ae1c40286 --- /dev/null +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py @@ -0,0 +1,143 @@ +import importlib + +import pytest +from dirty_equals import IsStr +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from ...utils import needs_py39, needs_py310, needs_pydanticv2 + + +@pytest.fixture( + name="client", + params=[ + pytest.param("tutorial015_an", marks=needs_pydanticv2), + pytest.param("tutorial015_an_py310", marks=(needs_py310, needs_pydanticv2)), + pytest.param("tutorial015_an_py39", marks=(needs_py39, needs_pydanticv2)), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.query_params_str_validations.{request.param}" + ) + + client = TestClient(mod.app) + return client + + +def test_get_random_item(client: TestClient): + response = client.get("/items") + assert response.status_code == 200, response.text + assert response.json() == {"id": IsStr(), "name": IsStr()} + + +def test_get_item(client: TestClient): + response = client.get("/items?id=isbn-9781529046137") + assert response.status_code == 200, response.text + assert response.json() == { + "id": "isbn-9781529046137", + "name": "The Hitchhiker's Guide to the Galaxy", + } + + +def test_get_item_does_not_exist(client: TestClient): + response = client.get("/items?id=isbn-nope") + assert response.status_code == 200, response.text + assert response.json() == {"id": "isbn-nope", "name": None} + + +def test_get_invalid_item(client: TestClient): + response = client.get("/items?id=wtf-yes") + assert response.status_code == 422, response.text + assert response.json() == snapshot( + { + "detail": [ + { + "type": "value_error", + "loc": ["query", "id"], + "msg": 'Value error, Invalid ID format, it must start with "isbn-" or "imdb-"', + "input": "wtf-yes", + "ctx": {"error": {}}, + } + ] + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "id", + "in": "query", + "required": False, + "schema": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Id", + }, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) From a2c2e332a0936a2d6277548d612ec7a1fc957020 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 1 Mar 2025 22:02:59 +0000 Subject: [PATCH 889/932] =?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 [skip ci] --- 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 80075319d..c4e7d051b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Fixes + +* 🐛 Add docs examples and tests (support) for `Annotated` custom validations, like `AfterValidator`, revert #13440. PR [#13442](https://github.com/fastapi/fastapi/pull/13442) by [@tiangolo](https://github.com/tiangolo). + ### Translations * 🌐 Add Russian translation for `docs/ru/docs/tutorial/middleware.md`. PR [#13412](https://github.com/fastapi/fastapi/pull/13412) by [@alv2017](https://github.com/alv2017). From a01ed2f6a71b4f5eb38cd25f4ad435b749f120df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 1 Mar 2025 23:13:11 +0100 Subject: [PATCH 890/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c4e7d051b..0c92d966d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,7 +9,8 @@ hide: ### Fixes -* 🐛 Add docs examples and tests (support) for `Annotated` custom validations, like `AfterValidator`, revert #13440. PR [#13442](https://github.com/fastapi/fastapi/pull/13442) by [@tiangolo](https://github.com/tiangolo). +* 🐛 Add docs examples and tests (support) for `Annotated` custom validations, like `AfterValidator`, revert [#13440](https://github.com/fastapi/fastapi/pull/13440). PR [#13442](https://github.com/fastapi/fastapi/pull/13442) by [@tiangolo](https://github.com/tiangolo). + * New docs: [Query Parameters and String Validations - Custom Validation](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#custom-validation). ### Translations From 3824664620433f0055125adbf2fc212ced2bdf94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 1 Mar 2025 23:14:01 +0100 Subject: [PATCH 891/932] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?5.11?= 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 0c92d966d..0679ce8a1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.115.11 + ### Fixes * 🐛 Add docs examples and tests (support) for `Annotated` custom validations, like `AfterValidator`, revert [#13440](https://github.com/fastapi/fastapi/pull/13440). PR [#13442](https://github.com/fastapi/fastapi/pull/13442) by [@tiangolo](https://github.com/tiangolo). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index a6e7e47fd..757b76106 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.10" +__version__ = "0.115.11" from starlette import status as status From 316566e40efb5b7dabc549ff0060a016e68719ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 3 Mar 2025 15:33:33 +0100 Subject: [PATCH 892/932] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors:=20pau?= =?UTF-8?q?se=20TestDriven=20(#13446)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/sponsors.yml | 6 +++--- docs/en/docs/advanced/index.md | 15 --------------- 2 files changed, 3 insertions(+), 18 deletions(-) diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index b994e533a..5cbf05f9d 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -58,9 +58,9 @@ bronze: - url: https://www.exoflare.com/open-source/?utm_source=FastAPI&utm_campaign=open_source title: Biosecurity risk assessments made easy. img: https://fastapi.tiangolo.com/img/sponsors/exoflare.png - - url: https://testdriven.io/courses/tdd-fastapi/ - title: Learn to build high-quality web apps with best practices - img: https://fastapi.tiangolo.com/img/sponsors/testdriven.svg + # - url: https://testdriven.io/courses/tdd-fastapi/ + # title: Learn to build high-quality web apps with best practices + # img: https://fastapi.tiangolo.com/img/sponsors/testdriven.svg - url: https://lambdatest.com/?utm_source=fastapi&utm_medium=partner&utm_campaign=sponsor&utm_term=opensource&utm_content=webpage title: LambdaTest, AI-Powered Cloud-based Test Orchestration Platform img: https://fastapi.tiangolo.com/img/sponsors/lambdatest.png diff --git a/docs/en/docs/advanced/index.md b/docs/en/docs/advanced/index.md index 36f0720c0..47385e2c6 100644 --- a/docs/en/docs/advanced/index.md +++ b/docs/en/docs/advanced/index.md @@ -19,18 +19,3 @@ And it's possible that for your use case, the solution is in one of them. You could still use most of the features in **FastAPI** with the knowledge from the main [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank}. And the next sections assume you already read it, and assume that you know those main ideas. - -## External Courses - -Although the [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} and this **Advanced User Guide** are written as a guided tutorial (like a book) and should be enough for you to **learn FastAPI**, you might want to complement it with additional courses. - -Or it might be the case that you just prefer to take other courses because they adapt better to your learning style. - -Some course providers ✨ [**sponsor FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, this ensures the continued and healthy **development** of FastAPI and its **ecosystem**. - -And it shows their true commitment to FastAPI and its **community** (you), as they not only want to provide you a **good learning experience** but also want to make sure you have a **good and healthy framework**, FastAPI. 🙇 - -You might want to try their courses: - -* Talk Python Training -* Test-Driven Development From ab22979dc566619f72eb989aacb84c95539ae5a4 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 3 Mar 2025 14:33:58 +0000 Subject: [PATCH 893/932] =?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 [skip ci] --- 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 0679ce8a1..72c47d4fb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Internal + +* 🔧 Update sponsors: pause TestDriven. PR [#13446](https://github.com/fastapi/fastapi/pull/13446) by [@tiangolo](https://github.com/tiangolo). + ## 0.115.11 ### Fixes From 8c94e97c89f617ad808d8ca24da6e52a238bcee9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 6 Mar 2025 13:18:57 +0100 Subject: [PATCH 894/932] =?UTF-8?q?=E2=AC=86=20Bump=20ruff=20to=200.9.4=20?= =?UTF-8?q?(#13299)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ⬆ Bump ruff from 0.6.4 to 0.9.4 Bumps [ruff](https://github.com/astral-sh/ruff) from 0.6.4 to 0.9.4. - [Release notes](https://github.com/astral-sh/ruff/releases) - [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md) - [Commits](https://github.com/astral-sh/ruff/compare/0.6.4...0.9.4) --- updated-dependencies: - dependency-name: ruff dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * update pre-commit accordingly and make formatting changes * 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks --------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> Co-authored-by: svlandeg Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .pre-commit-config.yaml | 2 +- fastapi/dependencies/utils.py | 42 +++++++-------- fastapi/openapi/utils.py | 12 ++--- fastapi/routing.py | 24 ++++----- requirements-docs-tests.txt | 2 +- scripts/translate.py | 12 ++--- tests/test_enforce_once_required_parameter.py | 6 +-- tests/test_generic_parameterless_depends.py | 4 +- tests/test_repeated_dependency_schema.py | 6 +-- .../test_tutorial001.py | 48 ++++++++--------- .../test_tutorial002.py | 54 +++++++++---------- .../test_tutorial003.py | 54 +++++++++---------- .../test_sql_databases/test_tutorial002.py | 6 +-- 13 files changed, 136 insertions(+), 136 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 767ef8d9e..05c33a608 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.7.4 + rev: v0.9.4 hooks: - id: ruff args: diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index e2866b488..d205d17fa 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -133,9 +133,9 @@ def get_param_sub_dependant( def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: - assert callable( - depends.dependency - ), "A parameter-less dependency must have a callable dependency" + assert callable(depends.dependency), ( + "A parameter-less dependency must have a callable dependency" + ) return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) @@ -302,9 +302,9 @@ def get_dependant( type_annotation=param_details.type_annotation, dependant=dependant, ): - assert ( - param_details.field is None - ), f"Cannot specify multiple FastAPI annotations for {param_name!r}" + assert param_details.field is None, ( + f"Cannot specify multiple FastAPI annotations for {param_name!r}" + ) continue assert param_details.field is not None if isinstance(param_details.field.field_info, params.Body): @@ -439,9 +439,9 @@ def analyze_param( ), ): assert depends is None, f"Cannot specify `Depends` for type {type_annotation!r}" - assert ( - field_info is None - ), f"Cannot specify FastAPI annotation for type {type_annotation!r}" + assert field_info is None, ( + f"Cannot specify FastAPI annotation for type {type_annotation!r}" + ) # Handle default assignations, neither field_info nor depends was not found in Annotated nor default value elif field_info is None and depends is None: default_value = value if value is not inspect.Signature.empty else RequiredParam @@ -494,9 +494,9 @@ def analyze_param( field_info=field_info, ) if is_path_param: - assert is_scalar_field( - field=field - ), "Path params must be of one of the supported types" + assert is_scalar_field(field=field), ( + "Path params must be of one of the supported types" + ) elif isinstance(field_info, params.Query): assert ( is_scalar_field(field) @@ -521,9 +521,9 @@ def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None: elif field_info_in == params.ParamTypes.header: dependant.header_params.append(field) else: - assert ( - field_info_in == params.ParamTypes.cookie - ), f"non-body parameters must be in path, query, header or cookie: {field.name}" + assert field_info_in == params.ParamTypes.cookie, ( + f"non-body parameters must be in path, query, header or cookie: {field.name}" + ) dependant.cookie_params.append(field) @@ -782,9 +782,9 @@ def request_params_to_args( if single_not_embedded_field: field_info = first_field.field_info - assert isinstance( - field_info, params.Param - ), "Params must be subclasses of Param" + assert isinstance(field_info, params.Param), ( + "Params must be subclasses of Param" + ) loc: Tuple[str, ...] = (field_info.in_.value,) v_, errors_ = _validate_value_with_model_field( field=first_field, value=params_to_process, values=values, loc=loc @@ -794,9 +794,9 @@ def request_params_to_args( for field in fields: value = _get_multidict_value(field, received_params) field_info = field.field_info - assert isinstance( - field_info, params.Param - ), "Params must be subclasses of Param" + assert isinstance(field_info, params.Param), ( + "Params must be subclasses of Param" + ) loc = (field_info.in_.value, field.alias) v_, errors_ = _validate_value_with_model_field( field=field, value=value, values=values, loc=loc diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py index 947eca948..bd8f3c106 100644 --- a/fastapi/openapi/utils.py +++ b/fastapi/openapi/utils.py @@ -364,9 +364,9 @@ def get_openapi_path( openapi_response = operation_responses.setdefault( status_code_key, {} ) - assert isinstance( - process_response, dict - ), "An additional response must be a dict" + assert isinstance(process_response, dict), ( + "An additional response must be a dict" + ) field = route.response_fields.get(additional_status_code) additional_field_schema: Optional[Dict[str, Any]] = None if field: @@ -434,9 +434,9 @@ def get_fields_from_routes( route, routing.APIRoute ): if route.body_field: - assert isinstance( - route.body_field, ModelField - ), "A request body must be a Pydantic Field" + assert isinstance(route.body_field, ModelField), ( + "A request body must be a Pydantic Field" + ) body_fields_from_routes.append(route.body_field) if route.response_field: responses_from_routes.append(route.response_field) diff --git a/fastapi/routing.py b/fastapi/routing.py index 8ea4bb219..457481e32 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -504,9 +504,9 @@ class APIRoute(routing.Route): status_code = int(status_code) self.status_code = status_code if self.response_model: - assert is_body_allowed_for_status_code( - status_code - ), f"Status code {status_code} must not have a response body" + assert is_body_allowed_for_status_code(status_code), ( + f"Status code {status_code} must not have a response body" + ) response_name = "Response_" + self.unique_id self.response_field = create_model_field( name=response_name, @@ -537,9 +537,9 @@ class APIRoute(routing.Route): assert isinstance(response, dict), "An additional response must be a dict" model = response.get("model") if model: - assert is_body_allowed_for_status_code( - additional_status_code - ), f"Status code {additional_status_code} must not have a response body" + assert is_body_allowed_for_status_code(additional_status_code), ( + f"Status code {additional_status_code} must not have a response body" + ) response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = create_model_field( name=response_name, type_=model, mode="serialization" @@ -844,9 +844,9 @@ class APIRouter(routing.Router): ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" - assert not prefix.endswith( - "/" - ), "A path prefix must not end with '/', as the routes will start with '/'" + assert not prefix.endswith("/"), ( + "A path prefix must not end with '/', as the routes will start with '/'" + ) self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) @@ -1256,9 +1256,9 @@ class APIRouter(routing.Router): """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" - assert not prefix.endswith( - "/" - ), "A path prefix must not end with '/', as the routes will start with '/'" + assert not prefix.endswith("/"), ( + "A path prefix must not end with '/', as the routes will start with '/'" + ) else: for r in router.routes: path = getattr(r, "path") # noqa: B009 diff --git a/requirements-docs-tests.txt b/requirements-docs-tests.txt index 331d2a5b3..e7718e61d 100644 --- a/requirements-docs-tests.txt +++ b/requirements-docs-tests.txt @@ -1,4 +1,4 @@ # For mkdocstrings and tests httpx >=0.23.0,<0.28.0 # For linting and generating docs versions -ruff ==0.6.4 +ruff ==0.9.4 diff --git a/scripts/translate.py b/scripts/translate.py index ce11b3877..9a2136d1b 100644 --- a/scripts/translate.py +++ b/scripts/translate.py @@ -38,9 +38,9 @@ def get_langs() -> dict[str, str]: def generate_lang_path(*, lang: str, path: Path) -> Path: en_docs_path = Path("docs/en/docs") - assert str(path).startswith( - str(en_docs_path) - ), f"Path must be inside {en_docs_path}" + assert str(path).startswith(str(en_docs_path)), ( + f"Path must be inside {en_docs_path}" + ) lang_docs_path = Path(f"docs/{lang}/docs") out_path = Path(str(path).replace(str(en_docs_path), str(lang_docs_path))) return out_path @@ -56,9 +56,9 @@ def translate_page(*, lang: str, path: Path) -> None: lang_prompt_content = lang_prompt_path.read_text() en_docs_path = Path("docs/en/docs") - assert str(path).startswith( - str(en_docs_path) - ), f"Path must be inside {en_docs_path}" + assert str(path).startswith(str(en_docs_path)), ( + f"Path must be inside {en_docs_path}" + ) out_path = generate_lang_path(lang=lang, path=path) out_path.parent.mkdir(parents=True, exist_ok=True) original_content = path.read_text() diff --git a/tests/test_enforce_once_required_parameter.py b/tests/test_enforce_once_required_parameter.py index b64f8341b..30329282f 100644 --- a/tests/test_enforce_once_required_parameter.py +++ b/tests/test_enforce_once_required_parameter.py @@ -48,7 +48,7 @@ expected_schema = { "type": "array", }, "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error " "Type", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, }, "required": ["loc", "msg", "type"], "title": "ValidationError", @@ -73,7 +73,7 @@ expected_schema = { "responses": { "200": { "content": {"application/json": {"schema": {}}}, - "description": "Successful " "Response", + "description": "Successful Response", }, "422": { "content": { @@ -83,7 +83,7 @@ expected_schema = { } } }, - "description": "Validation " "Error", + "description": "Validation Error", }, }, "summary": "Foo Handler", diff --git a/tests/test_generic_parameterless_depends.py b/tests/test_generic_parameterless_depends.py index fe13ff89b..5aa35320c 100644 --- a/tests/test_generic_parameterless_depends.py +++ b/tests/test_generic_parameterless_depends.py @@ -55,7 +55,7 @@ def test_openapi_schema(): "responses": { "200": { "content": {"application/json": {"schema": {}}}, - "description": "Successful " "Response", + "description": "Successful Response", } }, "summary": "A", @@ -67,7 +67,7 @@ def test_openapi_schema(): "responses": { "200": { "content": {"application/json": {"schema": {}}}, - "description": "Successful " "Response", + "description": "Successful Response", } }, "summary": "B", diff --git a/tests/test_repeated_dependency_schema.py b/tests/test_repeated_dependency_schema.py index d7d0dfa05..c21829bd9 100644 --- a/tests/test_repeated_dependency_schema.py +++ b/tests/test_repeated_dependency_schema.py @@ -41,7 +41,7 @@ schema = { "type": "array", }, "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error " "Type", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, }, "required": ["loc", "msg", "type"], "title": "ValidationError", @@ -66,7 +66,7 @@ schema = { "responses": { "200": { "content": {"application/json": {"schema": {}}}, - "description": "Successful " "Response", + "description": "Successful Response", }, "422": { "content": { @@ -76,7 +76,7 @@ schema = { } } }, - "description": "Validation " "Error", + "description": "Validation Error", }, }, "summary": "Get Deps", diff --git a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py index 72db54bd2..a04dba219 100644 --- a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py +++ b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py @@ -8,31 +8,31 @@ client = TestClient(app) def test_swagger_ui(): response = client.get("/docs") assert response.status_code == 200, response.text - assert ( - '"syntaxHighlight": false' in response.text - ), "syntaxHighlight should be included and converted to JSON" - assert ( - '"dom_id": "#swagger-ui"' in response.text - ), "default configs should be preserved" + assert '"syntaxHighlight": false' in response.text, ( + "syntaxHighlight should be included and converted to JSON" + ) + assert '"dom_id": "#swagger-ui"' in response.text, ( + "default configs should be preserved" + ) assert "presets: [" in response.text, "default configs should be preserved" - assert ( - "SwaggerUIBundle.presets.apis," in response.text - ), "default configs should be preserved" - assert ( - "SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text - ), "default configs should be preserved" - assert ( - '"layout": "BaseLayout",' in response.text - ), "default configs should be preserved" - assert ( - '"deepLinking": true,' in response.text - ), "default configs should be preserved" - assert ( - '"showExtensions": true,' in response.text - ), "default configs should be preserved" - assert ( - '"showCommonExtensions": true,' in response.text - ), "default configs should be preserved" + assert "SwaggerUIBundle.presets.apis," in response.text, ( + "default configs should be preserved" + ) + assert "SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text, ( + "default configs should be preserved" + ) + assert '"layout": "BaseLayout",' in response.text, ( + "default configs should be preserved" + ) + assert '"deepLinking": true,' in response.text, ( + "default configs should be preserved" + ) + assert '"showExtensions": true,' in response.text, ( + "default configs should be preserved" + ) + assert '"showCommonExtensions": true,' in response.text, ( + "default configs should be preserved" + ) def test_get_users(): diff --git a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py index d06a385b5..ea56b6f21 100644 --- a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py +++ b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py @@ -8,34 +8,34 @@ client = TestClient(app) def test_swagger_ui(): response = client.get("/docs") assert response.status_code == 200, response.text - assert ( - '"syntaxHighlight": false' not in response.text - ), "not used parameters should not be included" - assert ( - '"syntaxHighlight": {"theme": "obsidian"}' in response.text - ), "parameters with middle dots should be included in a JSON compatible way" - assert ( - '"dom_id": "#swagger-ui"' in response.text - ), "default configs should be preserved" + assert '"syntaxHighlight": false' not in response.text, ( + "not used parameters should not be included" + ) + assert '"syntaxHighlight": {"theme": "obsidian"}' in response.text, ( + "parameters with middle dots should be included in a JSON compatible way" + ) + assert '"dom_id": "#swagger-ui"' in response.text, ( + "default configs should be preserved" + ) assert "presets: [" in response.text, "default configs should be preserved" - assert ( - "SwaggerUIBundle.presets.apis," in response.text - ), "default configs should be preserved" - assert ( - "SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text - ), "default configs should be preserved" - assert ( - '"layout": "BaseLayout",' in response.text - ), "default configs should be preserved" - assert ( - '"deepLinking": true,' in response.text - ), "default configs should be preserved" - assert ( - '"showExtensions": true,' in response.text - ), "default configs should be preserved" - assert ( - '"showCommonExtensions": true,' in response.text - ), "default configs should be preserved" + assert "SwaggerUIBundle.presets.apis," in response.text, ( + "default configs should be preserved" + ) + assert "SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text, ( + "default configs should be preserved" + ) + assert '"layout": "BaseLayout",' in response.text, ( + "default configs should be preserved" + ) + assert '"deepLinking": true,' in response.text, ( + "default configs should be preserved" + ) + assert '"showExtensions": true,' in response.text, ( + "default configs should be preserved" + ) + assert '"showCommonExtensions": true,' in response.text, ( + "default configs should be preserved" + ) def test_get_users(): diff --git a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py index 187e89ace..926bbb14f 100644 --- a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py +++ b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py @@ -8,34 +8,34 @@ client = TestClient(app) def test_swagger_ui(): response = client.get("/docs") assert response.status_code == 200, response.text - assert ( - '"deepLinking": false,' in response.text - ), "overridden configs should be preserved" - assert ( - '"deepLinking": true' not in response.text - ), "overridden configs should not include the old value" - assert ( - '"syntaxHighlight": false' not in response.text - ), "not used parameters should not be included" - assert ( - '"dom_id": "#swagger-ui"' in response.text - ), "default configs should be preserved" + assert '"deepLinking": false,' in response.text, ( + "overridden configs should be preserved" + ) + assert '"deepLinking": true' not in response.text, ( + "overridden configs should not include the old value" + ) + assert '"syntaxHighlight": false' not in response.text, ( + "not used parameters should not be included" + ) + assert '"dom_id": "#swagger-ui"' in response.text, ( + "default configs should be preserved" + ) assert "presets: [" in response.text, "default configs should be preserved" - assert ( - "SwaggerUIBundle.presets.apis," in response.text - ), "default configs should be preserved" - assert ( - "SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text - ), "default configs should be preserved" - assert ( - '"layout": "BaseLayout",' in response.text - ), "default configs should be preserved" - assert ( - '"showExtensions": true,' in response.text - ), "default configs should be preserved" - assert ( - '"showCommonExtensions": true,' in response.text - ), "default configs should be preserved" + assert "SwaggerUIBundle.presets.apis," in response.text, ( + "default configs should be preserved" + ) + assert "SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text, ( + "default configs should be preserved" + ) + assert '"layout": "BaseLayout",' in response.text, ( + "default configs should be preserved" + ) + assert '"showExtensions": true,' in response.text, ( + "default configs should be preserved" + ) + assert '"showCommonExtensions": true,' in response.text, ( + "default configs should be preserved" + ) def test_get_users(): diff --git a/tests/test_tutorial/test_sql_databases/test_tutorial002.py b/tests/test_tutorial/test_sql_databases/test_tutorial002.py index 68c1966f5..79e48c1c3 100644 --- a/tests/test_tutorial/test_sql_databases/test_tutorial002.py +++ b/tests/test_tutorial/test_sql_databases/test_tutorial002.py @@ -71,9 +71,9 @@ def test_crud_app(client: TestClient): assert response.json() == snapshot( {"age": 30, "id": IsInt(), "name": "Dead Pond"} ) - assert ( - response.json()["id"] != 9000 - ), "The ID should be generated by the database" + assert response.json()["id"] != 9000, ( + "The ID should be generated by the database" + ) # Read a hero hero_id = response.json()["id"] From daf6820307816571433824617f69f9ac51621193 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 6 Mar 2025 12:19:24 +0000 Subject: [PATCH 895/932] =?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 [skip ci] --- 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 72c47d4fb..52edd7773 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Internal +* ⬆ Bump ruff to 0.9.4. PR [#13299](https://github.com/fastapi/fastapi/pull/13299) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Update sponsors: pause TestDriven. PR [#13446](https://github.com/fastapi/fastapi/pull/13446) by [@tiangolo](https://github.com/tiangolo). ## 0.115.11 From a592e8ad4dba1941a3619bd270ccb0f026ec5ba2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=C6=B0=C6=A1ng=20T=E1=BA=A5n=20Th=C3=A0nh?= <51350651+ptt3199@users.noreply.github.com> Date: Fri, 7 Mar 2025 10:24:13 +0700 Subject: [PATCH 896/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Vietnamese=20trans?= =?UTF-8?q?lation=20for=20`docs/vi/docs/deployment/cloud.md`=20(#13407)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sofie Van Landeghem Co-authored-by: Dinh Van Luc <39489075+MrL8199@users.noreply.github.com> --- docs/vi/docs/deployment/cloud.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 docs/vi/docs/deployment/cloud.md diff --git a/docs/vi/docs/deployment/cloud.md b/docs/vi/docs/deployment/cloud.md new file mode 100644 index 000000000..9ab72769d --- /dev/null +++ b/docs/vi/docs/deployment/cloud.md @@ -0,0 +1,17 @@ +# Triển khai FastAPI trên các Dịch vụ Cloud + +Bạn có thể sử dụng **bất kỳ nhà cung cấp dịch vụ cloud** nào để triển khai ứng dụng FastAPI của mình. + +Trong hầu hết các trường hợp, các nhà cung cấp dịch vụ cloud lớn đều có hướng dẫn triển khai FastAPI với họ. + +## Nhà cung cấp dịch vụ Cloud - Nhà tài trợ +Một vài nhà cung cấp dịch vụ cloud ✨ [**tài trợ cho FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, điều này giúp đảm bảo sự phát triển liên tục và khỏe mạnh của FastAPI và hệ sinh thái của nó. + +Thêm nữa, điều này cũng thể hiện cam kết thực sự của họ đối với FastAPI và **cộng đồng người dùng** (bạn), vì họ không chỉ muốn cung cấp cho bạn một **dịch vụ tốt** mà còn muốn đảm bảo rằng bạn có một **framework tốt và bền vững**, đó chính là FastAPI. 🙇 + +Bạn có thể thử các dịch vụ của họ và làm theo hướng dẫn của họ: + +* Platform.sh +* Porter +* Coherence +* Render From 0c36a7ac0587c05e3f8d6b54e65565190f68e580 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 7 Mar 2025 03:24:33 +0000 Subject: [PATCH 897/932] =?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 [skip ci] --- 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 52edd7773..e9bccf0fb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Translations + +* 🌐 Add Vietnamese translation for `docs/vi/docs/deployment/cloud.md`. PR [#13407](https://github.com/fastapi/fastapi/pull/13407) by [@ptt3199](https://github.com/ptt3199). + ### Internal * ⬆ Bump ruff to 0.9.4. PR [#13299](https://github.com/fastapi/fastapi/pull/13299) by [@dependabot[bot]](https://github.com/apps/dependabot). From a88a6050a6423630ac141a862742fca79333d516 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 7 Mar 2025 04:24:42 +0100 Subject: [PATCH 898/932] =?UTF-8?q?=E2=AC=86=20Bump=20black=20from=2024.10?= =?UTF-8?q?.0=20to=2025.1.0=20(#13436)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [black](https://github.com/psf/black) from 24.10.0 to 25.1.0. - [Release notes](https://github.com/psf/black/releases) - [Changelog](https://github.com/psf/black/blob/main/CHANGES.md) - [Commits](https://github.com/psf/black/compare/24.10.0...25.1.0) --- updated-dependencies: - dependency-name: black dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs.txt b/requirements-docs.txt index cd2e4e58e..8812e27f9 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -14,6 +14,6 @@ cairosvg==2.7.1 mkdocstrings[python]==0.26.1 griffe-typingdoc==0.2.7 # For griffe, it formats with black -black==24.10.0 +black==25.1.0 mkdocs-macros-plugin==1.3.7 markdown-include-variants==0.0.4 From 79bc28fab4b33c7822a5a30408ec0fec69d6630c Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 7 Mar 2025 03:25:02 +0000 Subject: [PATCH 899/932] =?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 [skip ci] --- 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 e9bccf0fb..86f9ab0cb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Internal +* ⬆ Bump black from 24.10.0 to 25.1.0. PR [#13436](https://github.com/fastapi/fastapi/pull/13436) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump ruff to 0.9.4. PR [#13299](https://github.com/fastapi/fastapi/pull/13299) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Update sponsors: pause TestDriven. PR [#13446](https://github.com/fastapi/fastapi/pull/13446) by [@tiangolo](https://github.com/tiangolo). From c46e4a1b1424cef38349627a32b4419d0a2a1612 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 7 Mar 2025 04:25:10 +0100 Subject: [PATCH 900/932] =?UTF-8?q?=E2=AC=86=20Bump=20sqlmodel=20from=200.?= =?UTF-8?q?0.22=20to=200.0.23=20(#13437)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [sqlmodel](https://github.com/fastapi/sqlmodel) from 0.0.22 to 0.0.23. - [Release notes](https://github.com/fastapi/sqlmodel/releases) - [Changelog](https://github.com/fastapi/sqlmodel/blob/main/docs/release-notes.md) - [Commits](https://github.com/fastapi/sqlmodel/compare/0.0.22...0.0.23) --- updated-dependencies: - dependency-name: sqlmodel dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-tests.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-tests.txt b/requirements-tests.txt index 4a15844e4..6a870add6 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -4,7 +4,7 @@ pytest >=7.1.3,<9.0.0 coverage[toml] >= 6.5.0,< 8.0 mypy ==1.8.0 dirty-equals ==0.8.0 -sqlmodel==0.0.22 +sqlmodel==0.0.23 flask >=1.1.2,<4.0.0 anyio[trio] >=3.2.1,<5.0.0 PyJWT==2.8.0 From 643d2845de09a437b955a163ab25eb0887bfd0e1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 7 Mar 2025 03:25:46 +0000 Subject: [PATCH 901/932] =?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 [skip ci] --- 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 86f9ab0cb..ee987b544 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Internal +* ⬆ Bump sqlmodel from 0.0.22 to 0.0.23. PR [#13437](https://github.com/fastapi/fastapi/pull/13437) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump black from 24.10.0 to 25.1.0. PR [#13436](https://github.com/fastapi/fastapi/pull/13436) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump ruff to 0.9.4. PR [#13299](https://github.com/fastapi/fastapi/pull/13299) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Update sponsors: pause TestDriven. PR [#13446](https://github.com/fastapi/fastapi/pull/13446) by [@tiangolo](https://github.com/tiangolo). From 3565ea00b6a3193743dddb98bdd47f878374ae64 Mon Sep 17 00:00:00 2001 From: Lee Yesong Date: Mon, 10 Mar 2025 21:29:03 +0900 Subject: [PATCH 902/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Korean=20translati?= =?UTF-8?q?on=20for=20`docs/ko/docs/tutorial/security/oauth2-jwt.md`=20(#1?= =?UTF-8?q?3333)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/docs/tutorial/security/oauth2-jwt.md | 273 +++++++++++++++++++ 1 file changed, 273 insertions(+) create mode 100644 docs/ko/docs/tutorial/security/oauth2-jwt.md diff --git a/docs/ko/docs/tutorial/security/oauth2-jwt.md b/docs/ko/docs/tutorial/security/oauth2-jwt.md new file mode 100644 index 000000000..d8bac8346 --- /dev/null +++ b/docs/ko/docs/tutorial/security/oauth2-jwt.md @@ -0,0 +1,273 @@ +# 패스워드 해싱을 이용한 OAuth2, JWT 토큰을 사용하는 Bearer 인증 + +모든 보안 흐름을 구성했으므로, 이제 JWT 토큰과 패스워드 해싱을 사용해 애플리케이션을 안전하게 만들 것입니다. + +이 코드는 실제로 애플리케이션에서 패스워드를 해싱하여 DB에 저장하는 등의 작업에 활용할 수 있습니다. + +이전 장에 이어서 시작해 봅시다. + +## JWT + +JWT 는 "JSON Web Tokens" 을 의미합니다. + +JSON 객체를 공백이 없는 긴 문자열로 인코딩하는 표준이며, 다음과 같은 형태입니다: + +``` +eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c +``` + +JWT는 암호화되지 않아 누구든지 토큰에서 정보를 복원할 수 있습니다. + +하지만 JWT는 서명되어 있습니다. 그래서 자신이 발급한 토큰을 받았을 때, 실제로 자신이 발급한게 맞는지 검증할 수 있습니다. + +만료 기간이 일주일인 토큰을 발행했다고 가정해 봅시다. 다음 날 사용자가 토큰을 가져왔을 때, 그 사용자가 시스템에 여전히 로그인되어 있다는 것을 알 수 있습니다. + +일주일 뒤에는 토큰이 만료될 것이고, 사용자는 인가되지 않아 새 토큰을 받기 위해 다시 로그인해야 할 것입니다. 만약 사용자(또는 제3자)가 토큰을 수정하거나 만료일을 변경하면, 서명이 일치하지 않기 때문에 알아챌 수 있을 것입니다. + +만약 JWT 토큰을 다뤄보고, 작동 방식도 알아보고 싶다면 https://jwt.io 을 확인하십시오. + +## `PyJWT` 설치 + +파이썬으로 JWT 토큰을 생성하고 검증하려면 `PyJWT` 를 설치해야 합니다. + +[가상환경](../../virtual-environments.md){.internal-link target=_blank} 을 만들고 활성화한 다음 `pyjwt` 를 설치하십시오: + +
    + +```console +$ pip install pyjwt + +---> 100% +``` + +
    + +/// info | 참고 + +RSA나 ECDSA 같은 전자 서명 알고리즘을 사용하려면, `pyjwt[crypto]`라는 암호화 라이브러리 의존성을 설치해야 합니다. + +더 자세한 내용은 PyJWT 설치 에서 확인할 수 있습니다. + +/// + +## 패스워드 해싱 + +"해싱(Hashing)"은 어떤 내용(여기서는 패스워드)을 해석할 수 없는 일련의 바이트 집합(단순 문자열)으로 변환하는 것을 의미합니다. + +동일한 내용(똑같은 패스워드)을 해싱하면 동일한 문자열을 얻습니다. + +하지만 그 문자열을 다시 패스워드로 되돌릴 수는 없습니다. + +### 패스워드를 해싱하는 이유 + +데이터베이스를 탈취당하더라도, 침입자는 사용자의 평문 패스워드 대신 해시 값만 얻을 수 있습니다. + +따라서 침입자는 훔친 사용자 패스워드를 다른 시스템에서 활용할 수 없습니다. (대다수 사용자가 여러 시스템에서 동일한 패스워드를 사용하기 때문에 평문 패스워드가 유출되면 위험합니다.) + +## `passlib` 설치 + +PassLib는 패스워드 해시를 다루는 훌륭한 파이썬 패키지입니다. + +많은 안전한 해시 알고리즘과 도구들을 지원합니다. + +추천하는 알고리즘은 "Bcrypt"입니다. + +[가상환경](../../virtual-environments.md){.internal-link target=_blank} 을 만들고 활성화한 다음 PassLib와 Bcrypt를 설치하십시오: + +
    + +```console +$ pip install "passlib[bcrypt]" + +---> 100% +``` + +
    + +/// tip | 팁 + +`passlib`를 사용하여, **Django**, **Flask** 의 보안 플러그인이나 다른 도구로 생성한 패스워드를 읽을 수 있도록 설정할 수도 있습니다. + +예를 들자면, FastAPI 애플리케이션과 Django 애플리케이션이 같은 데이터베이스에서 데이터를 공유할 수 있습니다. 또는 같은 데이터베이스를 사용하여 Django 애플리케이션을 점진적으로 마이그레이션 할 수도 있습니다. + +그리고 사용자는 FastAPI 애플리케이션과 Django 애플리케이션에 동시에 로그인할 수 있습니다. + +/// + +## 패스워드의 해시와 검증 + +필요한 도구를 `passlib`에서 임포트합니다. + +PassLib "컨텍스트(context)"를 생성합니다. 이것은 패스워드를 해싱하고 검증하는데 사용합니다. + +/// tip | 팁 + +PassLib 컨텍스트는 다양한 해싱 알고리즘을 사용할 수 있는 기능을 제공하며, 더 이상 사용이 권장되지 않는 오래된 해싱 알고리즘을 검증하는 기능도 포함되어 있습니다. + +예를 들어, 다른 시스템(Django 같은)에서 생성한 패스워드를 읽고 검증할 수 있으며, 새로운 패스워드를 Bcrypt 같은 다른 알고리즘으로 해싱할 수도 있습니다. + +그리고 동시에 그런 모든 알고리즘과 호환성을 유지합니다. + +/// + +사용자로부터 받은 패스워드를 해싱하는 유틸리티 함수를 생성합니다. + +그리고 받은 패스워드가 저장된 해시와 일치하는지 검증하는 또 다른 유틸리티 함수도 생성합니다. + +그리고 사용자를 인증하고 반환하는 또 다른 함수도 생성합니다. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *} + +/// note + +새로운 (가짜) 데이터베이스 `fake_users_db`를 확인하면, 해시 처리된 패스워드가 어떻게 생겼는지 볼 수 있습니다: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. + +/// + +## JWT 토큰 처리 + +설치된 모듈을 임포트 합니다. + +JWT 토큰 서명에 사용될 임의의 비밀키를 생성합니다. + +안전한 임의의 비밀키를 생성하려면 다음 명령어를 사용하십시오: + +
    + +```console +$ openssl rand -hex 32 + +09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7 +``` + +
    + +그리고 생성한 비밀키를 복사해 변수 `SECRET_KEY`에 대입합니다. (이 예제의 변수 값을 그대로 사용하지 마십시오.) + +JWT 토큰을 서명하는 데 사용될 알고리즘을 위한 변수 `ALGORITHM` 을 생성하고 `"HS256"` 으로 설정합니다. + +토큰 만료 기간을 위한 변수를 생성합니다. + +응답을 위한 토큰 엔드포인트에 사용될 Pydantic 모델을 정의합니다. + +새 액세스 토큰을 생성하기 위한 유틸리티 함수를 생성합니다. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *} + +## 의존성 수정 + +`get_current_user` 함수를 이전과 동일한 토큰을 받도록 수정하되, 이번에는 JWT 토큰을 사용하도록 합니다. + +받은 토큰을 디코딩하여 검증한 후 현재 사용자를 반환합니다. + +토큰이 유효하지 않다면 HTTP 오류를 반환합니다. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[90:107] *} + +## `/token` 경로 작업 수정 + +토큰의 만료 시각을 설정하기 위해 `timedelta` 를 생성합니다. + +실제 JWT 액세스 토큰을 생성하여 반환합니다. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *} + +### JWT "주체(subject)" `sub`에 대한 기술 세부 사항 + +JWT 명세에 따르면 토큰의 주체를 포함하는 `sub`라는 키가 있습니다. + +사용 여부는 선택사항이지만, 사용자의 식별 정보를 저장할 수 있으므로 여기서는 이를 사용합니다. + +JWT는 사용자를 식별하고 사용자가 API를 직접 사용할 수 있도록 허용하는 것 외에도 다른 용도로 사용될 수도 있습니다. + +예를 들어 "자동차"나 "블로그 게시물"을 식별하는 데 사용할 수 있습니다. + +그리고 "자동차를 운전하다"나 "블로그 게시물을 수정하다"처럼 해당 엔터티에 대한 권한을 추가할 수 있습니다. + +그 후 이 JWT 토큰을 사용자(또는 봇)에게 제공하면, 그들은 계정을 따로 만들 필요 없이 API가 생성한 JWT 토큰만으로 작업(자동차 운전 또는 블로그 게시물 편집)을 수행할 수 있습니다. + +이러한 개념을 활용하면 JWT는 훨씬 더 복잡한 시나리오에도 사용할 수 있습니다. + +이 경우 여러 엔터티가 동일한 ID를 가질 수 있습니다. 예를 들어 foo라는 ID를 가진 사용자, 자동차, 블로그 게시물이 있을 수 있습니다. + +그래서 ID 충돌을 방지하기 위해, 사용자의 JWT 토큰을 생성할 때 접두사로 `sub` 키를 추가할 수 있습니다. 예를 들어 `username:` 을 붙이는 방식입니다. 이 예제에서는 `sub` 값이 `username:johndoe`이 될 수 있습니다. + +가장 중요한 점은 `sub` 키는 전체 애플리케이션에서 고유한 식별자가 되어야 하며 문자열이어야 한다는 점입니다. + +## 확인해봅시다 + +서버를 실행하고 문서로 이동하십시오: http://127.0.0.1:8000/docs. + +다음과 같은 사용자 인터페이스를 볼 수 있습니다: + + + +이전과 같은 방법으로 애플리케이션에 인증하십시오. + +다음 인증 정보를 사용하십시오: + +Username: `johndoe` +Password: `secret` + +/// check + +코드 어디에도 평문 패스워드 "`secret`" 이 없다는 점에 유의하십시오. 해시된 버전만 있습니다. + +/// + + + +`/users/me/` 를 호출하면 다음과 같은 응답을 얻을 수 있습니다: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false +} +``` + + + +개발자 도구를 열어보면 전송된 데이터에 토큰만 포함된 것을 확인할 수 있습니다. 패스워드는 사용자를 인증하고 액세스 토큰을 받기 위한 첫 번째 요청에만 전송되며, 이후에는 전송되지 않습니다: + + + +/// note + +`Bearer `로 시작하는 `Authorization` 헤더에 주목하십시오. + +/// + +## `scopes` 의 고급 사용법 + +OAuth2는 "스코프(scopes)" 라는 개념을 갖고 있습니다. + +이를 사용하여 JWT 토큰에 특정 권한 집합을 추가할 수 있습니다. + +그 후 이 토큰을 사용자에게 직접 제공하거나 제3자에게 제공하여, 특정 제한사항 하에있는 API와 통신하도록 할 수 있습니다. + +**FastAPI** 에서의 사용 방법과 통합 방식은 **심화 사용자 안내서** 에서 자세히 배울 수 있습니다. + +## 요약 + +지금까지 살펴본 내용을 바탕으로, OAuth2와 JWT 같은 표준을 사용하여 안전한 **FastAPI** 애플리케이션을 만들 수 있습니다. + +거의 모든 프레임워크에서 보안 처리는 상당히 복잡한 주제입니다. + +이를 단순화하는 많은 패키지는 데이터 모델, 데이터베이스, 사용 가능한 기능들에 대해 여러 제약이 있습니다. 그리고 지나치게 단순화하는 일부 패키지들은 심각한 보안 결함을 가질 수도 있습니다. + +--- + +**FastAPI** 는 어떤 데이터베이스, 데이터 모델, 도구도 강요하지 않습니다. + +프로젝트에 가장 적합한 것을 선택할 수 있는 유연성을 제공합니다. + +그리고 `passlib` 와 `PyJWT` 처럼 잘 관리되고 널리 사용되는 패키지들을 바로 사용할 수 있습니다. **FastAPI** 는 외부 패키지 통합을 위해 복잡한 메커니즘이 필요하지 않기 때문입니다. + +그러나 유연성, 견고성, 보안성을 해치지 않으면서 과정을 단순화할 수 있는 도구들을 제공합니다. + +그리고 OAuth2와 같은 표준 프로토콜을 비교적 간단한 방법으로 구현하고 사용할 수 있습니다. + +더 세분화된 권한 체계를 위해 OAuth2의 "스코프"를 사용하는 방법은 **심화 사용자 안내서**에서 더 자세히 배울 수 있습니다. OAuth2의 스코프는 제3자 애플리케이션이 사용자를 대신해 그들의 API와 상호작용하도록 권한을 부여하기 위해, Facebook, Google, GitHub, Microsoft, Twitter 등의 많은 대형 인증 제공업체들이 사용하는 메커니즘입니다. From e988050f79b32c9444fba8d014d0c69cd7a4b6c7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 10 Mar 2025 12:29:25 +0000 Subject: [PATCH 903/932] =?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 [skip ci] --- 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 ee987b544..c900dc918 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Translations +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/security/oauth2-jwt.md`. PR [#13333](https://github.com/fastapi/fastapi/pull/13333) by [@yes0ng](https://github.com/yes0ng). * 🌐 Add Vietnamese translation for `docs/vi/docs/deployment/cloud.md`. PR [#13407](https://github.com/fastapi/fastapi/pull/13407) by [@ptt3199](https://github.com/ptt3199). ### Internal From d3cfe72cd7f5148ac89d5f411391bb565f25662a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 19 Mar 2025 14:33:41 +0300 Subject: [PATCH 904/932] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e=20-=20Experts=20(#13493)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions --- docs/en/data/people.yml | 574 +++++++++++++++++----------------------- 1 file changed, 241 insertions(+), 333 deletions(-) diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml index 7f910ab34..4afce19b5 100644 --- a/docs/en/data/people.yml +++ b/docs/en/data/people.yml @@ -1,11 +1,11 @@ maintainers: - login: tiangolo - answers: 1894 + answers: 1897 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 url: https://github.com/tiangolo experts: - login: tiangolo - count: 1894 + count: 1897 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 url: https://github.com/tiangolo - login: github-actions @@ -13,11 +13,11 @@ experts: avatarUrl: https://avatars.githubusercontent.com/in/15368?v=4 url: https://github.com/apps/github-actions - login: Kludex - count: 645 + count: 654 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex - login: jgould22 - count: 250 + count: 263 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 - login: dmontagu @@ -25,7 +25,7 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 url: https://github.com/dmontagu - login: YuriiMotov - count: 223 + count: 238 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov - login: Mause @@ -34,7 +34,7 @@ experts: url: https://github.com/Mause - login: ycd count: 217 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=f1e7bae394a315da950912c92dc861a8eaf95d4c&v=4 url: https://github.com/ycd - login: JarroVGIT count: 192 @@ -46,14 +46,14 @@ experts: url: https://github.com/euri10 - login: iudeen count: 128 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=f09cdd745e5bf16138f29b42732dd57c7f02bee1&v=4 url: https://github.com/iudeen - login: phy25 count: 126 avatarUrl: https://avatars.githubusercontent.com/u/331403?v=4 url: https://github.com/phy25 - login: JavierSanchezCastro - count: 85 + count: 91 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro - login: raphaelauv @@ -69,7 +69,7 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4 url: https://github.com/ArcLightSlavik - login: n8sty - count: 66 + count: 67 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty - login: falkben @@ -80,46 +80,46 @@ experts: count: 50 avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 url: https://github.com/acidjunk -- login: sm-Fifteen - count: 49 - avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 - url: https://github.com/sm-Fifteen - login: yinziyan1206 count: 49 avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 url: https://github.com/yinziyan1206 +- login: sm-Fifteen + count: 49 + avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 + url: https://github.com/sm-Fifteen +- login: luzzodev + count: 48 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?u=5607ae1ce75c5f54f09500ca854227f7bfd2033b&v=4 + url: https://github.com/luzzodev - login: adriangb count: 46 avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 url: https://github.com/adriangb -- login: Dustyposa - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 - url: https://github.com/Dustyposa - login: insomnes count: 45 avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 url: https://github.com/insomnes -- login: odiseo0 - count: 43 - avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 - url: https://github.com/odiseo0 +- login: Dustyposa + count: 45 + avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 + url: https://github.com/Dustyposa - login: frankie567 count: 43 avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=c159fe047727aedecbbeeaa96a1b03ceb9d39add&v=4 url: https://github.com/frankie567 +- login: odiseo0 + count: 43 + avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 + url: https://github.com/odiseo0 +- login: sinisaos + count: 40 + avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 + url: https://github.com/sinisaos - login: includeamin count: 40 avatarUrl: https://avatars.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4 url: https://github.com/includeamin -- login: sinisaos - count: 39 - avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 - url: https://github.com/sinisaos -- login: luzzodev - count: 37 - avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 - url: https://github.com/luzzodev - login: chbndrhnns count: 37 avatarUrl: https://avatars.githubusercontent.com/u/7534547?v=4 @@ -160,10 +160,10 @@ experts: count: 22 avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 url: https://github.com/nymous -- login: acnebs +- login: connebs count: 22 - avatarUrl: https://avatars.githubusercontent.com/u/9054108?v=4 - url: https://github.com/acnebs + avatarUrl: https://avatars.githubusercontent.com/u/9054108?u=e151d5f545a3395136d711c227c22032fda67cfa&v=4 + url: https://github.com/connebs - login: chrisK824 count: 22 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 @@ -188,14 +188,14 @@ experts: count: 19 avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 url: https://github.com/estebanx64 -- login: sehraramiz - count: 18 - avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 - url: https://github.com/sehraramiz - login: zoliknemet count: 18 avatarUrl: https://avatars.githubusercontent.com/u/22326718?u=31ba446ac290e23e56eea8e4f0c558aaf0b40779&v=4 url: https://github.com/zoliknemet +- login: sehraramiz + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 + url: https://github.com/sehraramiz - login: retnikt count: 18 avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4 @@ -216,6 +216,10 @@ experts: count: 17 avatarUrl: https://avatars.githubusercontent.com/u/28262306?u=e19427d8dc296d6950e9c424adacc92d37496fe9&v=4 url: https://github.com/nkhitrov +- login: alv2017 + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 - login: jonatasoli count: 16 avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4 @@ -224,6 +228,10 @@ experts: count: 16 avatarUrl: https://avatars.githubusercontent.com/u/41964673?u=9f2174f9d61c15c6e3a4c9e3aeee66f711ce311f&v=4 url: https://github.com/dstlny +- login: abhint + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 + url: https://github.com/abhint - login: ceb10n count: 15 avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 @@ -236,100 +244,96 @@ experts: count: 15 avatarUrl: https://avatars.githubusercontent.com/u/33907262?u=2721fb37014d50daf473267c808aa678ecaefe09&v=4 url: https://github.com/simondale00 -- login: ghost - count: 15 - avatarUrl: https://avatars.githubusercontent.com/u/10137?u=b1951d34a583cf12ec0d3b0781ba19be97726318&v=4 - url: https://github.com/ghost -- login: abhint - count: 15 - avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 - url: https://github.com/abhint last_month_experts: -- login: Kludex - count: 14 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 - url: https://github.com/Kludex -- login: YuriiMotov +- login: jgould22 + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 +- login: alv2017 count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 - url: https://github.com/YuriiMotov -- login: sehraramiz - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 - url: https://github.com/sehraramiz + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 - login: luzzodev - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?u=5607ae1ce75c5f54f09500ca854227f7bfd2033b&v=4 url: https://github.com/luzzodev -- login: yokwejuste +- login: YuriiMotov + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov +- login: Kludex count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/71908316?u=592c1e42aa0ee5cb94890e0b863e2acc78cc3bbc&v=4 - url: https://github.com/yokwejuste -- login: alv2017 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 - url: https://github.com/alv2017 -- login: Trinkes - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/9466879?v=4 - url: https://github.com/Trinkes -- login: PREPONDERANCE - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 - url: https://github.com/PREPONDERANCE -- login: nbx3 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/34649527?u=943812f69e0d40adbd3fa1c9b8ef50dd971a2a45&v=4 - url: https://github.com/nbx3 -- login: XiaoXinYo + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 + url: https://github.com/Kludex +- login: JavierSanchezCastro + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +- login: tiangolo + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo +- login: Ale-Cas count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=b3b7cb758997f283c271a581833e407229dab82c&v=4 - url: https://github.com/XiaoXinYo -- login: iloveitaly + avatarUrl: https://avatars.githubusercontent.com/u/64859146?u=d52a6ecf8d83d2927e2ae270bdfcc83495dba8c9&v=4 + url: https://github.com/Ale-Cas +- login: vtgn count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/150855?v=4 - url: https://github.com/iloveitaly + avatarUrl: https://avatars.githubusercontent.com/u/112889052?v=4 + url: https://github.com/vtgn three_months_experts: -- login: luzzodev - count: 33 - avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 - url: https://github.com/luzzodev - login: YuriiMotov count: 31 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov - login: Kludex - count: 24 + count: 25 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex +- login: luzzodev + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?u=5607ae1ce75c5f54f09500ca854227f7bfd2033b&v=4 + url: https://github.com/luzzodev +- login: alv2017 + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 +- login: jgould22 + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 - login: sehraramiz count: 11 avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 url: https://github.com/sehraramiz -- login: estebanx64 - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 - url: https://github.com/estebanx64 -- login: yvallois - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/36999744?v=4 - url: https://github.com/yvallois +- login: JavierSanchezCastro + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +- login: tiangolo + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo - login: yokwejuste count: 4 avatarUrl: https://avatars.githubusercontent.com/u/71908316?u=592c1e42aa0ee5cb94890e0b863e2acc78cc3bbc&v=4 url: https://github.com/yokwejuste -- login: jgould22 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 -- login: alv2017 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 - url: https://github.com/alv2017 - login: viniciusCalcantara count: 3 avatarUrl: https://avatars.githubusercontent.com/u/108818737?u=3d7ffe5808843ee4372f9cc5a559ff1674cf1792&v=4 url: https://github.com/viniciusCalcantara +- login: SobikXexe + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/87701130?v=4 + url: https://github.com/SobikXexe +- login: Ale-Cas + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/64859146?u=d52a6ecf8d83d2927e2ae270bdfcc83495dba8c9&v=4 + url: https://github.com/Ale-Cas +- login: vtgn + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/112889052?v=4 + url: https://github.com/vtgn - login: Trinkes count: 2 avatarUrl: https://avatars.githubusercontent.com/u/9466879?v=4 @@ -344,117 +348,81 @@ three_months_experts: url: https://github.com/nbx3 - login: XiaoXinYo count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=b3b7cb758997f283c271a581833e407229dab82c&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=1eebf5ce25a8067f7bfa6251a24f667be492d9d6&v=4 url: https://github.com/XiaoXinYo -- login: JavierSanchezCastro - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro - login: iloveitaly count: 2 avatarUrl: https://avatars.githubusercontent.com/u/150855?v=4 url: https://github.com/iloveitaly -- login: LincolnPuzey - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/18750802?v=4 - url: https://github.com/LincolnPuzey -- login: Knighthawk-Leo - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/72437494?u=27c68db94a3107b605e603cc136f4ba83f0106d5&v=4 - url: https://github.com/Knighthawk-Leo -- login: gelezo43 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/40732698?u=611f39d3c1d2f4207a590937a78c1f10eed6232c&v=4 - url: https://github.com/gelezo43 -- login: AliYmn - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/18416653?u=98c1fca46c7e4dabe8c39d17b5e55d1511d41cf9&v=4 - url: https://github.com/AliYmn -- login: RichieB2B - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1461970?u=edaa57d1077705244ea5c9244f4783d94ff11f12&v=4 - url: https://github.com/RichieB2B -- login: Synrom - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/30272537?v=4 - url: https://github.com/Synrom -- login: iiotsrc - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/131771119?u=bcaf2559ef6266af70b151b7fda31a1ee3dbecb3&v=4 - url: https://github.com/iiotsrc -- login: Kfir-G - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/57500876?u=0cd29db046a17f12f382d398141319fca7ff230a&v=4 - url: https://github.com/Kfir-G six_months_experts: - login: YuriiMotov - count: 72 + count: 63 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov +- login: luzzodev + count: 48 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?u=5607ae1ce75c5f54f09500ca854227f7bfd2033b&v=4 + url: https://github.com/luzzodev - login: Kludex - count: 40 + count: 48 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex -- login: luzzodev - count: 37 - avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 - url: https://github.com/luzzodev - login: sinisaos - count: 37 + count: 23 avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 url: https://github.com/sinisaos +- login: jgould22 + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 - login: JavierSanchezCastro - count: 16 + count: 17 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro +- login: alv2017 + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 - login: Kfir-G count: 13 avatarUrl: https://avatars.githubusercontent.com/u/57500876?u=0cd29db046a17f12f382d398141319fca7ff230a&v=4 url: https://github.com/Kfir-G -- login: tiangolo - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 - url: https://github.com/tiangolo - login: sehraramiz count: 11 avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 url: https://github.com/sehraramiz - login: ceb10n - count: 10 + count: 7 avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 url: https://github.com/ceb10n - login: estebanx64 count: 7 avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 url: https://github.com/estebanx64 +- login: tiangolo + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo - login: yvallois count: 6 avatarUrl: https://avatars.githubusercontent.com/u/36999744?v=4 url: https://github.com/yvallois -- login: n8sty - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty -- login: TomFaulkner - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/14956620?v=4 - url: https://github.com/TomFaulkner - login: yokwejuste count: 4 avatarUrl: https://avatars.githubusercontent.com/u/71908316?u=592c1e42aa0ee5cb94890e0b863e2acc78cc3bbc&v=4 url: https://github.com/yokwejuste -- login: jgould22 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 -- login: alv2017 +- login: n8sty count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 - url: https://github.com/alv2017 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty - login: viniciusCalcantara count: 3 avatarUrl: https://avatars.githubusercontent.com/u/108818737?u=3d7ffe5808843ee4372f9cc5a559ff1674cf1792&v=4 url: https://github.com/viniciusCalcantara +- login: SobikXexe + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/87701130?v=4 + url: https://github.com/SobikXexe - login: pawelad count: 3 avatarUrl: https://avatars.githubusercontent.com/u/7062874?u=d27dc220545a8401ad21840590a97d474d7101e6&v=4 @@ -467,26 +435,18 @@ six_months_experts: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/48672727?u=34d7b4ade252687d22a27cf53037b735b244bfc1&v=4 url: https://github.com/Isuxiz -- login: bertomaniac - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/10235051?u=14484a96833228a7b29fee4a7916d411c242c4f6&v=4 - url: https://github.com/bertomaniac -- login: PhysicallyActive - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 - url: https://github.com/PhysicallyActive - login: Minibrams count: 3 avatarUrl: https://avatars.githubusercontent.com/u/8108085?u=b028dbc308fa8485e0e2e9402b3d03d8deb22bf9&v=4 url: https://github.com/Minibrams -- login: AIdjis - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/88404339?u=2a80d80b054e9228391e32fb9bb39571509dab6a&v=4 - url: https://github.com/AIdjis -- login: svlandeg - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 - url: https://github.com/svlandeg +- login: Ale-Cas + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/64859146?u=d52a6ecf8d83d2927e2ae270bdfcc83495dba8c9&v=4 + url: https://github.com/Ale-Cas +- login: vtgn + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/112889052?v=4 + url: https://github.com/vtgn - login: Trinkes count: 2 avatarUrl: https://avatars.githubusercontent.com/u/9466879?v=4 @@ -499,26 +459,10 @@ six_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/34649527?u=943812f69e0d40adbd3fa1c9b8ef50dd971a2a45&v=4 url: https://github.com/nbx3 -- login: yanggeorge - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/2434407?v=4 - url: https://github.com/yanggeorge - login: XiaoXinYo count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=b3b7cb758997f283c271a581833e407229dab82c&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=1eebf5ce25a8067f7bfa6251a24f667be492d9d6&v=4 url: https://github.com/XiaoXinYo -- login: pythonweb2 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 - url: https://github.com/pythonweb2 -- login: slafs - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4 - url: https://github.com/slafs -- login: AmirHmZz - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/38752106?u=07f80e451bda00a9492bbc764e49d24ad3ada8cc&v=4 - url: https://github.com/AmirHmZz - login: iloveitaly count: 2 avatarUrl: https://avatars.githubusercontent.com/u/150855?v=4 @@ -527,10 +471,6 @@ six_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/18750802?v=4 url: https://github.com/LincolnPuzey -- login: alejsdev - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 - url: https://github.com/alejsdev - login: Knighthawk-Leo count: 2 avatarUrl: https://avatars.githubusercontent.com/u/72437494?u=27c68db94a3107b605e603cc136f4ba83f0106d5&v=4 @@ -559,10 +499,6 @@ six_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/30272537?v=4 url: https://github.com/Synrom -- login: ecly - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8410422?v=4 - url: https://github.com/ecly - login: iiotsrc count: 2 avatarUrl: https://avatars.githubusercontent.com/u/131771119?u=bcaf2559ef6266af70b151b7fda31a1ee3dbecb3&v=4 @@ -575,14 +511,6 @@ six_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/47495003?u=6e225cb42c688d0cd70e65c6baedb9f5922b1178&v=4 url: https://github.com/jd-solanki -- login: AumGupta - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/86357151?u=7d05aa606c0611a18f4db16cf26361ce10a6e195&v=4 - url: https://github.com/AumGupta -- login: DeoLeung - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/3764720?u=4c222ef513814de4c7fb3736d0a7adf11d953d43&v=4 - url: https://github.com/DeoLeung - login: Reemyos count: 2 avatarUrl: https://avatars.githubusercontent.com/u/44867003?v=4 @@ -591,77 +519,61 @@ six_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/37678115?u=a608798b5bd0034183a9c430ebb42fb266db86ce&v=4 url: https://github.com/deight93 +- login: PhysicallyActive + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive - login: Jkrox count: 2 avatarUrl: https://avatars.githubusercontent.com/u/83181939?u=d6a922d97129f7f3916d6a1c166bc011b3a72b7f&v=4 url: https://github.com/Jkrox -- login: mmzeynalli - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/33568903?u=19efd0c0722730b83a70b7c86c36e5b7d83e07d2&v=4 - url: https://github.com/mmzeynalli -- login: ddahan - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1933516?u=1d200a620e8d6841df017e9f2bb7efb58b580f40&v=4 - url: https://github.com/ddahan - login: jfeaver count: 2 avatarUrl: https://avatars.githubusercontent.com/u/1091338?u=0bcba366447d8fadad63f6705a52d128da4c7ec2&v=4 url: https://github.com/jfeaver -- login: Wurstnase - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8709415?u=f479af475a97aee9a1dab302cfc35d07e9ea245f&v=4 - url: https://github.com/Wurstnase - login: tristan count: 2 avatarUrl: https://avatars.githubusercontent.com/u/1412?u=aab8aaa4cc0f1210ac45fc93873a5909d314c965&v=4 url: https://github.com/tristan -- login: chandanch - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8663552?u=afc484bc0a952c83f1fb6a1583cda443f807cd66&v=4 - url: https://github.com/chandanch -- login: rvishruth - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/79176273?v=4 - url: https://github.com/rvishruth -- login: mattmess1221 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 - url: https://github.com/mattmess1221 one_year_experts: - login: YuriiMotov - count: 223 + count: 214 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov - login: Kludex - count: 81 + count: 66 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex +- login: luzzodev + count: 48 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?u=5607ae1ce75c5f54f09500ca854227f7bfd2033b&v=4 + url: https://github.com/luzzodev +- login: sinisaos + count: 40 + avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 + url: https://github.com/sinisaos - login: JavierSanchezCastro - count: 47 + count: 39 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro - login: jgould22 - count: 42 + count: 35 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 -- login: sinisaos - count: 39 - avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 - url: https://github.com/sinisaos -- login: luzzodev - count: 37 - avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 - url: https://github.com/luzzodev - login: tiangolo count: 24 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 url: https://github.com/tiangolo +- login: alv2017 + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 - login: n8sty - count: 23 + count: 15 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty - login: estebanx64 - count: 19 + count: 15 avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 url: https://github.com/estebanx64 - login: ceb10n @@ -682,10 +594,10 @@ one_year_experts: url: https://github.com/Kfir-G - login: mattmess1221 count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=d22ea18aa8ea688af25a45df306134d593621a44&v=4 url: https://github.com/mattmess1221 - login: hasansezertasan - count: 10 + count: 8 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan - login: AIdjis @@ -704,22 +616,18 @@ one_year_experts: count: 5 avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 url: https://github.com/pythonweb2 -- login: acidjunk - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk - login: gustavosett count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/99373133?u=1739ca547c3d200f1b72450520bce46a97aab184&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/99373133?u=1382fe27034a0179f07cf989f63c4f23017f043c&v=4 url: https://github.com/gustavosett -- login: binbjz - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 - url: https://github.com/binbjz - login: chyok count: 5 avatarUrl: https://avatars.githubusercontent.com/u/32629225?u=3b7c30e8a09426a1b9284f6e8a0ae53a525596bf&v=4 url: https://github.com/chyok +- login: svlandeg + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 + url: https://github.com/svlandeg - login: TomFaulkner count: 4 avatarUrl: https://avatars.githubusercontent.com/u/14956620?v=4 @@ -728,42 +636,34 @@ one_year_experts: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/71908316?u=592c1e42aa0ee5cb94890e0b863e2acc78cc3bbc&v=4 url: https://github.com/yokwejuste -- login: DeoLeung - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/3764720?u=4c222ef513814de4c7fb3736d0a7adf11d953d43&v=4 - url: https://github.com/DeoLeung -- login: flo-at - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 - url: https://github.com/flo-at -- login: GodMoonGoodman +- login: acidjunk count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 - url: https://github.com/GodMoonGoodman + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk - login: bertomaniac count: 4 avatarUrl: https://avatars.githubusercontent.com/u/10235051?u=14484a96833228a7b29fee4a7916d411c242c4f6&v=4 url: https://github.com/bertomaniac -- login: alv2017 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 - url: https://github.com/alv2017 -- login: msehnout - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/9369632?u=8c988f1b008a3f601385a3616f9327820f66e3a5&v=4 - url: https://github.com/msehnout +- login: binbjz + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 + url: https://github.com/binbjz - login: viniciusCalcantara count: 3 avatarUrl: https://avatars.githubusercontent.com/u/108818737?u=3d7ffe5808843ee4372f9cc5a559ff1674cf1792&v=4 url: https://github.com/viniciusCalcantara +- login: SobikXexe + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/87701130?v=4 + url: https://github.com/SobikXexe +- login: DeoLeung + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/3764720?u=4c222ef513814de4c7fb3736d0a7adf11d953d43&v=4 + url: https://github.com/DeoLeung - login: pawelad count: 3 avatarUrl: https://avatars.githubusercontent.com/u/7062874?u=d27dc220545a8401ad21840590a97d474d7101e6&v=4 url: https://github.com/pawelad -- login: ThirVondukr - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 - url: https://github.com/ThirVondukr - login: dbfreem count: 3 avatarUrl: https://avatars.githubusercontent.com/u/9778569?u=f2f1e9135b5e4f1b0c6821a548b17f97572720fc&v=4 @@ -772,10 +672,6 @@ one_year_experts: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/48672727?u=34d7b4ade252687d22a27cf53037b735b244bfc1&v=4 url: https://github.com/Isuxiz -- login: angely-dev - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 - url: https://github.com/angely-dev - login: deight93 count: 3 avatarUrl: https://avatars.githubusercontent.com/u/37678115?u=a608798b5bd0034183a9c430ebb42fb266db86ce&v=4 @@ -792,42 +688,70 @@ one_year_experts: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 url: https://github.com/ryanisn -- login: svlandeg - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 - url: https://github.com/svlandeg - login: alexandercronin count: 3 avatarUrl: https://avatars.githubusercontent.com/u/8014288?u=69580504c51a0cdd756fc47b23bb7f404bd694e7&v=4 url: https://github.com/alexandercronin -- login: aanchlia - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 - url: https://github.com/aanchlia -- login: chrisK824 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 - login: omarcruzpantoja count: 3 avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 url: https://github.com/omarcruzpantoja -- login: ahmedabdou14 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=d87b866e7c1db970d6f8e8031643818349b046d5&v=4 - url: https://github.com/ahmedabdou14 +- login: Wyko + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/467094?v=4 + url: https://github.com/Wyko +- login: ddahan + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1933516?u=1d200a620e8d6841df017e9f2bb7efb58b580f40&v=4 + url: https://github.com/ddahan +- login: Ale-Cas + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/64859146?u=d52a6ecf8d83d2927e2ae270bdfcc83495dba8c9&v=4 + url: https://github.com/Ale-Cas +- login: Trolldemorted + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/10261186?v=4 + url: https://github.com/Trolldemorted +- login: vtgn + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/112889052?v=4 + url: https://github.com/vtgn +- login: SDAravind + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/72403396?v=4 + url: https://github.com/SDAravind +- login: slafs + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4 + url: https://github.com/slafs +- login: redb0 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/30475117?v=4 + url: https://github.com/redb0 +- login: pedroconceicao + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/32837064?u=5a0e6559bc391442629a28b6923790b54deb4464&v=4 + url: https://github.com/pedroconceicao +- login: msukmanowsky + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/362755?u=782e6bf5b9f0356c3f74b4d894fda9f179252086&v=4 + url: https://github.com/msukmanowsky +- login: rishabhc32 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/15983714?u=147776509107af8bdf099223e1840d3f40f944da&v=4 + url: https://github.com/rishabhc32 +- login: meower1 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/109747197?u=0a5cc2a6ae74e558f0afc2874da85132e5953d8b&v=4 + url: https://github.com/meower1 - login: Trinkes count: 2 avatarUrl: https://avatars.githubusercontent.com/u/9466879?v=4 url: https://github.com/Trinkes -- login: Leon0824 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1922026?v=4 - url: https://github.com/Leon0824 -- login: CarlosOliveira-23 +- login: anantgupta129 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/102637302?u=cf350a4db956f30cbb2c27d3be0d15c282e32b14&v=4 - url: https://github.com/CarlosOliveira-23 + avatarUrl: https://avatars.githubusercontent.com/u/66518357?u=6e25dcd84638f17d2c6df5dc26f07fd7c6dc118e&v=4 + url: https://github.com/anantgupta129 - login: nbx3 count: 2 avatarUrl: https://avatars.githubusercontent.com/u/34649527?u=943812f69e0d40adbd3fa1c9b8ef50dd971a2a45&v=4 @@ -838,16 +762,8 @@ one_year_experts: url: https://github.com/yanggeorge - login: XiaoXinYo count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=b3b7cb758997f283c271a581833e407229dab82c&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=1eebf5ce25a8067f7bfa6251a24f667be492d9d6&v=4 url: https://github.com/XiaoXinYo -- login: anantgupta129 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/66518357?u=6e25dcd84638f17d2c6df5dc26f07fd7c6dc118e&v=4 - url: https://github.com/anantgupta129 -- login: slafs - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4 - url: https://github.com/slafs - login: monchin count: 2 avatarUrl: https://avatars.githubusercontent.com/u/18521800?v=4 @@ -860,11 +776,3 @@ one_year_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/150855?v=4 url: https://github.com/iloveitaly -- login: msukmanowsky - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/362755?u=782e6bf5b9f0356c3f74b4d894fda9f179252086&v=4 - url: https://github.com/msukmanowsky -- login: shurshilov - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/11828278?u=6bcadc5ce4f2f56a514331c9f68eb987d4afe29a&v=4 - url: https://github.com/shurshilov From 685969141934670994c58799dde27cc6e4aca45d Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 19 Mar 2025 11:34:07 +0000 Subject: [PATCH 905/932] =?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 [skip ci] --- 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 c900dc918..681f9237c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 👥 Update FastAPI People - Experts. PR [#13493](https://github.com/fastapi/fastapi/pull/13493) by [@tiangolo](https://github.com/tiangolo). + ### Translations * 🌐 Add Korean translation for `docs/ko/docs/tutorial/security/oauth2-jwt.md`. PR [#13333](https://github.com/fastapi/fastapi/pull/13333) by [@yes0ng](https://github.com/yes0ng). From 7ab1b9edcc0a464efe46fefed845dd2df9996473 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 19 Mar 2025 12:54:33 +0100 Subject: [PATCH 906/932] =?UTF-8?q?=E2=AC=86=20Bump=20pydantic-ai=20from?= =?UTF-8?q?=200.0.15=20to=200.0.30=20(#13438)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pydantic-ai](https://github.com/pydantic/pydantic-ai) from 0.0.15 to 0.0.30. - [Release notes](https://github.com/pydantic/pydantic-ai/releases) - [Changelog](https://github.com/pydantic/pydantic-ai/blob/main/docs/message-history.md) - [Commits](https://github.com/pydantic/pydantic-ai/compare/v0.0.15...v0.0.30) --- updated-dependencies: - dependency-name: pydantic-ai dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-translations.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-translations.txt b/requirements-translations.txt index a8f8a02d7..7a2a8004e 100644 --- a/requirements-translations.txt +++ b/requirements-translations.txt @@ -1 +1 @@ -pydantic-ai==0.0.15 +pydantic-ai==0.0.30 From 90d52cfa16edada8c95f0ef4f2979acc9984b230 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 19 Mar 2025 11:54:58 +0000 Subject: [PATCH 907/932] =?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 [skip ci] --- 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 681f9237c..10a55f550 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -18,6 +18,7 @@ hide: ### Internal +* ⬆ Bump pydantic-ai from 0.0.15 to 0.0.30. PR [#13438](https://github.com/fastapi/fastapi/pull/13438) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump sqlmodel from 0.0.22 to 0.0.23. PR [#13437](https://github.com/fastapi/fastapi/pull/13437) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump black from 24.10.0 to 25.1.0. PR [#13436](https://github.com/fastapi/fastapi/pull/13436) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump ruff to 0.9.4. PR [#13299](https://github.com/fastapi/fastapi/pull/13299) by [@dependabot[bot]](https://github.com/apps/dependabot). From f806e0380767a8d89e7a64dc3ccb41e3535a5961 Mon Sep 17 00:00:00 2001 From: k94-ishi <32672580+k94-ishi@users.noreply.github.com> Date: Wed, 19 Mar 2025 21:22:33 +0900 Subject: [PATCH 908/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/virtual-environments.md`=20(#13304)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ja/docs/virtual-environments.md | 831 +++++++++++++++++++++++++++ 1 file changed, 831 insertions(+) create mode 100644 docs/ja/docs/virtual-environments.md diff --git a/docs/ja/docs/virtual-environments.md b/docs/ja/docs/virtual-environments.md new file mode 100644 index 000000000..791cf64a8 --- /dev/null +++ b/docs/ja/docs/virtual-environments.md @@ -0,0 +1,831 @@ +# 仮想環境 + +Pythonプロジェクトの作業では、**仮想環境**(または類似の仕組み)を使用し、プロジェクトごとにインストールするパッケージを分離するべきでしょう。 + +/// info | 情報 + +もし、仮想環境の概要や作成方法、使用方法について既にご存知なら、このセクションをスキップすることができます。🤓 + +/// + +/// tip | 豆知識 + +**仮想環境**は、**環境変数**とは異なります。 + +**環境変数**は、プログラムが使用できるシステム内の変数です。 + +**仮想環境**は、ファイルをまとめたディレクトリのことです。 + +/// + +/// info | 情報 +このページでは、**仮想環境**の使用方法と、そのはたらきについて説明します。 + +もし**すべてを管理するツール**(Pythonのインストールも含む)を導入する準備ができているなら、uv をお試しください。 + +/// + +## プロジェクトの作成 + +まず、プロジェクト用のディレクトリを作成します。 + +私は通常 home/user ディレクトリの中に `code` というディレクトリを用意していて、プロジェクトごとに1つのディレクトリをその中に作成しています。 + +
    + +```console +// Go to the home directory +$ cd +// Create a directory for all your code projects +$ mkdir code +// Enter into that code directory +$ cd code +// Create a directory for this project +$ mkdir awesome-project +// Enter into that project directory +$ cd awesome-project +``` + +
    + +## 仮想環境の作成 + +Pythonプロジェクトでの**初めての**作業を開始する際には、**プロジェクト内**に仮想環境を作成してください。 + +/// tip | 豆知識 + +これを行うのは、**プロジェクトごとに1回だけ**です。作業のたびに行う必要はありません。 + +/// + +//// tab | `venv` + +仮想環境を作成するには、Pythonに付属している `venv` モジュールを使用できます。 + +
    + +```console +$ python -m venv .venv +``` + +
    + +/// details | このコマンドの意味 + +- `python` : `python` というプログラムを呼び出します +- `-m` : モジュールをスクリプトとして呼び出します。どのモジュールを呼び出すのか、この次に指定します +- `venv` : 通常Pythonに付随してインストールされる `venv`モジュールを使用します +- `.venv` : 仮想環境を`.venv`という新しいディレクトリに作成します + +/// + +//// + +//// tab | `uv` + +もし `uv` をインストール済みなら、仮想環境を作成するために `uv` を使うこともできます。 + +
    + +```console +$ uv venv +``` + +
    + +/// tip | 豆知識 + +デフォルトでは、 `uv` は `.venv` というディレクトリに仮想環境を作成します。 + +ただし、追加の引数にディレクトリ名を与えてカスタマイズすることもできます。 + +/// + +//// + +このコマンドは `.venv` というディレクトリに新しい仮想環境を作成します。 + +/// details | `.venv` またはその他の名前 + +仮想環境を別のディレクトリに作成することも可能ですが、 `.venv` と名付けるのが一般的な慣習です。 + +/// + +## 仮想環境の有効化 + +実行されるPythonコマンドやインストールされるパッケージが新しく作成した仮想環境を使用するよう、その仮想環境を有効化しましょう。 + +/// tip | 豆知識 + +そのプロジェクトの作業で**新しいターミナルセッション**を開始する際には、**毎回**有効化が必要です。 + +/// + +//// tab | Linux, macOS + +
    + +```console +$ source .venv/bin/activate +``` + +
    + +//// + +//// tab | Windows PowerShell + +
    + +```console +$ .venv\Scripts\Activate.ps1 +``` + +
    + +//// + +//// tab | Windows Bash + +もしWindowsでBashを使用している場合 (Git Bashなど): + +
    + +```console +$ source .venv/Scripts/activate +``` + +
    + +//// + +/// tip | 豆知識 + +**新しいパッケージ**を仮想環境にインストールするときには、再度**有効化**してください。 + +こうすることで、そのパッケージがインストールした**ターミナル(CLI)プログラム**を使用する場合に、仮想環境内のものが確実に使われ、グローバル環境にインストールされている別のもの(おそらく必要なものとは異なるバージョン)を誤って使用することを防ぎます。 + +/// + +## 仮想環境が有効であることを確認する + +仮想環境が有効である(前のコマンドが正常に機能した)ことを確認します。 + +/// tip | 豆知識 + +これは**任意**ですが、すべてが期待通りに機能し、意図した仮想環境を使用していることを**確認する**良い方法です。 + +/// + +//// tab | Linux, macOS, Windows Bash + +
    + +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
    + +`.venv/bin/python` にある `python` バイナリが、プロジェクト(この場合は `awesome-project` )内に表示されていれば、正常に動作しています 🎉。 + +//// + +//// tab | Windows PowerShell + +
    + +``` console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
    + +`.venv\Scripts\python` にある `python` バイナリが、プロジェクト(この場合は `awesome-project` )内に表示されていれば、正常に動作しています 🎉。 + +//// + +## `pip` をアップグレードする + +/// tip | 豆知識 + +もし `uv` を使用している場合は、 `pip` の代わりに `uv` を使ってインストールを行うため、 `pip` をアップグレードする必要はありません 😎。 + +/// + +もしパッケージのインストールに `pip`(Pythonに標準で付属しています)を使用しているなら、 `pip` を最新バージョンに**アップグレード**しましょう。 + +パッケージのインストール中に発生する想定外のエラーの多くは、最初に `pip` をアップグレードしておくだけで解決されます。 + +/// tip | 豆知識 + +通常、これは仮想環境を作成した直後に**一度だけ**実行します。 + +/// + +仮想環境が有効であることを(上で説明したコマンドで)確認し、アップグレードを実行しましょう: + +
    + +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
    + +## `.gitignore` を追加する + +**Git**を使用している場合(使用するべきでしょう)、 `.gitignore` ファイルを追加して、 `.venv` 内のあらゆるファイルをGitの管理対象から除外します。 + +/// tip | 豆知識 + +もし `uv` を使用して仮想環境を作成した場合、すでにこの作業は済んでいるので、この手順をスキップできます 😎。 + +/// + +/// tip | 豆知識 + +これも、仮想環境を作成した直後に**一度だけ**実行します。 + +/// + +
    + +```console +$ echo "*" > .venv/.gitignore +``` + +
    + +/// details | このコマンドの意味 + +- `echo "*"` : ターミナルに `*` というテキストを「表示」しようとします。(次の部分によってその動作が少し変わります) +- `>` : `>` の左側のコマンドがターミナルに表示しようとする内容を、ターミナルには表示せず、 `>` の右側のファイルに書き込みます。 +- `.gitignore` : `*` を書き込むファイル名。 + +ここで、Gitにおける `*` は「すべて」を意味するので、このコマンドによって `.venv` ディレクトリ内のすべてがGitに無視されるようになります。 + +このコマンドは以下のテキストを持つ `.gitignore` ファイルを作成します: + +```gitignore +* +``` + +/// + +## パッケージのインストール + +仮想環境を有効化した後、その中でパッケージをインストールできます。 + +/// tip | 豆知識 + +プロジェクトに必要なパッケージをインストールまたはアップグレードする場合、これを**一度**実行します。 + +もし新しいパッケージを追加したり、バージョンをアップグレードする必要がある場合は、もう**一度この手順を繰り返し**ます。 + +/// + +### パッケージを直接インストールする + +急いでいて、プロジェクトのパッケージ要件を宣言するファイルを使いたくない場合、パッケージを直接インストールできます。 + +/// tip | 豆知識 + +プログラムが必要とするパッケージとバージョンをファイル(例えば `requirements.txt` や `pyproject.toml` )に記載しておくのは、(とても)良い考えです。 + +/// + +//// tab | `pip` + +
    + +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
    + +//// + +//// tab | `uv` + +もし `uv` を使用できるなら: + +
    + +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
    + +//// + +### `requirements.txt` からインストールする + +もし `requirements.txt` があるなら、パッケージのインストールに使用できます。 + +//// tab | `pip` + +
    + +```console +$ pip install -r requirements.txt +---> 100% +``` + +
    + +//// + +//// tab | `uv` + +もし `uv` を使用できるなら: + +
    + +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
    + +//// + +/// details | `requirements.txt` + +パッケージが記載された `requirements.txt` は以下のようになっています: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## プログラムを実行する + +仮想環境を有効化した後、プログラムを実行できます。この際、仮想環境内のPythonと、そこにインストールしたパッケージが使用されます。 + +
    + +```console +$ python main.py + +Hello World +``` + +
    + +## エディタの設定 + +プロジェクトではおそらくエディタを使用するでしょう。コード補完やインラインエラーの表示ができるように、作成した仮想環境をエディタでも使えるよう設定してください。(多くの場合、自動検出されます) + +設定例: + +* VS Code +* PyCharm + +/// tip | 豆知識 + +この設定は通常、仮想環境を作成した際に**一度だけ**行います。 + +/// + +## 仮想環境の無効化 + +プロジェクトの作業が終了したら、その仮想環境を**無効化**できます。 + +
    + +```console +$ deactivate +``` + +
    + +これにより、 `python` コマンドを実行しても、そのプロジェクト用(のパッケージがインストールされた)仮想環境から `python` プログラムを呼び出そうとはしなくなります。 + +## 作業準備完了 + +ここまでで、プロジェクトの作業を始める準備が整いました。 + +/// tip | 豆知識 + +上記の内容を理解したいですか? + +もしそうなら、以下を読み進めてください。👇🤓 + +/// + +## なぜ仮想環境? + +FastAPIを使った作業をするには、 [Python](https://www.python.org/) のインストールが必要です。 + +それから、FastAPIや、使用したいその他の**パッケージ**を**インストール**する必要があります。 + +パッケージをインストールするには、通常、Python に付属する `pip` コマンド (または同様の代替コマンド) を使用します。 + +ただし、`pip` を直接使用すると、パッケージは**グローバルなPython環境**(OS全体にインストールされたPython環境)にインストールされます。 + +### 問題点 + +では、グローバルPython環境にパッケージをインストールすることの問題点は何でしょうか? + +ある時点で、あなたは**異なるパッケージ**に依存する多くのプログラムを書くことになるでしょう。そして、これらの中には同じパッケージの**異なるバージョン**に依存するものも出てくるでしょう。😱 + +例えば、 `philosophers-stone` (賢者の石)というプロジェクトを作成するとします。このプログラムは **`harry` (ハリー)というパッケージのバージョン `1`**に依存しています。そのため、 `harry` (ハリー)をインストールする必要があります。 + +```mermaid +flowchart LR + stone(philosophers-stone) -->|requires| harry-1[harry v1] +``` + +それから、 `prisoner-of-azkaban` (アズカバンの囚人)という別のプロジェクトを作成したとします。このプロジェクトも `harry` (ハリー)に依存していますが、**`harry` (ハリー)のバージョン `3`**が必要です。 + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3] +``` + +しかし、ここで問題になるのは、もしローカルの**仮想環境**ではなくグローバル(環境)にパッケージをインストールするなら、 `harry` (ハリー)のどのバージョンをインストールするか選ばないといけないことです。 + +例えば、 `philosophers-stone` (賢者の石)を実行するには、まず `harry` (ハリー)のバージョン `1` をインストールする必要があります: + +
    + +```console +$ pip install "harry==1" +``` + +
    + +これにより、`harry` (ハリー)バージョン1がグローバルなPython環境にインストールされます。 + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -->|requires| harry-1 + end +``` + +しかし、 `prisoner-of-azkaban` (アズカバンの囚人)を実行したい場合は、`harry` (ハリー)のバージョン `1` をアンインストールし、`harry` (ハリー)のバージョン `3` をインストールし直す必要があります。(あるいは、単に`harry` (ハリー)のバージョン `3` をインストールすることで、自動的にバージョン `1` がアンインストールされます) + +
    + +```console +$ pip install "harry==3" +``` + +
    + +このようにして、グローバル環境への `harry` (ハリー)のバージョン `3` のインストールが完了します。 + +それから、 `philosophers-stone` (賢者の石)を再び実行しようとすると、このプログラムは `harry` (ハリー)のバージョン `1` が必要なため、**動作しなくなる**可能性があります。 + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --> |requires| harry-3 + end +``` + +/// tip | 豆知識 + +Pythonのパッケージでは、**新しいバージョン**で**互換性を損なう変更を避ける**よう努めるのが一般的ですが、それでも注意が必要です。すべてが正常に動作することをテストで確認してから、意図的に指定して新しいバージョンをインストールするのが良いでしょう。 + +/// + +あなたのすべての**プロジェクトが依存している**、**多数の**他の**パッケージ**が上記の問題を抱えていると想像してください。これは管理が非常に困難です。そして、**互換性のないバージョン**のパッケージを使ってプロジェクトを実行し、なぜ動作しないのか分からなくなるでしょう。 + +また、使用しているOS(Linux、Windows、macOS など)によっては、Pythonがすでにインストールされていることがあります。この場合、特定のバージョンのパッケージが**OSの動作に必要である**ことがあります。グローバル環境にパッケージをインストールすると、OSに付属するプログラムを**壊してしまう**可能性があります。 + +## パッケージのインストール先 + +Pythonをインストールしたとき、ファイルを含んだいくつかのディレクトリが作成されます。 + +これらの中には、インストールされたパッケージを保存するためのものもあります。 + +以下のコマンドを実行したとき: + +
    + +```console +// Don't run this now, it's just an example 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
    + +FastAPIのコードを含む圧縮ファイルが、通常は [PyPI](https://pypi.org/project/fastapi/) からダウンロードされます。 + +また、FastAPIが依存する他のパッケージも**ダウンロード**されます。 + +それから、これらのファイルは**解凍**され、コンピュータのあるディレクトリに配置されます。 + +デフォルトでは、これらのファイルはPythonのインストール時に作成されるディレクトリ、つまり**グローバル環境**に配置されます。 + +## 仮想環境とは + +すべてのパッケージをグローバル環境に配置することによって生じる問題の解決策は、作業する**プロジェクトごとの仮想環境**を使用することです。 + +仮想環境は**ディレクトリ**であり、グローバル環境と非常に似ていて、一つのプロジェクトで使う特定のパッケージ群をインストールできる場所です。 + +このようにして、それぞれのプロジェクトが独自の仮想環境(`.venv` ディレクトリ)に独自のパッケージ群を持つことができます。 + +```mermaid +flowchart TB + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) --->|requires| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --->|requires| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## 仮想環境の有効化とは + +仮想環境を有効にしたとき、例えば次のコマンドを実行した場合を考えます: + +//// tab | Linux, macOS + +
    + +```console +$ source .venv/bin/activate +``` + +
    + +//// + +//// tab | Windows PowerShell + +
    + +```console +$ .venv\Scripts\Activate.ps1 +``` + +
    + +//// + +//// tab | Windows Bash + +あるいは、WindowsでBashを使用している場合 (Git Bashなど): + +
    + +```console +$ source .venv/Scripts/activate +``` + +
    + +//// + +これによって、いくつかの [環境変数](environment-variables.md){.internal-link target=_blank} が作成・修正され、次に実行されるコマンドで使用できるようになります。 + +これらの環境変数のひとつに、 `PATH` 変数があります。 + +/// tip | 豆知識 + +`PATH` 変数についての詳細は [環境変数](environment-variables.md#path環境変数){.internal-link target=_blank} を参照してください。 + +/// + +仮想環境を有効にすると、その仮想環境のパス `.venv/bin` (LinuxとmacOS)、あるいは `.venv\Scripts` (Windows)が `PATH` 変数に追加されます。 + +その環境を有効にする前の `PATH` 変数が次のようになっているとします。 + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +これは、OSが以下のディレクトリ中でプログラムを探すことを意味します: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +これは、OSが以下のディレクトリ中でプログラムを探すことを意味します: + +* `C:\Windows\System32` + +//// + +仮想環境を有効にすると、 `PATH` 変数は次のようになります。 + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +これは、OSが他のディレクトリを探すより前に、最初に以下のディレクトリ中でプログラムを探し始めることを意味します: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +そのため、ターミナルで `python` と入力した際に、OSはPythonプログラムを以下のパスで発見し、使用します。 + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +これは、OSが他のディレクトリを探すより前に、最初に以下のディレクトリ中でプログラムを探し始めることを意味します: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +そのため、ターミナルで `python` と入力した際に、OSはPythonプログラムを以下のパスで発見し、使用します。 + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +//// + +重要な点は、仮想環境のパスを `PATH` 変数の**先頭**に配置することです。OSは利用可能な他のPythonを見つけるより**前に**、この仮想環境のPythonを見つけるようになります。このようにして、 `python` を実行したときに、他の `python` (例えばグローバル環境の `python` )ではなく、**その仮想環境の**Pythonを使用するようになります。 + +仮想環境を有効にして変更されることは他にもありますが、これが最も重要な変更のひとつです。 + +## 仮想環境の確認 + +仮想環境が有効かどうか、例えば次のように確認できます。: + +//// tab | Linux, macOS, Windows Bash + +
    + +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
    + +//// + +//// tab | Windows PowerShell + +
    + +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
    + +//// + +これは、使用される `python` プログラムが**その仮想環境の**ものであることを意味します。 + +LinuxやmacOSでは `which` を、Windows PowerShellでは `Get-Command` を使用します。 + +このコマンドの動作は、 `PATH`変数に設定された**それぞれのパスを順に**確認していき、呼ばれている `python` プログラムを探します。そして、見つかり次第そのプログラムへの**パスを表示します**。 + +最も重要なことは、 `python` が呼ばれたときに、まさにこのコマンドで確認した "`python`" が実行されることです。 + +こうして、自分が想定通りの仮想環境にいるかを確認できます。 + +/// tip | 豆知識 + +ある仮想環境を有効にし、そのPythonを使用したまま**他のプロジェクトに移動して**しまうことは簡単に起こり得ます。 + +そして、その第二のプロジェクトは動作しないでしょう。なぜなら別のプロジェクトの仮想環境の**誤ったPython**を使用しているからです。 + +そのため、どの `python` が使用されているのか確認できることは役立ちます。🤓 + +/// + +## なぜ仮想環境を無効化するのか + +例えば、`philosophers-stone` (賢者の石)というプロジェクトで作業をしていて、**その仮想環境を有効にし**、必要なパッケージをインストールしてその環境内で作業を進めているとします。 + +それから、**別のプロジェクト**、 `prisoner-of-azkaban` (アズカバンの囚人)に取り掛かろうとします。 + +そのプロジェクトディレクトリへ移動します: + +
    + +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
    + +もし `philosophers-stone` (賢者の石)の仮想環境を無効化していないと、`python` を実行したとき、 ターミナルは `philosophers-stone` (賢者の石)のPythonを使用しようとします。 + +
    + +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// Error importing sirius, it's not installed 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
    + +しかし、その仮想環境を無効化し、 `prisoner-of-azkaban` (アズカバンの囚人)のための新しい仮想環境を有効にすれば、 `python` を実行したときに `prisoner-of-azkaban` (アズカバンの囚人)の仮想環境の Python が使用されるようになります。 + +
    + +```console +$ cd ~/code/prisoner-of-azkaban + +// You don't need to be in the old directory to deactivate, you can do it wherever you are, even after going to the other project 😎 +$ deactivate + +// Activate the virtual environment in prisoner-of-azkaban/.venv 🚀 +$ source .venv/bin/activate + +// Now when you run python, it will find the package sirius installed in this virtual environment ✨ +$ python main.py + +I solemnly swear 🐺 +``` + +
    + +## 代替手段 + +これは、あらゆる仕組みを**根本から**学ぶためのシンプルな入門ガイドです。 + +仮想環境、パッケージの依存関係(requirements)、プロジェクトの管理には、多くの**代替手段**があります。 + +準備が整い、パッケージの依存関係、仮想環境など**プロジェクト全体の管理**ツールを使いたいと考えたら、uv を試してみることをおすすめします。 + +`uv` では以下のような多くのことができます: + +* 異なるバージョンも含めた**Python のインストール** +* プロジェクトごとの**仮想環境**の管理 +* **パッケージ**のインストール +* プロジェクトのパッケージの**依存関係やバージョン**の管理 +* パッケージとそのバージョンの、依存関係を含めた**厳密な**組み合わせを保持し、これによって、本番環境で、開発環境と全く同じようにプロジェクトを実行できる(これは**locking**と呼ばれます) +* その他のさまざまな機能 + +## まとめ + +ここまで読みすべて理解したなら、世間の多くの開発者と比べて、仮想環境について**あなたはより多くのことを知っています**。🤓 + +これらの詳細を知ることは、将来、複雑に見える何かのデバッグにきっと役立つでしょう。しかし、その頃には、あなたは**そのすべての動作を根本から**理解しているでしょう。😎 From 7e33df505afd89ab235b8e8abdf08316e1a5bc78 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 19 Mar 2025 12:22:56 +0000 Subject: [PATCH 909/932] =?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 [skip ci] --- 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 10a55f550..f4d8a9917 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/virtual-environments.md`. PR [#13304](https://github.com/fastapi/fastapi/pull/13304) by [@k94-ishi](https://github.com/k94-ishi). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/security/oauth2-jwt.md`. PR [#13333](https://github.com/fastapi/fastapi/pull/13333) by [@yes0ng](https://github.com/yes0ng). * 🌐 Add Vietnamese translation for `docs/vi/docs/deployment/cloud.md`. PR [#13407](https://github.com/fastapi/fastapi/pull/13407) by [@ptt3199](https://github.com/ptt3199). From f9f1d93c584843e700522c26fb768eb0ce110f4d Mon Sep 17 00:00:00 2001 From: Valentyn Date: Wed, 19 Mar 2025 13:03:13 -0400 Subject: [PATCH 910/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/tutorial/header-param-models.md`=20?= =?UTF-8?q?page=20(#13461)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/uk/docs/tutorial/header-param-models.md | 58 ++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 docs/uk/docs/tutorial/header-param-models.md diff --git a/docs/uk/docs/tutorial/header-param-models.md b/docs/uk/docs/tutorial/header-param-models.md new file mode 100644 index 000000000..6f7b0bdae --- /dev/null +++ b/docs/uk/docs/tutorial/header-param-models.md @@ -0,0 +1,58 @@ +# Моделі Параметрів Заголовків + +Якщо у Вас є група пов’язаних параметрів заголовків, Ви можете створити **Pydantic модель** для їх оголошення. + +Це дозволить Вам повторно **використовувати модель** в **різних місцях**, а також оголосити валідації та метадані для всіх параметрів одночасно. 😎 + +/// note | Нотатки + +Ця можливість підтримується починаючи з версії FastAPI `0.115.0`. 🤓 + +/// + +## Параметри Заголовків з Використанням Pydantic Model + +Оголосіть потрібні **параметри заголовків** у **Pydantic моделі**, а потім оголосіть параметр як `Header`: + +{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *} + +FastAPI буде витягувати дані для кожного поля з заголовків у запиті та передавати їх у створену Вами Pydantic модель. + +**FastAPI** буде **витягувати** дані для **кожного поля** з **заголовків** у запиті та передавати їх у створену Вами Pydantic модель. + +## Перевірка в Документації + +Ви можете побачити необхідні заголовки в інтерфейсі документації за адресою `/docs`: + +
    + +
    + +## Заборона Додаткових Заголовків + +У деяких особливих випадках (ймовірно, не дуже поширених) Ви можете захотіти **обмежити** заголовки, які хочете отримати. + +Ви можете використати конфігурацію моделі Pydantic, щоб `заборонити` будь-які `додаткові` поля: + +{* ../../docs_src/header_param_models/tutorial002_an_py310.py hl[10] *} + +Якщо клієнт спробує надіслати **додаткові заголовки**, він отримає **помилку** у відповіді. + +Наприклад, якщо клієнт спробує надіслати заголовок `tool` зі значенням `plumbus`, він отримає **помилку** з повідомленням про те, що параметр заголовка `tool` не дозволений: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["header", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ] +} +``` + +## Підсумок + +Ви можете використовувати **Pydantic моделі** для оголошення **заголовків** у **FastAPI**. 😎 From f077c17e1e5d3b5ccd1ac43f9228f576b0401095 Mon Sep 17 00:00:00 2001 From: Valentyn Date: Wed, 19 Mar 2025 13:03:38 -0400 Subject: [PATCH 911/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/tutorial/cookie-param-models.md`=20?= =?UTF-8?q?page=20(#13460)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/uk/docs/tutorial/cookie-param-models.md | 76 ++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 docs/uk/docs/tutorial/cookie-param-models.md diff --git a/docs/uk/docs/tutorial/cookie-param-models.md b/docs/uk/docs/tutorial/cookie-param-models.md new file mode 100644 index 000000000..f070b6ac8 --- /dev/null +++ b/docs/uk/docs/tutorial/cookie-param-models.md @@ -0,0 +1,76 @@ +# Моделі для Cookie-параметрів + +Якщо у Вас є група **cookies** параметрів, які пов'язані між собою, Ви можете створити **Pydantic-модель**, щоб оголосити їх. 🍪 + +Це дозволить Вам повторно **використовувати модель** у **різних місцях**, а також оголосити валідацію та метадані для всіх параметрів одночасно. 😎 + +/// note | Нотатки + +Це підтримується з версії FastAPI `0.115.0`. 🤓 + +/// + +/// tip | Порада + +Ця ж техніка застосовується до `Query`, `Cookie`, та `Header`. 😎 + +/// + +## Cookie з Pydantic-моделлю + +Оголосіть **cookie-параметри**, які Вам потрібні, у **Pydantic-моделі**, а потім оголосіть параметр як `Cookie`: + +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} + +**FastAPI** буде **витягувати** дані для **кожного поля** з **cookie** параметрів, отриманих у запиті, і передавати Вам Pydantic-модель, яку Ви визначили. + +## Перевірка у документації + +Ви можете побачити визначені cookie в інтерфейсі документації за адресою `/docs`: + +
    + +
    + +/// info | Інформація + +Майте на увазі, що оскільки **браузери обробляють cookie** особливим чином і "за лаштунками", вони **не** дозволяють **JavaScript** легко з ними працювати. + +Якщо Ви зайдете до **інтерфейсу документації API** за адресою `/docs`, Ви зможете побачити **документацію** для cookie у Ваших **операціях шляху**. + +Але навіть якщо Ви заповните дані й натиснете "Execute", оскільки інтерфейс документації працює з **JavaScript**, cookie не будуть відправлені, і Ви побачите **помилку**, ніби Ви не ввели жодних значень. + +/// + +## Заборона додаткових cookie + +У деяких спеціальних випадках (ймовірно, не дуже поширених) Ви можете захотіти **обмежити** список cookie, які хочете отримувати. + +Ваша API тепер має можливість контролювати власну згоду на cookie. 🤪🍪 + +Ви можете використовувати налаштування моделі Pydantic, щоб `заборонити` будь-які `додаткові` поля: + +{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *} + +Якщо клієнт спробує надіслати якісь **додаткові cookie**, він отримає відповідь з **помилкою**. + +Бідні банери cookie, які так старанно намагаються отримати Вашу згоду, щоб API її відхилила. 🍪 + +Наприклад, якщо клієнт спробує надіслати cookie `santa_tracker` зі значенням `good-list-please`, він отримає відповідь з помилкою, яка повідомить, що cookie `santa_tracker` не дозволено: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "santa_tracker"], + "msg": "Extra inputs are not permitted", + "input": "good-list-please", + } + ] +} +``` + +## Підсумок + +Ви можете використовувати **Pydantic-моделі** для оголошення cookie у FastAPI. 😎 From f977da6ae0e43d3c29fba57095777e596ca32d3e Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 19 Mar 2025 17:03:40 +0000 Subject: [PATCH 912/932] =?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 [skip ci] --- 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 f4d8a9917..bde2306b9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/header-param-models.md` page. PR [#13461](https://github.com/fastapi/fastapi/pull/13461) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Japanese translation for `docs/ja/docs/virtual-environments.md`. PR [#13304](https://github.com/fastapi/fastapi/pull/13304) by [@k94-ishi](https://github.com/k94-ishi). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/security/oauth2-jwt.md`. PR [#13333](https://github.com/fastapi/fastapi/pull/13333) by [@yes0ng](https://github.com/yes0ng). * 🌐 Add Vietnamese translation for `docs/vi/docs/deployment/cloud.md`. PR [#13407](https://github.com/fastapi/fastapi/pull/13407) by [@ptt3199](https://github.com/ptt3199). From e4c1dd799d5b1a1c4697bbc5f923dff701d2ffff Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 19 Mar 2025 17:04:06 +0000 Subject: [PATCH 913/932] =?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 [skip ci] --- 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 bde2306b9..f63d240fe 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/cookie-param-models.md` page. PR [#13460](https://github.com/fastapi/fastapi/pull/13460) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/header-param-models.md` page. PR [#13461](https://github.com/fastapi/fastapi/pull/13461) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Japanese translation for `docs/ja/docs/virtual-environments.md`. PR [#13304](https://github.com/fastapi/fastapi/pull/13304) by [@k94-ishi](https://github.com/k94-ishi). * 🌐 Add Korean translation for `docs/ko/docs/tutorial/security/oauth2-jwt.md`. PR [#13333](https://github.com/fastapi/fastapi/pull/13333) by [@yes0ng](https://github.com/yes0ng). From 8557a88d169a7981fb18aff10160517ea1338cf4 Mon Sep 17 00:00:00 2001 From: Valentyn Date: Wed, 19 Mar 2025 13:04:17 -0400 Subject: [PATCH 914/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/tutorial/response-status-code.md`?= =?UTF-8?q?=20page=20(#13462)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/uk/docs/tutorial/response-status-code.md | 100 ++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 docs/uk/docs/tutorial/response-status-code.md diff --git a/docs/uk/docs/tutorial/response-status-code.md b/docs/uk/docs/tutorial/response-status-code.md new file mode 100644 index 000000000..1ed69d6f2 --- /dev/null +++ b/docs/uk/docs/tutorial/response-status-code.md @@ -0,0 +1,100 @@ +# Статус коди Відповідей + +Так само як Ви можете вказати модель відповіді, Ви також можете оголосити HTTP код статусу для відповіді за допомогою параметра `status_code` в будь-якій з *операцій шляху*: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* тощо. + +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} + +/// note | Нотатка + +Зверніть увагу, що `status_code` є параметром методу "декоратора" (`get`, `post` і т.д.), а не Вашої *функції операції шляху*, як усі інші параметри та тіло запиту. + +/// + +Параметр `status_code` приймає число, яке відповідає HTTP коду статусу. + +/// info | Інформація +`status_code` також може отримувати значення з `IntEnum`, наприклад, з Python `http.HTTPStatus`. + +/// + +Він буде: + +* Повертати вказаний код статусу у відповіді. +* Документувати його як такий у схемі OpenAPI (і, таким чином, в інтерфейсі користувача): + + + +/// note | Нотатка + +Деякі коди відповіді (див. наступний розділ) вказують, що відповідь не має тіла. + +FastAPI знає про це і створить OpenAPI документацію, яка вказує, що тіла відповіді немає. + +/// + +## Про HTTP статус коди + +/// note | Нотатка + +Якщо Ви вже знаєте, що таке HTTP коди статусу, переходьте до наступного розділу. + +/// + +В HTTP Ви надсилаєте числовий код статусу з 3 цифр як частину відповіді. + +Ці коди статусу мають пов’язану назву для їх розпізнавання, але найважливішою частиною є саме число. + +Коротко: + +* **`100 - 199`** "Інформаційні" відповіді. Ви рідко використовуєте їх напряму. Відповіді з такими кодами не можуть мати тіла. +* **`200 - 299`** "Успішні" відповіді. Це ті, які Ви використовуватимете найчастіше. + * `200` - код за замовчуванням, який означає, що все пройшло "OK". + * Інший приклад – `201`, "Created" (створено). Його зазвичай використовують після створення нового запису в базі даних. + * Особливий випадок – `204`, "No Content" (немає вмісту). Ця відповідь використовується, коли немає даних для повернення клієнту, тому відповідь не повинна мати тіла. +* **`300 - 399`** "Перенаправлення". Відповіді з цими кодами можуть мати або не мати тіла, за винятком `304`, "Not Modified" (не змінено), яка не повинна мати тіла. +* **`400 - 499`** "Помилка клієнта". Це другий тип, який Ви, ймовірно, будете використовувати найчастіше. + * Приклад `404`, "Not Found" (не знайдено). + * Для загальних помилок клієнта можна використовувати `400`. +* `500 - 599` "Помилки сервера". Ви майже ніколи не використовуєте їх напряму. Якщо в коді Вашого застосунку або на сервері щось пішло не так, автоматично буде повернено один із цих кодів статусу. + +/// tip | Порада + +Щоб дізнатися більше про кожен код статусу і призначення кожного з них, перегляньте документацію MDN про HTTP коди статусу. + +/// + +## Легкий спосіб запам'ятати назви + +Розглянемо ще раз попередній приклад: + +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} + +`201` - це код статусу для "Created" (створено). + +Але Вам не потрібно запам'ятовувати, що означає кожен із цих кодів. + +Ви можете використовувати зручні змінні з `fastapi.status` + +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} + +Ці змінні просто для зручності. Вони містять ті ж самі числа, але Ви можете скористатися автозаповненням в редакторі: + + + +/// note | Технічні деталі + +Ви також можете використати `from starlette import status`. + +**FastAPI** надає ті ж самі змінні `starlette.status` як `fastapi.status`, просто для зручності розробника. Однак вони походять безпосередньо зі Starlette. + +/// + +## Зміна значення за замовчуванням + +Далі, у Посібнику для досвідчених користувачів{.internal-link target=_blank}, Ви дізнаєтесь, як повернути інший код статусу, ніж той, який Ви оголосили тут. From 3afd733753ba2dc51eb141d1b0d2bf4b2bf8f4f3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 19 Mar 2025 17:04:51 +0000 Subject: [PATCH 915/932] =?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 [skip ci] --- 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 f63d240fe..d9a1f5ac1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/response-status-code.md` page. PR [#13462](https://github.com/fastapi/fastapi/pull/13462) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/cookie-param-models.md` page. PR [#13460](https://github.com/fastapi/fastapi/pull/13460) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/header-param-models.md` page. PR [#13461](https://github.com/fastapi/fastapi/pull/13461) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Japanese translation for `docs/ja/docs/virtual-environments.md`. PR [#13304](https://github.com/fastapi/fastapi/pull/13304) by [@k94-ishi](https://github.com/k94-ishi). From ecf6e7eec292122ac33a8d96c2c8bff94fa597f4 Mon Sep 17 00:00:00 2001 From: Valentyn Date: Wed, 19 Mar 2025 13:09:57 -0400 Subject: [PATCH 916/932] =?UTF-8?q?=F0=9F=8C=90=20Add=20Ukrainian=20transl?= =?UTF-8?q?ation=20for=20`docs/uk/docs/tutorial/metadata.md`=20page=20(#13?= =?UTF-8?q?459)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/uk/docs/tutorial/metadata.md | 120 ++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 docs/uk/docs/tutorial/metadata.md diff --git a/docs/uk/docs/tutorial/metadata.md b/docs/uk/docs/tutorial/metadata.md new file mode 100644 index 000000000..64e667ec6 --- /dev/null +++ b/docs/uk/docs/tutorial/metadata.md @@ -0,0 +1,120 @@ +# Метадані та URL-адреси документації + +Ви можете налаштувати кілька конфігурацій метаданих у Вашому додатку **FastAPI**. + +## Метадані для API + +Ви можете встановити такі поля, які використовуються в специфікації OpenAPI та в автоматично згенерованих інтерфейсах документації API: + +| Параметр | Тип | Опис | +|------------|------|-------------| +| `title` | `str` | Назва API. | +| `summary` | `str` | Короткий опис API. Доступно з OpenAPI 3.1.0, FastAPI 0.99.0. | +| `description` | `str` | Більш детальний опис API. Може використовувати Markdown. | +| `version` | `string` | Версія API. Це версія Вашого додатка, а не OpenAPI. Наприклад, `2.5.0`. | +| `terms_of_service` | `str` | URL до умов використання API. Якщо вказано, має бути у форматі URL. | +| `contact` | `dict` | Інформація для контакту з API. Може містити кілька полів.
    contact поля
    ПараметрТипОпис
    namestrІм'я контактної особи або організації.
    urlstrURL з інформацією для контакту. Повинен бути у форматі URL.
    emailstrEmail контактної особи або організації. Повинен бути у форматі електронної пошти.
    | +| `license_info` | `dict` | Інформація про ліцензію для API. Може містити кілька полів.
    license_info поля
    ПараметрТипОпис
    namestrОБОВ'ЯЗКОВО (якщо встановлено license_info). Назва ліцензії для API.
    identifierstrЛіцензійний вираз за SPDX для API. Поле identifier взаємовиключне з полем url. Доступно з OpenAPI 3.1.0, FastAPI 0.99.0.
    urlstrURL до ліцензії, яка використовується для API. Повинен бути у форматі URL.
    | + +Ви можете налаштувати їх наступним чином: + +{* ../../docs_src/metadata/tutorial001.py hl[3:16, 19:32] *} + +/// tip | Підказка + +У полі `description` можна використовувати Markdown, і він буде відображатися у результаті. + +/// + +З цією конфігурацією автоматична документація API виглядатиме так: + + + +## Ідентифікатор ліцензії + +З початку використання OpenAPI 3.1.0 та FastAPI 0.99.0 Ви також можете налаштувати `license_info` за допомогою `identifier` замість `url`. + +Наприклад: + +{* ../../docs_src/metadata/tutorial001_1.py hl[31] *} + +## Метадані для тегів + +Ви також можете додати додаткові метадані для різних тегів, які використовуються для групування операцій шляхів, за допомогою параметра `openapi_tags`. + +Він приймає список, який містить один словник для кожного тега. + +Кожен словник може містити: + +* `name` (**обов'язково**): `str` з тією ж назвою тегу, яку Ви використовуєте у параметрі `tags` у Ваших *операціях шляху* та `APIRouter`s. +* `description`: `str` з коротким описом тегу. Може містити Markdown і буде відображено в інтерфейсі документації. +* `externalDocs`: `dict` який описує зовнішню документацію з такими полями: + * `description`: `str` з коротким описом зовнішньої документації. + * `url` (**обов'язково**): `str`з URL-адресою зовнішньої документації. + +### Створення метаданих для тегів + +Спробуймо це на прикладі з тегами для `users` та `items`. + +Створіть метадані для своїх тегів і передайте їх у параметр `openapi_tags`: + +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} + +Зверніть увагу, що в описах можна використовувати Markdown, наприклад, "login" буде показано жирним шрифтом (**login**), а "fancy" буде показано курсивом (_fancy_). + +/// tip | Порада + +Не обов'язково додавати метадані для всіх тегів, які Ви використовуєте. + +/// + +### Використання тегів + +Використовуйте параметр `tags` зі своїми *операціями шляху* (і `APIRouter`) для призначення їх до різних тегів: + +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} + +/// info | Інформація + +Детальніше про теги читайте в розділі [Конфігурація шляхів операцій](path-operation-configuration.md#tags){.internal-link target=_blank}. + +/// + +### Перевірка документації + +Якщо Ви зараз перевірите документацію, вона покаже всі додаткові метадані: + + + +### Порядок тегів + +Порядок кожного словника метаданих тегу також визначає порядок відображення в інтерфейсі документації. + +Наприклад, хоча `users` мав би йти після `items` в алфавітному порядку, він відображається перед ними, оскільки ми додали його метадані як перший словник у списку. + +## URL для OpenAPI + +За замовчуванням схема OpenAPI надається за адресою `/openapi.json`. + +Але Ви можете налаштувати це за допомогою параметра `openapi_url`. + +Наприклад, щоб налаштувати його на `/api/v1/openapi.json`: + +{* ../../docs_src/metadata/tutorial002.py hl[3] *} + +Якщо Ви хочете повністю вимкнути схему OpenAPI, Ви можете встановити `openapi_url=None`, це також вимкне інтерфейси документації, які її використовують. + +## URL-адреси документації + +Ви можете налаштувати два інтерфейси користувача для документації, які включені: + +* **Swagger UI**: доступний за адресою `/docs`. + * Ви можете змінити його URL за допомогою параметра `docs_url`. + * Ви можете вимкнути його, встановивши `docs_url=None`. +* **ReDoc**: доступний за адресою `/redoc`. + * Ви можете змінити його URL за допомогою параметра `redoc_url`. + * Ви можете вимкнути його, встановивши `redoc_url=None`. + +Наприклад, щоб налаштувати Swagger UI на `/documentation` і вимкнути ReDoc: + +{* ../../docs_src/metadata/tutorial003.py hl[3] *} From 4e40e1e85d2e62375f79ee726a8448539d503030 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 19 Mar 2025 17:10:19 +0000 Subject: [PATCH 917/932] =?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 [skip ci] --- 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 d9a1f5ac1..009705cdd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -13,6 +13,7 @@ hide: ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/metadata.md` page. PR [#13459](https://github.com/fastapi/fastapi/pull/13459) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/response-status-code.md` page. PR [#13462](https://github.com/fastapi/fastapi/pull/13462) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/cookie-param-models.md` page. PR [#13460](https://github.com/fastapi/fastapi/pull/13460) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/header-param-models.md` page. PR [#13461](https://github.com/fastapi/fastapi/pull/13461) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). From 241de23b68664a45d07534513bc2dfb0191ba24f Mon Sep 17 00:00:00 2001 From: Rishat-F <66554797+Rishat-F@users.noreply.github.com> Date: Thu, 20 Mar 2025 15:29:48 +0300 Subject: [PATCH 918/932] =?UTF-8?q?=F0=9F=93=9D=20Update=20`docs/en/docs/t?= =?UTF-8?q?utorial/middleware.md`=20(#13444)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com> --- docs/en/docs/tutorial/middleware.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index 53c47a085..4f7980165 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -15,7 +15,7 @@ A "middleware" is a function that works with every **request** before it is proc If you have dependencies with `yield`, the exit code will run *after* the middleware. -If there were any background tasks (documented later), they will run *after* all the middleware. +If there were any background tasks (covered in the [Background Tasks](background-tasks.md){.internal-link target=_blank} section, you will see it later), they will run *after* all the middleware. /// From c08a3e8f2250cc84032e4261a18ec717de74d0c7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 20 Mar 2025 12:30:17 +0000 Subject: [PATCH 919/932] =?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 [skip ci] --- 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 009705cdd..5410c75b8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update `docs/en/docs/tutorial/middleware.md`. PR [#13444](https://github.com/fastapi/fastapi/pull/13444) by [@Rishat-F](https://github.com/Rishat-F). * 👥 Update FastAPI People - Experts. PR [#13493](https://github.com/fastapi/fastapi/pull/13493) by [@tiangolo](https://github.com/tiangolo). ### Translations From 2537d9d1c2517f9e552ca2b076b3b63b1acbc55d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 23 Mar 2025 20:48:54 +0000 Subject: [PATCH 920/932] =?UTF-8?q?=F0=9F=90=9B=20Fix=20`convert=5Fundersc?= =?UTF-8?q?ores=3DFalse`=20for=20header=20Pydantic=20models=20(#13515)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/header-param-models.md | 16 + docs_src/header_param_models/tutorial003.py | 19 ++ .../header_param_models/tutorial003_an.py | 22 ++ .../tutorial003_an_py310.py | 21 ++ .../tutorial003_an_py39.py | 21 ++ .../header_param_models/tutorial003_py310.py | 17 ++ .../header_param_models/tutorial003_py39.py | 19 ++ fastapi/dependencies/utils.py | 10 +- fastapi/openapi/utils.py | 23 +- .../test_tutorial001.py | 6 +- .../test_tutorial002.py | 6 +- .../test_tutorial003.py | 285 ++++++++++++++++++ 12 files changed, 457 insertions(+), 8 deletions(-) create mode 100644 docs_src/header_param_models/tutorial003.py create mode 100644 docs_src/header_param_models/tutorial003_an.py create mode 100644 docs_src/header_param_models/tutorial003_an_py310.py create mode 100644 docs_src/header_param_models/tutorial003_an_py39.py create mode 100644 docs_src/header_param_models/tutorial003_py310.py create mode 100644 docs_src/header_param_models/tutorial003_py39.py create mode 100644 tests/test_tutorial/test_header_param_models/test_tutorial003.py diff --git a/docs/en/docs/tutorial/header-param-models.md b/docs/en/docs/tutorial/header-param-models.md index 73950a668..4cdf09705 100644 --- a/docs/en/docs/tutorial/header-param-models.md +++ b/docs/en/docs/tutorial/header-param-models.md @@ -51,6 +51,22 @@ For example, if the client tries to send a `tool` header with a value of `plumbu } ``` +## Disable Convert Underscores + +The same way as with regular header parameters, when you have underscore characters in the parameter names, they are **automatically converted to hyphens**. + +For example, if you have a header parameter `save_data` in the code, the expected HTTP header will be `save-data`, and it will show up like that in the docs. + +If for some reason you need to disable this automatic conversion, you can do it as well for Pydantic models for header parameters. + +{* ../../docs_src/header_param_models/tutorial003_an_py310.py hl[19] *} + +/// warning + +Before setting `convert_underscores` to `False`, bear in mind that some HTTP proxies and servers disallow the usage of headers with underscores. + +/// + ## Summary You can use **Pydantic models** to declare **headers** in **FastAPI**. 😎 diff --git a/docs_src/header_param_models/tutorial003.py b/docs_src/header_param_models/tutorial003.py new file mode 100644 index 000000000..dc2eb74bd --- /dev/null +++ b/docs_src/header_param_models/tutorial003.py @@ -0,0 +1,19 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header(convert_underscores=False)): + return headers diff --git a/docs_src/header_param_models/tutorial003_an.py b/docs_src/header_param_models/tutorial003_an.py new file mode 100644 index 000000000..e3edb1189 --- /dev/null +++ b/docs_src/header_param_models/tutorial003_an.py @@ -0,0 +1,22 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items( + headers: Annotated[CommonHeaders, Header(convert_underscores=False)], +): + return headers diff --git a/docs_src/header_param_models/tutorial003_an_py310.py b/docs_src/header_param_models/tutorial003_an_py310.py new file mode 100644 index 000000000..07bfa83bf --- /dev/null +++ b/docs_src/header_param_models/tutorial003_an_py310.py @@ -0,0 +1,21 @@ +from typing import Annotated + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items( + headers: Annotated[CommonHeaders, Header(convert_underscores=False)], +): + return headers diff --git a/docs_src/header_param_models/tutorial003_an_py39.py b/docs_src/header_param_models/tutorial003_an_py39.py new file mode 100644 index 000000000..8be6b01d0 --- /dev/null +++ b/docs_src/header_param_models/tutorial003_an_py39.py @@ -0,0 +1,21 @@ +from typing import Annotated, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items( + headers: Annotated[CommonHeaders, Header(convert_underscores=False)], +): + return headers diff --git a/docs_src/header_param_models/tutorial003_py310.py b/docs_src/header_param_models/tutorial003_py310.py new file mode 100644 index 000000000..65e92a28c --- /dev/null +++ b/docs_src/header_param_models/tutorial003_py310.py @@ -0,0 +1,17 @@ +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header(convert_underscores=False)): + return headers diff --git a/docs_src/header_param_models/tutorial003_py39.py b/docs_src/header_param_models/tutorial003_py39.py new file mode 100644 index 000000000..848c34111 --- /dev/null +++ b/docs_src/header_param_models/tutorial003_py39.py @@ -0,0 +1,19 @@ +from typing import Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header(convert_underscores=False)): + return headers diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index d205d17fa..84dfa4d03 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -750,9 +750,15 @@ def request_params_to_args( first_field = fields[0] fields_to_extract = fields single_not_embedded_field = False + default_convert_underscores = True if len(fields) == 1 and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_cached_model_fields(first_field.type_) single_not_embedded_field = True + # If headers are in a Pydantic model, the way to disable convert_underscores + # would be with Header(convert_underscores=False) at the Pydantic model level + default_convert_underscores = getattr( + first_field.field_info, "convert_underscores", True + ) params_to_process: Dict[str, Any] = {} @@ -763,7 +769,9 @@ def request_params_to_args( if isinstance(received_params, Headers): # Handle fields extracted from a Pydantic Model for a header, each field # doesn't have a FieldInfo of type Header with the default convert_underscores=True - convert_underscores = getattr(field.field_info, "convert_underscores", True) + convert_underscores = getattr( + field.field_info, "convert_underscores", default_convert_underscores + ) if convert_underscores: alias = ( field.alias diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py index bd8f3c106..808646cc2 100644 --- a/fastapi/openapi/utils.py +++ b/fastapi/openapi/utils.py @@ -32,6 +32,7 @@ from fastapi.utils import ( generate_operation_id_for_path, is_body_allowed_for_status_code, ) +from pydantic import BaseModel from starlette.responses import JSONResponse from starlette.routing import BaseRoute from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY @@ -113,6 +114,13 @@ def _get_openapi_operation_parameters( (ParamTypes.header, header_params), (ParamTypes.cookie, cookie_params), ] + default_convert_underscores = True + if len(flat_dependant.header_params) == 1: + first_field = flat_dependant.header_params[0] + if lenient_issubclass(first_field.type_, BaseModel): + default_convert_underscores = getattr( + first_field.field_info, "convert_underscores", True + ) for param_type, param_group in parameter_groups: for param in param_group: field_info = param.field_info @@ -126,8 +134,21 @@ def _get_openapi_operation_parameters( field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) + name = param.alias + convert_underscores = getattr( + param.field_info, + "convert_underscores", + default_convert_underscores, + ) + if ( + param_type == ParamTypes.header + and param.alias == param.name + and convert_underscores + ): + name = param.name.replace("_", "-") + parameter = { - "name": param.alias, + "name": name, "in": param_type.value, "required": param.required, "schema": param_schema, diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial001.py b/tests/test_tutorial/test_header_param_models/test_tutorial001.py index 06b2404cf..bc876897b 100644 --- a/tests/test_tutorial/test_header_param_models/test_tutorial001.py +++ b/tests/test_tutorial/test_header_param_models/test_tutorial001.py @@ -129,13 +129,13 @@ def test_openapi_schema(client: TestClient): "schema": {"type": "string", "title": "Host"}, }, { - "name": "save_data", + "name": "save-data", "in": "header", "required": True, "schema": {"type": "boolean", "title": "Save Data"}, }, { - "name": "if_modified_since", + "name": "if-modified-since", "in": "header", "required": False, "schema": IsDict( @@ -171,7 +171,7 @@ def test_openapi_schema(client: TestClient): ), }, { - "name": "x_tag", + "name": "x-tag", "in": "header", "required": False, "schema": { diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial002.py b/tests/test_tutorial/test_header_param_models/test_tutorial002.py index e07655a0c..0615521c4 100644 --- a/tests/test_tutorial/test_header_param_models/test_tutorial002.py +++ b/tests/test_tutorial/test_header_param_models/test_tutorial002.py @@ -140,13 +140,13 @@ def test_openapi_schema(client: TestClient): "schema": {"type": "string", "title": "Host"}, }, { - "name": "save_data", + "name": "save-data", "in": "header", "required": True, "schema": {"type": "boolean", "title": "Save Data"}, }, { - "name": "if_modified_since", + "name": "if-modified-since", "in": "header", "required": False, "schema": IsDict( @@ -182,7 +182,7 @@ def test_openapi_schema(client: TestClient): ), }, { - "name": "x_tag", + "name": "x-tag", "in": "header", "required": False, "schema": { diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial003.py b/tests/test_tutorial/test_header_param_models/test_tutorial003.py new file mode 100644 index 000000000..60940e1da --- /dev/null +++ b/tests/test_tutorial/test_header_param_models/test_tutorial003.py @@ -0,0 +1,285 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial003", + pytest.param("tutorial003_py39", marks=needs_py39), + pytest.param("tutorial003_py310", marks=needs_py310), + "tutorial003_an", + pytest.param("tutorial003_an_py39", marks=needs_py39), + pytest.param("tutorial003_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.header_param_models.{request.param}") + + client = TestClient(mod.app) + return client + + +def test_header_param_model(client: TestClient): + response = client.get( + "/items/", + headers=[ + ("save_data", "true"), + ("if_modified_since", "yesterday"), + ("traceparent", "123"), + ("x_tag", "one"), + ("x_tag", "two"), + ], + ) + assert response.status_code == 200 + assert response.json() == { + "host": "testserver", + "save_data": True, + "if_modified_since": "yesterday", + "traceparent": "123", + "x_tag": ["one", "two"], + } + + +def test_header_param_model_no_underscore(client: TestClient): + response = client.get( + "/items/", + headers=[ + ("save-data", "true"), + ("if-modified-since", "yesterday"), + ("traceparent", "123"), + ("x-tag", "one"), + ("x-tag", "two"), + ], + ) + assert response.status_code == 422 + assert response.json() == snapshot( + { + "detail": [ + IsDict( + { + "type": "missing", + "loc": ["header", "save_data"], + "msg": "Field required", + "input": { + "host": "testserver", + "traceparent": "123", + "x_tag": [], + "accept": "*/*", + "accept-encoding": "gzip, deflate", + "connection": "keep-alive", + "user-agent": "testclient", + "save-data": "true", + "if-modified-since": "yesterday", + "x-tag": "two", + }, + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "value_error.missing", + "loc": ["header", "save_data"], + "msg": "field required", + } + ) + ] + } + ) + + +def test_header_param_model_defaults(client: TestClient): + response = client.get("/items/", headers=[("save_data", "true")]) + assert response.status_code == 200 + assert response.json() == { + "host": "testserver", + "save_data": True, + "if_modified_since": None, + "traceparent": None, + "x_tag": [], + } + + +def test_header_param_model_invalid(client: TestClient): + response = client.get("/items/") + assert response.status_code == 422 + assert response.json() == snapshot( + { + "detail": [ + IsDict( + { + "type": "missing", + "loc": ["header", "save_data"], + "msg": "Field required", + "input": { + "x_tag": [], + "host": "testserver", + "accept": "*/*", + "accept-encoding": "gzip, deflate", + "connection": "keep-alive", + "user-agent": "testclient", + }, + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "value_error.missing", + "loc": ["header", "save_data"], + "msg": "field required", + } + ) + ] + } + ) + + +def test_header_param_model_extra(client: TestClient): + response = client.get( + "/items/", headers=[("save_data", "true"), ("tool", "plumbus")] + ) + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "host": "testserver", + "save_data": True, + "if_modified_since": None, + "traceparent": None, + "x_tag": [], + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "host", + "in": "header", + "required": True, + "schema": {"type": "string", "title": "Host"}, + }, + { + "name": "save_data", + "in": "header", + "required": True, + "schema": {"type": "boolean", "title": "Save Data"}, + }, + { + "name": "if_modified_since", + "in": "header", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "If Modified Since", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "If Modified Since", + } + ), + }, + { + "name": "traceparent", + "in": "header", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Traceparent", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Traceparent", + } + ), + }, + { + "name": "x_tag", + "in": "header", + "required": False, + "schema": { + "type": "array", + "items": {"type": "string"}, + "default": [], + "title": "X Tag", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) From 8e76d4e5f4ee2e4b9f77378a39aa15940255e164 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 23 Mar 2025 20:49:19 +0000 Subject: [PATCH 921/932] =?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 [skip ci] --- 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 5410c75b8..9d4bd3301 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Fixes + +* 🐛 Fix `convert_underscores=False` for header Pydantic models. PR [#13515](https://github.com/fastapi/fastapi/pull/13515) by [@tiangolo](https://github.com/tiangolo). + ### Docs * 📝 Update `docs/en/docs/tutorial/middleware.md`. PR [#13444](https://github.com/fastapi/fastapi/pull/13444) by [@Rishat-F](https://github.com/Rishat-F). From 628c34e0cae200564d191c95d7edea78c88c4b5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 23 Mar 2025 23:54:13 +0100 Subject: [PATCH 922/932] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.11?= =?UTF-8?q?5.12?= 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 9d4bd3301..7e54dd7d6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.115.12 + ### Fixes * 🐛 Fix `convert_underscores=False` for header Pydantic models. PR [#13515](https://github.com/fastapi/fastapi/pull/13515) by [@tiangolo](https://github.com/tiangolo). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 757b76106..80eb783da 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.11" +__version__ = "0.115.12" from starlette import status as status From d70f0ecec3d537b903b5c663c4fc3fcc9269db84 Mon Sep 17 00:00:00 2001 From: Blueswen Date: Mon, 24 Mar 2025 19:12:43 +0800 Subject: [PATCH 923/932] =?UTF-8?q?=F0=9F=93=9D=20Add=20External=20Link:?= =?UTF-8?q?=20Taiwanese=20talk=20on=20FastAPI=20with=20observability=20=20?= =?UTF-8?q?(#13527)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/external_links.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index 9e411a631..00bb55422 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -411,3 +411,8 @@ Talks: author_link: https://twitter.com/chriswithers13 link: https://www.youtube.com/watch?v=3DLwPcrE5mA title: 'PyCon UK 2019: FastAPI from the ground up' + Taiwanese: + - author: Bluewen + author_link: https://github.com/blueswen + link: https://www.youtube.com/watch?v=y3sumuoDq4w + title: 'PyCon TW 2024: 全方位強化 Python 服務可觀測性:以 FastAPI 和 Grafana Stack 為例' From cbd7d4895b0a88802f50cd5c6fb05c1ffcb417e7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 24 Mar 2025 11:13:09 +0000 Subject: [PATCH 924/932] =?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 [skip ci] --- 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 7e54dd7d6..d09b7c0a0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Add External Link: Taiwanese talk on FastAPI with observability . PR [#13527](https://github.com/fastapi/fastapi/pull/13527) by [@blueswen](https://github.com/blueswen). + ## 0.115.12 ### Fixes From f0d59e57f10e4592f43e11ddca3640791140016c Mon Sep 17 00:00:00 2001 From: Zhongheng Cheng Date: Mon, 24 Mar 2025 17:09:43 -0400 Subject: [PATCH 925/932] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/tutorial/first-steps.md`=20(#13348?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/first-steps.md | 95 ++++++++++++---------------- 1 file changed, 41 insertions(+), 54 deletions(-) diff --git a/docs/zh/docs/tutorial/first-steps.md b/docs/zh/docs/tutorial/first-steps.md index c4ff460e0..80a34116a 100644 --- a/docs/zh/docs/tutorial/first-steps.md +++ b/docs/zh/docs/tutorial/first-steps.md @@ -11,26 +11,42 @@
    ```console -$ uvicorn main:app --reload +$ fastapi dev main.py -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] -INFO: Waiting for application startup. -INFO: Application startup complete. -``` + FastAPI Starting development server 🚀 -
    + Searching for package file structure from directories + with __init__.py files + Importing from /home/user/code/awesomeapp -/// note + module 🐍 main.py -`uvicorn main:app` 命令含义如下: + code Importing the FastAPI app object from the module with + the following code: -* `main`:`main.py` 文件(一个 Python「模块」)。 -* `app`:在 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。 -* `--reload`:让服务器在更新代码后重新启动。仅在开发时使用该选项。 + from main import app -/// + app Using import string: main:app + + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: + + 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 [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. +``` + + 在输出中,会有一行信息像下面这样: @@ -38,7 +54,6 @@ $ uvicorn main:app --reload INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` - 该行显示了你的应用在本机所提供服务的 URL 地址。 ### 查看 @@ -63,7 +78,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) 前往 http://127.0.0.1:8000/redoc。 -你将会看到可选的自动生成文档 (由 ReDoc 提供): +你将会看到可选的自动生成文档 (由 ReDoc 提供): ![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) @@ -77,9 +92,9 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) #### API「模式」 -在这种场景下,OpenAPI 是一种规定如何定义 API 模式的规范。 +在这种场景下,OpenAPI 是一种规定如何定义 API 模式的规范。 -定义的 OpenAPI 模式将包括你的 API 路径,以及它们可能使用的参数等等。 +「模式」的定义包括你的 API 路径,以及它们可能使用的参数等等。 #### 数据「模式」 @@ -93,7 +108,7 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送 #### 查看 `openapi.json` -如果你对原始的 OpenAPI 模式长什么样子感到好奇,其实它只是一个自动生成的包含了所有 API 描述的 JSON。 +如果你对原始的 OpenAPI 模式长什么样子感到好奇,FastAPI 自动生成了包含所有 API 描述的 JSON(模式)。 你可以直接在:http://127.0.0.1:8000/openapi.json 看到它。 @@ -101,7 +116,7 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送 ```JSON { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": { "title": "FastAPI", "version": "0.1.0" @@ -140,7 +155,7 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送 `FastAPI` 是直接从 `Starlette` 继承的类。 -你可以通过 `FastAPI` 使用所有的 Starlette 的功能。 +你可以通过 `FastAPI` 使用所有的 Starlette 的功能。 /// @@ -152,34 +167,6 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送 这个实例将是创建你所有 API 的主要交互对象。 -这个 `app` 同样在如下命令中被 `uvicorn` 所引用: - -
    - -```console -$ uvicorn main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
    - -如果你像下面这样创建应用: - -{* ../../docs_src/first_steps/tutorial002.py hl[3] *} - -将代码放入 `main.py` 文件中,然后你可以像下面这样运行 `uvicorn`: - -
    - -```console -$ uvicorn main:my_awesome_api --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
    - ### 步骤 3:创建一个*路径操作* #### 路径 @@ -279,13 +266,13 @@ https://example.com/items/foo /// tip -您可以随意使用任何一个操作(HTTP方法)。 +你可以随意使用任何一个操作(HTTP方法)。 **FastAPI** 没有强制要求操作有任何特定的含义。 此处提供的信息仅作为指导,而不是要求。 -比如,当使用 GraphQL 时通常你所有的动作都通过 `post` 一种方法执行。 +比如,当使用 GraphQL 时通常你所有的动作都通过 `POST` 一种方法执行。 /// @@ -331,6 +318,6 @@ https://example.com/items/foo * 导入 `FastAPI`。 * 创建一个 `app` 实例。 -* 编写一个**路径操作装饰器**(如 `@app.get("/")`)。 -* 编写一个**路径操作函数**(如上面的 `def root(): ...`)。 -* 运行开发服务器(如 `uvicorn main:app --reload`)。 +* 编写一个**路径操作装饰器**,如 `@app.get("/")`。 +* 定义一个**路径操作函数**,如 `def root(): ...`。 +* 使用命令 `fastapi dev` 运行开发服务器。 From b58c2a31ed5eeaf0b0ca937fbd932044cd2cbf23 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 24 Mar 2025 21:10:05 +0000 Subject: [PATCH 926/932] =?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 [skip ci] --- 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 d09b7c0a0..4704bd53f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -11,6 +11,10 @@ hide: * 📝 Add External Link: Taiwanese talk on FastAPI with observability . PR [#13527](https://github.com/fastapi/fastapi/pull/13527) by [@blueswen](https://github.com/blueswen). +### Translations + +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/first-steps.md`. PR [#13348](https://github.com/fastapi/fastapi/pull/13348) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). + ## 0.115.12 ### Fixes From c12652b7858e70e57c6e65e264d1547a07ef2769 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 26 Mar 2025 14:18:42 +0100 Subject: [PATCH 927/932] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#12986)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ⬆ [pre-commit.ci] pre-commit autoupdate updates: - [github.com/astral-sh/ruff-pre-commit: v0.9.4 → v0.11.2](https://github.com/astral-sh/ruff-pre-commit/compare/v0.9.4...v0.11.2) * also bump in doc requirements --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: svlandeg Co-authored-by: Sofie Van Landeghem --- .pre-commit-config.yaml | 2 +- requirements-docs-tests.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 05c33a608..6aa7c458d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.9.4 + rev: v0.11.2 hooks: - id: ruff args: diff --git a/requirements-docs-tests.txt b/requirements-docs-tests.txt index e7718e61d..71f4a7ab9 100644 --- a/requirements-docs-tests.txt +++ b/requirements-docs-tests.txt @@ -1,4 +1,4 @@ # For mkdocstrings and tests httpx >=0.23.0,<0.28.0 # For linting and generating docs versions -ruff ==0.9.4 +ruff ==0.11.2 From c8a7552e29e369e4e52957d72c8dcbde605c56d6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 26 Mar 2025 13:19:03 +0000 Subject: [PATCH 928/932] =?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 [skip ci] --- 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 4704bd53f..e3a703ef9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -15,6 +15,10 @@ hide: * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/first-steps.md`. PR [#13348](https://github.com/fastapi/fastapi/pull/13348) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). +### Internal + +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12986](https://github.com/fastapi/fastapi/pull/12986) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). + ## 0.115.12 ### Fixes From 031622a989833e9842d1200ab18088ef61424fc3 Mon Sep 17 00:00:00 2001 From: Sofie Van Landeghem Date: Wed, 26 Mar 2025 15:38:36 +0100 Subject: [PATCH 929/932] =?UTF-8?q?=F0=9F=94=A7=20Clean=20up=20`docs/en/mk?= =?UTF-8?q?docs.yml`=20configuration=20file=20(#13542)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/mkdocs.yml | 76 ++++++++++++++++------------------------------ 1 file changed, 26 insertions(+), 50 deletions(-) diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index e9a639d0b..bfa88c06e 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -6,7 +6,7 @@ theme: name: material custom_dir: ../en/overrides palette: - - media: "(prefers-color-scheme)" + - media: (prefers-color-scheme) toggle: icon: material/lightbulb-auto name: Switch to light mode @@ -27,7 +27,6 @@ theme: features: - content.code.annotate - content.code.copy - # - content.code.select - content.footnote.tooltips - content.tabs.link - content.tooltips @@ -35,7 +34,6 @@ theme: - navigation.indexes - navigation.instant - navigation.instant.prefetch - # - navigation.instant.preview - navigation.instant.progress - navigation.path - navigation.tabs @@ -46,7 +44,6 @@ theme: - search.share - search.suggest - toc.follow - icon: repo: fontawesome/brands/github-alt logo: img/icon-white.svg @@ -55,11 +52,7 @@ theme: repo_name: fastapi/fastapi repo_url: https://github.com/fastapi/fastapi plugins: - # Material for MkDocs - search: - # Configured in mkdocs.insiders.yml - # social: - # Other plugins + search: null macros: include_yaml: - external_links: ../en/data/external_links.yml @@ -103,7 +96,6 @@ plugins: signature_crossrefs: true show_symbol_type_heading: true show_symbol_type_toc: true - nav: - FastAPI: index.md - features.md @@ -258,33 +250,27 @@ nav: - benchmarks.md - management.md - release-notes.md - markdown_extensions: - # Python Markdown - abbr: - attr_list: - footnotes: - md_in_html: - tables: + abbr: null + attr_list: null + footnotes: null + md_in_html: null + tables: null toc: permalink: true - - # Python Markdown Extensions - pymdownx.betterem: - pymdownx.caret: + pymdownx.betterem: null + pymdownx.caret: null pymdownx.highlight: line_spans: __span - pymdownx.inlinehilite: - pymdownx.keys: - pymdownx.mark: + pymdownx.inlinehilite: null + pymdownx.keys: null + pymdownx.mark: null pymdownx.superfences: custom_fences: - name: mermaid class: mermaid - format: !!python/name:pymdownx.superfences.fence_code_format - pymdownx.tilde: - - # pymdownx blocks + format: !!python/name:pymdownx.superfences.fence_code_format '' + pymdownx.tilde: null pymdownx.blocks.admonition: types: - note @@ -295,17 +281,13 @@ markdown_extensions: - tip - hint - warning - # Custom types - info - check - pymdownx.blocks.details: + pymdownx.blocks.details: null pymdownx.blocks.tab: - alternate_style: True - - # Other extensions - mdx_include: - markdown_include_variants: - + alternate_style: true + mdx_include: null + markdown_include_variants: null extra: analytics: provider: google @@ -313,16 +295,14 @@ extra: feedback: title: Was this page helpful? ratings: - - icon: material/emoticon-happy-outline - name: This page was helpful - data: 1 - note: >- - Thanks for your feedback! - - icon: material/emoticon-sad-outline - name: This page could be improved - data: 0 - note: >- - Thanks for your feedback! + - icon: material/emoticon-happy-outline + name: This page was helpful + data: 1 + note: Thanks for your feedback! + - icon: material/emoticon-sad-outline + name: This page could be improved + data: 0 + note: Thanks for your feedback! social: - icon: fontawesome/brands/github-alt link: https://github.com/fastapi/fastapi @@ -338,7 +318,6 @@ extra: link: https://medium.com/@tiangolo - icon: fontawesome/solid/globe link: https://tiangolo.com - alternate: - link: / name: en - English @@ -390,14 +369,11 @@ extra: name: zh-hant - 繁體中文 - link: /em/ name: 😉 - extra_css: - css/termynal.css - css/custom.css - extra_javascript: - js/termynal.js - js/custom.js - hooks: - ../../scripts/mkdocs_hooks.py From b5bdc153a12716b45a55ff4b9a298a898d1502e0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 26 Mar 2025 14:39:00 +0000 Subject: [PATCH 930/932] =?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 [skip ci] --- 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 e3a703ef9..359ec4b49 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Internal +* 🔧 Clean up `docs/en/mkdocs.yml` configuration file. PR [#13542](https://github.com/fastapi/fastapi/pull/13542) by [@svlandeg](https://github.com/svlandeg). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12986](https://github.com/fastapi/fastapi/pull/12986) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). ## 0.115.12 From a49f69f074e334b0abf8cb4aeded213b9f371b9d Mon Sep 17 00:00:00 2001 From: Blueswen Date: Mon, 31 Mar 2025 03:23:32 +0800 Subject: [PATCH 931/932] =?UTF-8?q?=E2=9C=8F=EF=B8=8F=20Fix=20talk=20infor?= =?UTF-8?q?mation=20typo=20(#13544)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/external_links.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index 00bb55422..50f84ecbf 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -412,7 +412,7 @@ Talks: link: https://www.youtube.com/watch?v=3DLwPcrE5mA title: 'PyCon UK 2019: FastAPI from the ground up' Taiwanese: - - author: Bluewen + - author: Blueswen author_link: https://github.com/blueswen link: https://www.youtube.com/watch?v=y3sumuoDq4w title: 'PyCon TW 2024: 全方位強化 Python 服務可觀測性:以 FastAPI 和 Grafana Stack 為例' From 4db37fdf954f24bf8e91d141a0ad675fdd9c90c8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 30 Mar 2025 19:23:55 +0000 Subject: [PATCH 932/932] =?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 [skip ci] --- 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 359ec4b49..bc122be5d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* ✏️ Fix talk information typo. PR [#13544](https://github.com/fastapi/fastapi/pull/13544) by [@blueswen](https://github.com/blueswen). * 📝 Add External Link: Taiwanese talk on FastAPI with observability . PR [#13527](https://github.com/fastapi/fastapi/pull/13527) by [@blueswen](https://github.com/blueswen). ### Translations