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 001/405] =?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 002/405] =?UTF-8?q?=F0=9F=93=9D=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 003/405] =?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 004/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 005/405] =?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 006/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 007/405] =?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 008/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 009/405] =?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 010/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 011/405] =?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 012/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 013/405] =?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 014/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 015/405] =?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 016/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 017/405] =?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 018/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 019/405] =?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 020/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 021/405] =?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 022/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 023/405] =?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 024/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 025/405] =?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 026/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 027/405] =?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 028/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 029/405] =?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 030/405] =?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 031/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 032/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 033/405] =?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) +
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 034/405] =?UTF-8?q?=F0=9F=93=9D=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 035/405] =?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 036/405] =?UTF-8?q?=F0=9F=93=9D=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 037/405] =?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 038/405] =?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 039/405] =?UTF-8?q?=F0=9F=93=9D=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 040/405] =?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 041/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 042/405] =?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 043/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 044/405] =?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 045/405] =?UTF-8?q?=F0=9F=93=9D=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 046/405] =?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 047/405] =?UTF-8?q?=F0=9F=93=9D=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 048/405] =?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 049/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 050/405] =?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 051/405] =?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 052/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 053/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 054/405] =?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 055/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 056/405] =?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 057/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 058/405] =?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 059/405] =?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 060/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 061/405] =?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 062/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 063/405] =?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 064/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 065/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 066/405] =?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 067/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 068/405] =?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 069/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 070/405] =?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 071/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 072/405] =?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 073/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 074/405] =?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 075/405] =?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 076/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 077/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 078/405] =?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 079/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 080/405] =?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 081/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 082/405] =?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 083/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 084/405] =?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 085/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 086/405] =?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 087/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 088/405] =?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 089/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 090/405] =?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 091/405] =?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 092/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 093/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 094/405] =?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 095/405] =?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 096/405] =?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 097/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 098/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 099/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 100/405] =?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 101/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 102/405] =?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 103/405] =?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 104/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 105/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 106/405] =?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 107/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 108/405] =?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 109/405] =?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 110/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 111/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 112/405] =?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 113/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 114/405] =?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 115/405] =?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 116/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 117/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 118/405] =?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 119/405] =?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 120/405] =?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 121/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 122/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 123/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 124/405] =?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 125/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 126/405] =?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 127/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 128/405] =?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 129/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 130/405] =?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 131/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 132/405] =?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 133/405] =?UTF-8?q?=F0=9F=93=9D=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 134/405] =?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 135/405] =?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 136/405] =?UTF-8?q?=F0=9F=93=9D=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 137/405] =?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 138/405] =?UTF-8?q?=F0=9F=93=9D=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 139/405] =?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 140/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 141/405] =?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 142/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 143/405] =?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 144/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 145/405] =?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 146/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 147/405] =?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 148/405] =?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 149/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 150/405] =?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 151/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 152/405] =?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 153/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 154/405] =?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 155/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 156/405] =?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 157/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 158/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 159/405] =?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 160/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 161/405] =?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 162/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 163/405] =?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 164/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 165/405] =?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 166/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 167/405] =?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 168/405] =?UTF-8?q?=F0=9F=93=9D=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 169/405] =?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 170/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 171/405] =?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 172/405] =?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 173/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 174/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 175/405] =?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 176/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 177/405] =?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 178/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 179/405] =?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 180/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 181/405] =?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 182/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 183/405] =?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 184/405] =?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 185/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 186/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 187/405] =?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 188/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 189/405] =?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 190/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 191/405] =?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 192/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 193/405] =?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 194/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 195/405] =?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 196/405] =?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 197/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 198/405] =?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 199/405] =?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 200/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 201/405] =?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 202/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 203/405] =?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 204/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 205/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 206/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 207/405] =?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 208/405] =?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 209/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 210/405] =?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 211/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 212/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 213/405] =?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 214/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 215/405] =?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 216/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 217/405] =?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 218/405] =?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 219/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 220/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 221/405] =?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 222/405] =?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 223/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 224/405] =?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 225/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 226/405] =?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 227/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 228/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 229/405] =?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 230/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 231/405] =?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 232/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 233/405] =?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 234/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.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 235/405] =?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 236/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 237/405] =?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 238/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 239/405] =?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 240/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 241/405] =?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 242/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 243/405] =?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 244/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 245/405] =?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 246/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 247/405] =?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 248/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 249/405] =?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 250/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 251/405] =?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 252/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 253/405] =?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 254/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 255/405] =?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 256/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 257/405] =?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 258/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 259/405] =?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 260/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 261/405] =?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 262/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 263/405] =?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 264/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 265/405] =?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 266/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 267/405] =?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 268/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 269/405] =?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 270/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 271/405] =?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 272/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 273/405] =?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 274/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 275/405] =?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 276/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 277/405] =?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 278/405] =?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 279/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 280/405] =?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 281/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 282/405] =?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 283/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 284/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 285/405] =?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 286/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 287/405] =?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 288/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 289/405] =?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 290/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 291/405] =?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 292/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 293/405] =?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 294/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 295/405] =?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 296/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 297/405] =?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 298/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 299/405] =?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 300/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 301/405] =?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 302/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 303/405] =?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 304/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 305/405] =?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 306/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 307/405] =?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 308/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 309/405] =?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 310/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 311/405] =?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 312/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 313/405] =?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 314/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 315/405] =?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 316/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 317/405] =?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 318/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 319/405] =?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 320/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 321/405] =?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 322/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 323/405] =?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 324/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 325/405] =?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 326/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 327/405] =?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 328/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 329/405] =?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 330/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 331/405] =?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 332/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 333/405] =?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 334/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 335/405] =?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 336/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 337/405] =?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 338/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 339/405] =?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 340/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 341/405] =?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 342/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 343/405] =?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 344/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 345/405] =?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 346/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 347/405] =?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 348/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 349/405] =?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 350/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 351/405] =?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 352/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 353/405] =?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 354/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 355/405] =?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 356/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 357/405] =?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 358/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 359/405] =?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 360/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 361/405] =?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 362/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 363/405] =?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 364/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 365/405] =?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 366/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 367/405] =?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 368/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 369/405] =?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 370/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 371/405] =?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 372/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 373/405] =?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 374/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 375/405] =?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 376/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 377/405] =?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 378/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 379/405] =?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 380/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=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 381/405] =?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 382/405] =?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 383/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=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 384/405] =?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 385/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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 386/405] =?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 387/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=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 388/405] =?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 405/405] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.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).